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/5/0x0E841ae8f9CCDa3bDC14780216B974a477978Fec/sources/src/ERC721TL.sol | @inheritdoc StoryContractUpgradeable restricted to the owner of the contract | function _isStoryAdmin(address potentialAdmin) internal view override(StoryContractUpgradeable) returns (bool) {
return potentialAdmin == owner();
}
| 1,858,544 |
./full_match/5/0xB69deB097DeE5A0c880A6094478d20b56fAADd25/sources/contracts/Store.sol | Seller: Create a new product for sale Ensure that the seller has enough balance to sell Ensure that the value sent is equal to the price Ensure that the price is bigger than 0 Ensure that the amount is bigger than 0 Create a new product Add information about the new product newProduct.seller = address(msg.sender); | function createProduct (
address _seller,
string calldata name,
string calldata description,
uint price,
uint amt
) public payable {
require(address(msg.sender).balance > price * 1 ether, "Not enough balance to sell");
require(msg.value == price * 1 ether, "Value must be equal to price");
require(price > 0, "Price must be bigger than 0");
require(amt > 0, "Amount must be bigger than 0");
Product memory newProduct;
newProduct.name = name;
newProduct.description = description;
newProduct.price = price * 1 ether;
newProduct.value_escrow = price * 2 ether;
newProduct.amt = amt;
newProduct.init_amt = amt;
newProduct.seller = _seller;
newProduct.cancelled = false;
newProduct.deposit_fund = price * 1 ether;
newProduct.in_delivery = 0;
products.push(newProduct);
numProducts++;
}
| 1,898,875 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libraries/LinearVestingLibrary.sol";
contract LinearVesting is ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
using LinearVestingLibrary for LinearVestingLibrary.Data;
event Withdraw(address indexed sender, uint amount);
event SetLockup(address _account, uint total);
mapping(address => uint) public lockupAmountOf;
mapping(address => uint) public vestedAmountOf;
address immutable private token;
LinearVestingLibrary.Data private vestingData;
constructor(
address _token,
uint _cliffEndBlock,
uint _vestingDurationBlocks
) {
token = _token;
vestingData.initialize(
_cliffEndBlock,
_vestingDurationBlocks
);
}
function addLockup(address[] calldata _accounts, uint128[] calldata _amounts) external onlyOwner {
require(_accounts.length == _amounts.length, "LinearVesting: LENGTH");
for (uint i; i < _accounts.length; ++i) {
lockupAmountOf[_accounts[i]] += _amounts[i];
emit SetLockup(_accounts[i], lockupAmountOf[_accounts[i]]);
}
}
function setLockup(address[] calldata _accounts, uint128[] calldata _totalAmounts) external onlyOwner {
require(_accounts.length == _totalAmounts.length, "LinearVesting: LENGTH");
for (uint i; i < _accounts.length; ++i) {
lockupAmountOf[_accounts[i]] = _totalAmounts[i];
emit SetLockup(_accounts[i], _totalAmounts[i]);
}
}
/// @notice Withdrawals are allowed only if ownership was renounced (setLockup cannot be called, vesting recipients cannot be changed anymore)
function withdraw() external nonReentrant {
require(owner() == address(0), "LinearVesting: RENOUNCE_OWNERSHIP");
uint unlocked = vestingData.availableInputAmount(
lockupAmountOf[msg.sender],
vestedAmountOf[msg.sender]
);
require(unlocked > 0, "LinearVesting: ZERO");
vestedAmountOf[msg.sender] += unlocked;
IERC20(token).safeTransfer(msg.sender, unlocked);
emit Withdraw(msg.sender, unlocked);
}
function unlockedAmountOf(address _account) external view returns (uint) {
return vestingData.availableInputAmount(
lockupAmountOf[_account],
vestedAmountOf[_account]
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
}
}
// 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'
// 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");
}
}
}
// 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 () {
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: GPL-3.0-or-later
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/utils/math/Math.sol";
library LinearVestingLibrary {
struct Data {
uint cliffEndBlock;
uint vestingDurationBlocks;
}
function initialize(
Data storage self,
uint cliffEndBlock,
uint vestingDurationBlocks
) internal {
// cliff may have zero duration to instantaneously unlock percentage of funds
self.cliffEndBlock = cliffEndBlock;
self.vestingDurationBlocks = vestingDurationBlocks;
}
function availableInputAmount(
Data storage self,
uint totalAmount,
uint vestedAmount
) internal view returns (uint) {
if (block.number < self.cliffEndBlock || totalAmount == 0) {
return 0; // no unlock or vesting yet
}
return _vested(self, totalAmount, vestedAmount);
}
function _vested(
Data storage self,
uint totalAmount,
uint vestedAmount
) private view returns (uint) {
if (totalAmount == vestedAmount) {
return 0;
}
if (self.vestingDurationBlocks == 0 || block.number >= self.cliffEndBlock + self.vestingDurationBlocks) {
return totalAmount - vestedAmount;
}
uint passedBlocks = block.number - self.cliffEndBlock;
uint available = totalAmount * passedBlocks / self.vestingDurationBlocks - vestedAmount;
return Math.min(available, totalAmount - vestedAmount);
}
}
// 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;
/**
* @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
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
| Withdrawals are allowed only if ownership was renounced (setLockup cannot be called, vesting recipients cannot be changed anymore) | function withdraw() external nonReentrant {
require(owner() == address(0), "LinearVesting: RENOUNCE_OWNERSHIP");
uint unlocked = vestingData.availableInputAmount(
lockupAmountOf[msg.sender],
vestedAmountOf[msg.sender]
);
require(unlocked > 0, "LinearVesting: ZERO");
vestedAmountOf[msg.sender] += unlocked;
IERC20(token).safeTransfer(msg.sender, unlocked);
emit Withdraw(msg.sender, unlocked);
}
| 11,809,691 |
pragma solidity 0.5.15;
pragma experimental ABIEncoderV2;
import 'ROOT/libraries/ContractExists.sol';
import "ROOT/trading/wrappedShareToken/WrappedShareToken.sol";
import 'ROOT/para/interfaces/IParaShareToken.sol';
import "ROOT/libraries/CloneFactory2.sol";
/**
* @dev This is a factory that creates Wrappers around ERC1155 shareTokens generated by Augur
* @author yashnaman
* as shares on outcomes of a markets.
* For every outcome there will be one wrapper.
*/
contract WrappedShareTokenFactory is CloneFactory2 {
using ContractExists for address;
// contract cloned for each wrapped token
WrappedShareToken public tokenTemplate;
// share token => tokenId => symbol => wrapper
mapping(address => mapping(uint256 => mapping(string => address))) public wrappers;
event WrappedShareTokenCreated(IParaShareToken indexed shareToken, uint256 indexed tokenId, address tokenAddress, string symbol);
constructor (WrappedShareToken _tokenTemplate) public {
tokenTemplate = _tokenTemplate;
}
/**@dev creates new ERC20 wrappers for a outcome of a market
*@param _paraShareToken address of shareToken associated with a augur universe
*@param _tokenId token id associated with a outcome of a market
*@param _symbol symbol for the ERC20 wrapper
*/
function getOrCreateWrappedShareToken(
IParaShareToken _shareToken,
uint256 _tokenId,
string memory _symbol
) public returns (WrappedShareToken) {
address _wrapper = wrappers[address(_shareToken)][_tokenId][_symbol];
if (_wrapper != address(0)) {
return WrappedShareToken(_wrapper);
} else {
_wrapper = createClone2(address(tokenTemplate), salt(_shareToken, _tokenId, _symbol));
wrappers[address(_shareToken)][_tokenId][_symbol] = _wrapper;
}
WrappedShareToken _wrappedShareToken = WrappedShareToken(_wrapper);
_wrappedShareToken.initialize(
_shareToken,
_tokenId,
_symbol
);
emit WrappedShareTokenCreated(_shareToken, _tokenId, _wrapper, _symbol);
return _wrappedShareToken;
}
/**@dev creates new ERC20 wrappers for multiple tokenIds*/
function getOrCreateWrappedShareTokens(
IParaShareToken _shareToken,
uint256[] memory _tokenIds,
string[] memory _symbols
) public returns (WrappedShareToken[] memory _wrappedShareTokens){
require(_tokenIds.length == _symbols.length, "Each token must have one symbol");
_wrappedShareTokens = new WrappedShareToken[](_tokenIds.length);
for (uint256 _i = 0; _i < _tokenIds.length; _i++) {
_wrappedShareTokens[_i] = getOrCreateWrappedShareToken(_shareToken, _tokenIds[_i], _symbols[_i]);
}
}
/**@dev A function that wraps ERC1155s shareToken into ERC20s
* Requirements:
* - msg.sender has setApprovalForAll to this contract
* @param _tokenId token id associated with a outcome of a market
* @param _symbol symbol used for ERC20 for these shares
* @param _account account the newly minted ERC20s will go to
* @param _amount amount of tokens to be wrapped
*/
function wrapShares(
IParaShareToken _shareToken,
uint256 _tokenId,
string memory _symbol,
address _account,
uint256 _amount
) public {
WrappedShareToken _wrappedShareToken = getOrCreateWrappedShareToken(_shareToken, _tokenId, _symbol);
_shareToken.unsafeTransferFrom(
msg.sender,
address(_wrappedShareToken),
_tokenId,
_amount
);
_wrappedShareToken.trustedWrapShares(_account, _amount);
}
/**@dev A function that burns ERC20s and gives back ERC1155s
* Requirements:
* - msg.sender has more than _amount of ERC20 tokens associated with _tokenId.
* - if the market has finalized then it is advised that you call claim() on WrappedShareToken
* contract associated with the winning outcome
* @param _tokenId token id associated with a outcome of a market
* @param _symbol The humab readable representation of the token
* @param _amount amount of tokens to be unwrapped
*/
function unwrapShares(IParaShareToken _shareToken, uint256 _tokenId, string memory _symbol, uint256 _amount) public {
WrappedShareToken wrappedShareToken = WrappedShareToken(calculateShareTokenAddress(_shareToken, _tokenId, _symbol));
wrappedShareToken.unwrapShares(msg.sender, msg.sender, _amount);
}
function unwrapAllShares(IParaShareToken _shareToken, uint256 _tokenId, string memory _symbol) public {
WrappedShareToken wrappedShareToken = WrappedShareToken(calculateShareTokenAddress(_shareToken, _tokenId, _symbol));
wrappedShareToken.unwrapShares(msg.sender, msg.sender, wrappedShareToken.balanceOf(msg.sender));
}
/**@dev wraps multiple tokens */
function wrapMultipleShares(
IParaShareToken _shareToken,
uint256[] memory _tokenIds,
string[] memory _symbols,
address _account,
uint256[] memory _amounts
) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
wrapShares(_shareToken, _tokenIds[i], _symbols[i], _account, _amounts[i]);
}
}
/**@dev unwraps multiple tokens */
function unwrapMultipleShares(
IParaShareToken _shareToken,
uint256[] memory _tokenIds,
string[] memory _symbols,
uint256[] memory _amounts
) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
unwrapShares(_shareToken, _tokenIds[i], _symbols[i], _amounts[i]);
}
}
/**
* @notice Buy some amount of complete sets for a market
* @param _market The market to purchase complete sets in
* @param _amount The number of complete sets to purchase
* @return Bool True
*/
function publicBuyCompleteSets(IMarket _market, IParaShareToken _shareToken, string[] calldata _symbols, uint256 _amount) external returns (bool) {
if(!_shareToken.isMarketInitialized(_market)) {
_shareToken.initializeMarket(_market);
}
require(_market.getNumberOfOutcomes() == _symbols.length, "Must pass in one symbol name for each outcome");
_shareToken.cash().approve(_shareToken.augur(), _amount * _market.getNumTicks());
_shareToken.cash().transferFrom(msg.sender, address(this), _amount * _market.getNumTicks());
_shareToken.publicBuyCompleteSets(_market, _amount);
for (uint256 _i = 0; _i < _symbols.length; _i++) {
uint256 _tokenId = _shareToken.getTokenId(_market, _i);
WrappedShareToken _wrappedShareToken = getOrCreateWrappedShareToken(_shareToken, _tokenId, _symbols[_i]);
_shareToken.unsafeTransferFrom(
address(this),
address(_wrappedShareToken),
_tokenId,
_amount
);
_wrappedShareToken.trustedWrapShares(msg.sender, _amount);
}
return true;
}
/**
* @notice Sell complete sets for the underlying collateral
* @param _market The market for which to sell complete sets
* @param _symbols The token symbols for which you are selling, e.g yOutcome, nOutcome, iOutcome
* @param _amount the number of complete sets to sell
*/
function publicSellCompleteSets(IParaShareToken _shareToken, IMarket _market, string[] calldata _symbols, uint256 _amount) external returns (uint256 _creatorFee, uint256 _reportingFee) {
require(_shareToken.isMarketInitialized(_market));
require(_market.getNumberOfOutcomes() == _symbols.length, "Must pass in one symbol name for each outcome");
for (uint256 _i = 0; _i < _symbols.length; _i++) {
uint256 _tokenId = TokenId.getTokenId(_market, _i);
WrappedShareToken _wrappedShareToken = WrappedShareToken(getOrCreateWrappedShareToken(_shareToken, _tokenId, _symbols[_i]));
_wrappedShareToken.unwrapShares(msg.sender, address(this), _amount);
}
return _shareToken.sellCompleteSets(_market, address(this), msg.sender, _amount, bytes32(0));
}
/**@notice get the address for a particular WrappedShareToken
*@param _shareToken ParaShareToken address for the collateral being used
*@param _tokenId token id associated with a outcome of a market
*@param _name a descriptive name mentioning market and outcome
*@param _symbol symbol for the ERC20 wrapper
*@param decimals decimals for the ERC20 wrapper
*/
function calculateShareTokenAddress(IParaShareToken _shareToken, uint256 _tokenId, string memory _symbol) public view returns (address) {
return clone2Address(address(tokenTemplate), salt(_shareToken, _tokenId, _symbol), address(this));
}
function salt(IParaShareToken _shareToken, uint256 _tokenId, string memory _symbol) private pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(_shareToken, _tokenId, _symbol)));
}
}
| wraps multiple tokens / | function wrapMultipleShares(
IParaShareToken _shareToken,
uint256[] memory _tokenIds,
string[] memory _symbols,
address _account,
uint256[] memory _amounts
) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
wrapShares(_shareToken, _tokenIds[i], _symbols[i], _account, _amounts[i]);
}
}
| 14,072,581 |
/*
--------------------------------------------------------------------------------
The Bethereum [BETHER] Token Smart Contract
Credit:
Bethereum Limited
ERC20: https://github.com/ethereum/EIPs/issues/20
ERC223: https://github.com/ethereum/EIPs/issues/223
MIT Licence
--------------------------------------------------------------------------------
*/
/*
* Contract that is working with ERC223 tokens
*/
contract ContractReceiver {
function tokenFallback(address _from, uint _value, bytes _data) {
/* Fix for Mist warning */
_from;
_value;
_data;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 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.
*/
function Ownable() {
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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC223Interface {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
contract BethereumERC223 is ERC223Interface {
using SafeMath for uint256;
/* Contract Constants */
string public constant _name = "Bethereum";
string public constant _symbol = "BETHER";
uint8 public constant _decimals = 18;
/* Contract Variables */
address public owner;
mapping(address => uint256) public balances;
mapping(address => mapping (address => uint256)) public allowed;
/* Constructor initializes the owner's balance and the supply */
function BethereumERC223() {
owner = msg.sender;
}
/* ERC20 Events */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed to, uint256 value);
/* ERC223 Events */
event Transfer(address indexed from, address indexed to, uint value, bytes data);
/* Returns the balance of a particular account */
function balanceOf(address _address) constant returns (uint256 balance) {
return balances[_address];
}
/* Transfer the balance from the sender's address to the address _to */
function transfer(address _to, uint _value) returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]) {
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
} else {
return false;
}
}
/* Withdraws to address _to form the address _from up to the amount _value */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value
&& allowed[_from][msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]) {
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
/* Allows _spender to withdraw the _allowance amount form sender */
function approve(address _spender, uint256 _allowance) returns (bool success) {
allowed[msg.sender][_spender] = _allowance;
Approval(msg.sender, _spender, _allowance);
return true;
}
/* Checks how much _spender can withdraw from _owner */
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/* ERC223 Functions */
/* Get the contract constant _name */
function name() constant returns (string name) {
return _name;
}
/* Get the contract constant _symbol */
function symbol() constant returns (string symbol) {
return _symbol;
}
/* Get the contract constant _decimals */
function decimals() constant returns (uint8 decimals) {
return _decimals;
}
/* Transfer the balance from the sender's address to the address _to with data _data */
function transfer(address _to, uint _value, bytes _data) returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
} else {
return false;
}
}
/* Transfer function when _to represents a regular address */
function transferToAddress(address _to, uint _value, bytes _data) internal returns (bool success) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
Transfer(msg.sender, _to, _value, _data);
return true;
}
/* Transfer function when _to represents a contract address, with the caveat
that the contract needs to implement the tokenFallback function in order to receive tokens */
function transferToContract(address _to, uint _value, bytes _data) internal returns (bool success) {
balances[msg.sender] -= _value;
balances[_to] += _value;
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value);
Transfer(msg.sender, _to, _value, _data);
return true;
}
/* Infers if whether _address is a contract based on the presence of bytecode */
function isContract(address _address) internal returns (bool is_contract) {
uint length;
if (_address == 0) return false;
assembly {
length := extcodesize(_address)
}
if(length > 0) {
return true;
} else {
return false;
}
}
/* Stops any attempt to send Ether to this contract */
function () {
throw;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is BethereumERC223, Pausable {
function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused returns (bool) {
return super.transfer(_to, _value, _data);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is BethereumERC223, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract BethereumToken is MintableToken, PausableToken {
function BethereumToken(){
pause();
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _endTime, address _wallet) {
require(_endTime >= now);
require(_wallet != 0x0);
token = createTokenContract();
endTime = _endTime;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (BethereumToken) {
return new BethereumToken();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable { }
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
bool public weiCapReached = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract BETHERTokenSale is FinalizableCrowdsale {
using SafeMath for uint256;
// Define sale
uint public constant RATE = 17500;
uint public constant TOKEN_SALE_LIMIT = 25000 * 1000000000000000000;
uint256 public constant TOKENS_FOR_OPERATIONS = 400000000*(10**18);
uint256 public constant TOKENS_FOR_SALE = 600000000*(10**18);
uint public constant TOKENS_FOR_PRESALE = 315000000*(1 ether / 1 wei);
uint public BONUS_PERCENTAGE;
enum Phase {
Created,
CrowdsaleRunning,
Paused
}
Phase public currentPhase = Phase.Created;
event LogPhaseSwitch(Phase phase);
// Constructor
function BETHERTokenSale(
uint256 _end,
address _wallet
)
FinalizableCrowdsale()
Crowdsale(_end, _wallet) {
}
function setNewBonusScheme(uint _bonusPercentage) {
BONUS_PERCENTAGE = _bonusPercentage;
}
function mintRawTokens(address _buyer, uint256 _newTokens) public onlyOwner {
token.mint(_buyer, _newTokens);
}
/// @dev Lets buy you some tokens.
function buyTokens(address _buyer) public payable {
// Available only if presale or crowdsale is running.
require(currentPhase == Phase.CrowdsaleRunning);
require(_buyer != address(0));
require(msg.value > 0);
require(validPurchase());
uint tokensWouldAddTo = 0;
uint weiWouldAddTo = 0;
uint256 weiAmount = msg.value;
uint newTokens = msg.value.mul(RATE);
weiWouldAddTo = weiRaised.add(weiAmount);
require(weiWouldAddTo <= TOKEN_SALE_LIMIT);
newTokens = addBonusTokens(token.totalSupply(), newTokens);
tokensWouldAddTo = newTokens.add(token.totalSupply());
require(tokensWouldAddTo <= TOKENS_FOR_SALE);
token.mint(_buyer, newTokens);
TokenPurchase(msg.sender, _buyer, weiAmount, newTokens);
weiRaised = weiWouldAddTo;
forwardFunds();
if (weiRaised == TOKENS_FOR_SALE){
weiCapReached = true;
}
}
// @dev Adds bonus tokens by token supply bought by user
// @param _totalSupply total supply of token bought during pre-sale/crowdsale
// @param _newTokens tokens currently bought by user
function addBonusTokens(uint256 _totalSupply, uint256 _newTokens) internal view returns (uint256) {
uint returnTokens;
uint tokens = _newTokens;
returnTokens = tokens.add(tokens.mul(BONUS_PERCENTAGE).div(100));
return returnTokens;
}
function setSalePhase(Phase _nextPhase) public onlyOwner {
currentPhase = _nextPhase;
LogPhaseSwitch(_nextPhase);
}
function transferTokenOwnership(address _newOwner) {
token.transferOwnership(_newOwner);
}
// Finalize
function finalization() internal {
uint256 toMint = TOKENS_FOR_OPERATIONS;
token.mint(wallet, toMint);
token.finishMinting();
token.transferOwnership(wallet);
}
} | Contract Constants / Contract Variables / Constructor initializes the owner's balance and the supply / | function BethereumERC223() {
owner = msg.sender;
}
event Approval(address indexed from, address indexed to, uint256 value);
| 4,805,209 |
./full_match/3/0x37ff2Dab3fc4323b304fD894D1e8df57E2CaD152/sources/browser/ERC721Beers.sol | ERC-721 Non-Fungible Token Standard, optional metadata extension/ | interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 nftIndex) external view returns (string memory);
}
}
| 14,133,070 |
./full_match/5/0x998bf0Eb2ee683020eC906FAF16f81Fc22641435/sources/contracts/core/connext/helpers/OZERC20.sol | 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,
msg.sender,
allowances[_sender][msg.sender].sub(_amount, "ERC20: transfer amount exceeds allowance")
);
return true;
}
| 1,904,028 |
pragma solidity ^0.5.0;
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./uniswap/UniswapV2Factory.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
//create pair
function createPair(address _tokenA, address _tokenB) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//make sure _tokenA is fee token
require(tokenAID <= MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "tokenA should be fee token");
//create pair
address pair = pairmanager.createPair(_tokenA, _tokenB);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
tokenAID,
_tokenA,
tokenBID,
_tokenB,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
address(0),
erc20ID,
_tokenERC20,
validatePairTokenAddress(pair),
pair
);
}
function registerCreatePair(uint16 _tokenAID, address _tokenA, uint16 _tokenBID, address _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
Operations.CreatePair memory op = Operations.CreatePair({
accountId : 0, //unknown at this point
tokenA : _tokenAID,
tokenB : _tokenBID,
tokenPair : _tokenPair,
pair : _pair
});
bytes memory pubData = Operations.writeCreatePairPubdata(op);
bytes memory userData = abi.encodePacked(
_tokenA, // tokenA address
_tokenB // tokenB address
);
addPriorityRequest(Operations.OpType.CreatePair, pubData, userData);
emit OnchainCreatePair(_tokenAID, _tokenBID, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
function upgradeNoticePeriodStarted() external {
}
/// @notice Notification that upgrade preparation status is activated
function upgradePreparationStarted() external {
upgradePreparationActive = true;
upgradePreparationActivationTime = now;
}
/// @notice Notification that upgrade canceled
function upgradeCanceled() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
function upgradeFinishes() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) {
return !exodusMode;
}
constructor() public {
governance = Governance(msg.sender);
zkSyncCommitBlockAddress = address(this);
zkSyncExitAddress = address(this);
}
/// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _governanceAddress The address of Governance contract
/// _verifierAddress The address of Verifier contract
/// _ // FIXME: remove _genesisAccAddress
/// _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external {
require(address(governance) == address(0), "init0");
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress
) = abi.decode(initializationParameters, (address, address, address, address));
verifier = Verifier(_verifierAddress);
verifierExit = VerifierExit(_verifierExitAddress);
governance = Governance(_governanceAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
maxDepositAmount = DEFAULT_MAX_DEPOSIT_AMOUNT;
withdrawGasLimit = ERC20_WITHDRAWAL_GAS_LIMIT;
}
function setGenesisRootAndAddresses(bytes32 _genesisRoot, address _zkSyncCommitBlockAddress, address _zkSyncExitAddress) external {
// This function cannot be called twice as long as
// _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to
// non-zero.
require(zkSyncCommitBlockAddress == address(0), "sraa1");
require(zkSyncExitAddress == address(0), "sraa2");
blocks[0].stateRoot = _genesisRoot;
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
zkSyncExitAddress = _zkSyncExitAddress;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @param _maxAmount Maximum possible amount of tokens to transfer to this account
function withdrawERC20Guarded(IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "wtg10");
// wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint16 lpTokenId = tokenIds[address(_token)];
uint256 balance_before = _token.balanceOf(address(this));
if (lpTokenId > 0) {
validatePairTokenAddress(address(_token));
pairmanager.mint(address(_token), _to, _amount);
} else {
require(Utils.sendERC20(_token, _to, _amount), "wtg11");
// wtg11 - ERC20 transfer fails
}
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
require(balance_diff <= _maxAmount, "wtg12");
// wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balance_diff);
}
/// @notice executes pending withdrawals
/// @param _n The number of withdrawals to complete starting from oldest
function completeWithdrawals(uint32 _n) external nonReentrant {
// TODO: when switched to multi validators model we need to add incentive mechanism to call complete.
uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals);
uint32 startIndex = firstPendingWithdrawalIndex;
numberOfPendingWithdrawals -= toProcess;
firstPendingWithdrawalIndex += toProcess;
for (uint32 i = startIndex; i < startIndex + toProcess; ++i) {
uint16 tokenId = pendingWithdrawals[i].tokenId;
address to = pendingWithdrawals[i].to;
// send fails are ignored hence there is always a direct way to withdraw.
delete pendingWithdrawals[i];
bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId);
uint128 amount = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
// amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20
if (amount != 0) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw -= amount;
bool sent = false;
if (tokenId == 0) {
address payable toPayable = address(uint160(to));
sent = Utils.sendETHNoRevert(toPayable, amount);
} else {
address tokenAddr = address(0);
if (tokenId < PAIR_TOKEN_START_ID) {
// It is normal ERC20
tokenAddr = governance.tokenAddresses(tokenId);
} else {
// It is pair token
tokenAddr = tokenAddresses[tokenId];
}
// tokenAddr cannot be 0
require(tokenAddr != address(0), "cwt0");
// we can just check that call not reverts because it wants to withdraw all amount
(sent,) = address(this).call.gas(withdrawGasLimit)(
abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount)
);
}
if (!sent) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += amount;
}
}
}
if (toProcess > 0) {
emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess);
}
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n) external nonReentrant {
require(exodusMode, "coe01");
// exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "coe02");
// no deposits to process
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
Operations.Deposit memory op = Operations.readDepositPubdata(priorityRequests[id].pubData);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _franklinAddr The receiver Layer 2 address
function depositETH(address _franklinAddr) external payable nonReentrant {
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr);
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender
/// @param _amount Ether amount to withdraw
function withdrawETH(uint128 _amount) external nonReentrant {
registerWithdrawal(0, _amount, msg.sender);
(bool success,) = msg.sender.call.value(_amount)("");
require(success, "fwe11");
// ETH withdraw failed
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to _to address
/// @param _amount Ether amount to withdraw
function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa11");
registerWithdrawal(0, _amount, _to);
(bool success,) = _to.call.value(_amount)("");
require(success, "fwe12");
// ETH withdraw failed
}
/// @notice Config amount limit for each ERC20 deposit
/// @param _amount Max deposit amount
function setMaxDepositAmount(uint128 _amount) external {
governance.requireGovernor(msg.sender);
maxDepositAmount = _amount;
}
/// @notice Config gas limit for withdraw erc20 token
/// @param _gasLimit withdraw erc20 gas limit
function setWithDrawGasLimit(uint256 _gasLimit) external {
governance.requireGovernor(msg.sender);
withdrawGasLimit = _gasLimit;
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
/// @param _franklinAddr Receiver Layer 2 address
function depositERC20(IERC20 _token, uint104 _amount, address _franklinAddr) external nonReentrant {
requireActive();
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount));
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= maxDepositAmount, "fd011");
registerDeposit(lpTokenId, deposit_amount, _franklinAddr);
} else {
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012");
// token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= maxDepositAmount, "fd013");
registerDeposit(tokenId, deposit_amount, _franklinAddr);
}
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender
/// @param _token Token address
/// @param _amount amount to withdraw
function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant {
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, msg.sender, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, msg.sender);
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to _to address
/// @param _token Token address
/// @param _amount amount to withdraw
/// @param _to address to withdraw
function withdrawERC20WithAddress(IERC20 _token, uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa12");
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(_to, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, _to, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, _to);
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function fullExit(uint32 _accountId, address _token) external nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "fee11");
uint16 tokenId;
if (_token == address(0)) {
tokenId = 0;
} else {
tokenId = governance.validateTokenAddress(_token);
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "fee12");
}
// Priority Queue request
Operations.FullExit memory op = Operations.FullExit({
accountId : _accountId,
owner : msg.sender,
tokenId : tokenId,
amount : 0 // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdata(op);
addPriorityRequest(Operations.OpType.FullExit, pubData, "");
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff;
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op = Operations.Deposit({
accountId : 0, // unknown at this point
owner : _owner,
tokenId : _tokenId,
amount : _amount
});
bytes memory pubData = Operations.writeDepositPubdata(op);
addPriorityRequest(Operations.OpType.Deposit, pubData, "");
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
/// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event
/// @param _token - token by id
/// @param _amount - token amount
/// @param _to - address to withdraw to
function registerWithdrawal(uint16 _token, uint128 _amount, address payable _to) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(_amount);
emit OnchainWithdrawal(
_to,
_token,
_amount
);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "fre11");
// exodus mode activated
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData,
bytes memory _userData
) internal {
// Expiration block is: current block number + priority expiration delta
uint256 expirationBlock = block.number + PRIORITY_EXPIRATION;
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
priorityRequests[nextPriorityRequestId] = PriorityOperation({
opType : _opType,
pubData : _pubData,
expirationBlock : expirationBlock
});
emit NewPriorityRequest(
msg.sender,
nextPriorityRequestId,
_opType,
_pubData,
_userData,
expirationBlock
);
totalOpenPriorityRequests++;
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
function() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.5.0;
/**
* @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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// Address of lock flag variable.
/// Flag is placed at random memory location to not interfere with Storage contract.
uint constant private LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
function initializeReentrancyGuard () internal {
// Storing an initial 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 percetange 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.
assembly { sstore(LOCK_FLAG_ADDRESS, 1) }
}
/**
* @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() {
bool notEntered;
assembly { notEntered := sload(LOCK_FLAG_ADDRESS) }
// On the first call to nonReentrant, _notEntered will be true
require(notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
assembly { sstore(LOCK_FLAG_ADDRESS, 0) }
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly { sstore(LOCK_FLAG_ADDRESS, 1) }
}
}
pragma solidity ^0.5.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.
*
* _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;
}
}
pragma solidity ^0.5.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 SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(
abi.encodeWithSignature("transfer(address,uint256)", _to, _amount)
);
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(
abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount)
);
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Sends ETH
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) {
// TODO: Use constant from Config
uint256 ETH_WITHDRAWAL_GAS_LIMIT = 10000;
(bool callSuccess, ) = _to.call.gas(ETH_WITHDRAWAL_GAS_LIMIT).value(_amount)("");
return callSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _message signed message.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes memory _message) internal pure returns (address) {
require(_signature.length == 65, "ves10"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint offset = 0;
(offset, signR) = Bytes.readBytes32(_signature, offset);
(offset, signS) = Bytes.readBytes32(_signature, offset);
uint8 signV = uint8(_signature[offset]);
return ecrecover(keccak256(_message), signV, signR, signS);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title ZKSwap storage contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Storage {
/// @notice Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool public upgradePreparationActive;
/// @notice Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public upgradePreparationActivationTime;
/// @notice Verifier contract. Used to verify block proof and exit proof
Verifier internal verifier;
VerifierExit internal verifierExit;
/// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance internal governance;
UniswapV2Factory internal pairmanager;
struct BalanceToWithdraw {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw;
/// @notice verified withdrawal pending to be executed.
struct PendingWithdrawal {
address to;
uint16 tokenId;
}
/// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue)
mapping(uint32 => PendingWithdrawal) public pendingWithdrawals;
uint32 public firstPendingWithdrawalIndex;
uint32 public numberOfPendingWithdrawals;
/// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis)
uint32 public totalBlocksVerified;
/// @notice Total number of checked blocks
uint32 public totalBlocksChecked;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Rollup block data (once per block)
/// @member validator Block producer
/// @member committedAtBlock ETH block number at which this block was committed
/// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks
/// @member priorityOperations Total number of priority operations for this block
/// @member commitment Hash of the block circuit commitment
/// @member stateRoot New tree root hash
///
/// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html
struct Block {
uint32 committedAtBlock;
uint64 priorityOperations;
uint32 chunks;
bytes32 withdrawalsDataHash; /// can be restricted to 16 bytes to reduce number of required storage slots
bytes32 commitment;
bytes32 stateRoot;
}
/// @notice Blocks by Franklin block id
mapping(uint32 => Block) public blocks;
/// @notice Onchain operations - operations processed inside rollup blocks
/// @member opType Onchain operation type
/// @member amount Amount used in the operation
/// @member pubData Operation pubdata
struct OnchainOperation {
Operations.OpType opType;
bytes pubData;
}
/// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public exited;
mapping(uint32 => mapping(uint32 => bool)) public swap_exited;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice User authenticated fact hashes for some nonce.
mapping(address => mapping(uint32 => bytes32)) public authFacts;
/// @notice Priority Operation container
/// @member opType Priority operation type
/// @member pubData Priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
struct PriorityOperation {
Operations.OpType opType;
bytes pubData;
uint256 expirationBlock;
}
/// @notice Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
mapping(uint64 => PriorityOperation) public priorityRequests;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @notice Gets value from balancesToWithdraw
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
address public zkSyncCommitBlockAddress;
address public zkSyncExitAddress;
/// @notice Limit the max amount for each ERC20 deposit
uint128 public maxDepositAmount;
/// @notice withdraw erc20 token gas limit
uint256 public withdrawGasLimit;
}
pragma solidity ^0.5.0;
/// @title ZKSwap configuration constants
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Config {
/// @notice ERC20 token withdrawal gas limit, used only for complete withdrawals
uint256 constant ERC20_WITHDRAWAL_GAS_LIMIT = 350000;
/// @notice ETH token withdrawal gas limit, used only for complete withdrawals
uint256 constant ETH_WITHDRAWAL_GAS_LIMIT = 10000;
/// @notice Bytes in one chunk
uint8 constant CHUNK_BYTES = 11;
/// @notice ZKSwap address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @notice Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @notice Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @notice Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @notice Max amount of fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS = 32 - 1;
/// @notice start ID for user tokens
uint16 constant USER_TOKENS_START_ID = 32;
/// @notice Max amount of user tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_USER_TOKENS = 16352;
/// @notice Max amount of tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 16384 - 1;
/// @notice Max account id that could be registered in the network
uint32 constant MAX_ACCOUNT_ID = (2 ** 28) - 1;
/// @notice Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @notice ETH blocks verification expectation
/// Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant CREATE_PAIR_BYTES = 3 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 4 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 4 * CHUNK_BYTES;
uint256 constant PARTIAL_EXIT_BYTES = 5 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant UNISWAP_ADD_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_RM_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_SWAP_BYTES = 2 * CHUNK_BYTES;
/// @notice Full exit operation length
uint256 constant FULL_EXIT_BYTES = 4 * CHUNK_BYTES;
/// @notice OnchainWithdrawal data length
uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 1 + 20 + 2 + 16; // (uint8 addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
/// @notice ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 5 * CHUNK_BYTES;
/// @notice Expiration delta for priority request to be satisfied (in seconds)
/// NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD), otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 3 days;
/// @notice Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @notice Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @notice Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint constant MASS_FULL_EXIT_PERIOD = 3 days;
/// @notice Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @notice Notice period before activation preparation status of upgrade mode (in seconds)
// NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD + PRIORITY_EXPIRATION_PERIOD + TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT;
// @notice Default amount limit for each ERC20 deposit
uint128 constant DEFAULT_MAX_DEPOSIT_AMOUNT = 2 ** 85;
}
pragma solidity ^0.5.0;
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title ZKSwap events
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
/// @notice Event emitted when a block is verified
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when a sequence of blocks is verified
event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo);
/// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash)
event FactAuth(
address indexed sender,
uint32 nonce,
bytes fact
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(
uint32 indexed totalBlocksVerified,
uint32 indexed totalBlocksCommitted
);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
bytes userData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Pending withdrawals index range that were added in the verifyBlock operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsAdd(
uint32 queueStartIndex,
uint32 queueEndIndex
);
/// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsComplete(
uint32 queueStartIndex,
uint32 queueEndIndex
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(
uint indexed versionId,
address indexed upgradeable
);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint indexed versionId,
address[] newTargets,
uint noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(
uint indexed versionId
);
/// @notice Upgrade mode preparation status event
event PreparationStart(
uint indexed versionId
);
/// @notice Upgrade mode complete event
event UpgradeComplete(
uint indexed versionId,
address[] newTargets
);
}
pragma solidity ^0.5.0;
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "bt211");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint data = self << ((32 - byteLength) * 8);
assembly {
mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "bta11");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "btb20");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "btu02");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "btu03");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "btu04");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "btu16");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "btu20");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "btb32");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
// TODO: Review this thoroughly.
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
// Helper function for hex conversion.
function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
}
}
return outStringBytes;
}
/// Trim bytes into single word
function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) {
require(_new_length <= 0x20, "trm10"); // new_length is longer than word
require(_data.length >= _new_length, "trm11"); // data is to short
uint a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
}
pragma solidity ^0.5.0;
import "./Bytes.sol";
/// @title ZKSwap operations tools
library Operations {
// Circuit ops and their pubdata (chunks * bytes)
/// @notice ZKSwap circuit operation type
enum OpType {
Noop,
Deposit,
TransferToNew,
PartialExit,
_CloseAccount, // used for correct op id offset
Transfer,
FullExit,
ChangePubKey,
CreatePair,
AddLiquidity,
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @notice Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @notice ZKSwap account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @notice Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
}
uint public constant PACKED_DEPOSIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure
returns (Deposit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner // owner
);
}
/// @notice Check that deposit pubdata from request and block matches
function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// FullExit pubdata
struct FullExit {
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
}
uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure
returns (FullExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size
}
function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
/// @notice Check that full exit pubdata from request and block matches
function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// `amount` is ignored because it is present in block pubdata but not in priority queue
uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
return lhs == rhs;
}
// PartialExit pubdata
struct PartialExit {
//uint32 accountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
}
function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure
returns (PartialExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
}
function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
// ChangePubKey
struct ChangePubKey {
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
}
function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure
returns (ChangePubKey memory parsed)
{
uint offset = _offset;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// Withdrawal data process
function readWithdrawalData(bytes memory _data, uint _offset) internal pure
returns (bool _addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
{
uint offset = _offset;
(offset, _addToPendingWithdrawalsQueue) = Bytes.readBool(_data, offset);
(offset, _to) = Bytes.readAddress(_data, offset);
(offset, _tokenId) = Bytes.readUInt16(_data, offset);
(offset, _amount) = Bytes.readUInt128(_data, offset);
}
// CreatePair pubdata
struct CreatePair {
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
function readCreatePairPubdata(bytes memory _data) internal pure
returns (CreatePair memory parsed)
{
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
/// @notice Check that create pair pubdata from request and block matches
function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() public {
}
function initialize(bytes calldata data) external {
}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
//require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
IUniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
IUniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.5.0;
contract PairTokenManager {
/// @notice Max amount of pair tokens registered in the network.
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 49152;
uint16 constant PAIR_TOKEN_START_ID = 16384;
/// @notice Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
tokenAddresses[newPairTokenId] = _token;
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @notice Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId <= (PAIR_TOKEN_START_ID -1 + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
return tokenId;
}
}
pragma solidity ^0.5.0;
/**
* @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);
}
pragma solidity ^0.5.0;
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
/// @notice Governor changed
event NewGovernor(
address newGovernor
);
/// @notice tokenLister changed
event NewTokenLister(
address newTokenLister
);
/// @notice Validator's status changed
event ValidatorStatusUpdate(
address indexed validatorAddress,
bool isActive
);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalFeeTokens;
/// @notice Total number of ERC20 user tokens registered in the network
uint16 public totalUserTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
address public tokenLister;
constructor() public {
networkGovernor = msg.sender;
}
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
require(networkGovernor == address(0), "init0");
(address _networkGovernor, address _tokenLister) = abi.decode(initializationParameters, (address, address));
networkGovernor = _networkGovernor;
tokenLister = _tokenLister;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
require(_newGovernor != address(0), "zero address is passed as _newGovernor");
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Change current governor
/// @param _newTokenLister Address of the new governor
function changeTokenLister(address _newTokenLister) external {
requireGovernor(msg.sender);
require(_newTokenLister != address(0), "zero address is passed as _newTokenLister");
if (tokenLister != _newTokenLister) {
tokenLister = _newTokenLister;
emit NewTokenLister(_newTokenLister);
}
}
/// @notice Add fee token to the list of networks tokens
/// @param _token Token address
function addFeeToken(address _token) external {
requireGovernor(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalFeeTokens < MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "fee12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
totalFeeTokens++;
uint16 newTokenId = totalFeeTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireTokenLister(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalUserTokens < MAX_AMOUNT_OF_REGISTERED_USER_TOKENS, "gan12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
uint16 newTokenId = USER_TOKENS_START_ID + totalUserTokens;
totalUserTokens++;
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "grr11"); // only by governor
}
/// @notice Check if specified address can list token
/// @param _address Address to check
function requireTokenLister(address _address) public view {
require(_address == networkGovernor || _address == tokenLister, "grr11"); // token lister or governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "grr21"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return (_tokenId <= totalFeeTokens) || (_tokenId >= USER_TOKENS_START_ID && _tokenId < (USER_TOKENS_START_ID + totalUserTokens ));
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "gvs11"); // 0 is not a valid token
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "gvs12");
return tokenId;
}
function getTokenAddress(uint16 _tokenId) external view returns (address) {
address tokenAddr = tokenAddresses[_tokenId];
return tokenAddr;
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkAggVerifier.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkAggVerifier {
bool constant DUMMY_VERIFIER = false;
function initialize(bytes calldata) external {
}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function isBlockSizeSupported(uint32 _size) public pure returns (bool) {
if (DUMMY_VERIFIER) {
return true;
} else {
return isBlockSizeSupportedInternal(_size);
}
}
function verifyMultiblockProof(
uint256[] calldata _recursiveInput,
uint256[] calldata _proof,
uint32[] calldata _block_sizes,
uint256[] calldata _individual_vks_inputs,
uint256[] calldata _subproofs_limbs
) external view returns (bool) {
if (DUMMY_VERIFIER) {
uint oldGasValue = gasleft();
uint tmp;
while (gasleft() + 500000 > oldGasValue) {
tmp += 1;
}
return true;
}
uint8[] memory vkIndexes = new uint8[](_block_sizes.length);
for (uint32 i = 0; i < _block_sizes.length; i++) {
vkIndexes[i] = blockSizeToVkIndex(_block_sizes[i]);
}
VerificationKey memory vk = getVkAggregated(uint32(_block_sizes.length));
return verify_serialized_proof_with_recursion(_recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, vkIndexes, _individual_vks_inputs, _subproofs_limbs, vk);
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkSingleVerifier.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkSingleVerifier {
function initialize(bytes calldata) external {
}
/// @notice VerifierExit contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment = sha256(abi.encodePacked(_rootHash, _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _pair_data0,
bytes calldata _pair_data1,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory _data1 = concatBytes(_account_data, _pair_data0);
bytes memory _data2 = concatBytes(_data1, _pair_data1);
bytes32 commitment = sha256(_data2);
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkLpExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
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);
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IUNISWAPERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkAggCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkAggVerifier is AggVerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x0a3cdc9655e61bf64758c1e8df745723e9b83addd4f0d0f2dd65dc762dc1e9e7;
uint8 constant VK_MAX_INDEX = 5;
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function blockSizeToVkIndex(uint32 _chunks) internal pure returns (uint8) {
if (_chunks == uint32(6)) { return 0; }
else if (_chunks == uint32(12)) { return 1; }
else if (_chunks == uint32(48)) { return 2; }
else if (_chunks == uint32(96)) { return 3; }
else if (_chunks == uint32(204)) { return 4; }
else if (_chunks == uint32(420)) { return 5; }
}
function getVkAggregated(uint32 _blocks) internal pure returns (VerificationKey memory vk) {
if (_blocks == uint32(1)) { return getVkAggregated1(); }
else if (_blocks == uint32(5)) { return getVkAggregated5(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated5() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x023cfc69ef1b002da66120fce352ede75893edd8cd8196403a54e1eceb82cd43,
0x2baf3bd673e46be9df0d43ca30f834671543c22db422f450b2efd8c931e9b34e
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x23783fe0e5c3f83c02c864e25fe766afb727134c9a77ae6b9694efb7b46f31ab,
0x1903d01005e447d061c16323a1d604d8fbd4b5cc9b64945a71f1234d280c4d3a
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x2897df6c6fa993661b2b0b0cf52460278e33533de71b3c0f7ed7c1f20af238c6,
0x042344afee0aed5505e59bce4ebbe942a91268a8af6b77ea95f603b5b726e8cb
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x0fceed33e78426afc38d8a68c0d93413d2bbaa492b087125271d33d52bdb07b8,
0x0057e4f63be36edb56e91da931f3d0ba72d1862d4b7751c59b92b6ae9f1fcc11
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x14230a35f172cd77a2147cecc20b2a13148363cbab78709489a29d08001e26fb,
0x04f1040477d77896475080b5abb8091cda2cce4917ee0ba5dd62d0ab1be379b4
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x20d1a079ad80a8abb7fd8ba669dddbbe23231360a5f0ba679b6536b6bf980649,
0x120c5a845903bd6de4105eb8cef90e6dff2c3888ada16c90e1efb393778d6a4d
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x1af6b9e362e458a96b8bbbf8f8ce2bdbd650fb68478360c408a2acf1633c1ce1,
0x27033728b767b44c659e7896a6fcc956af97566a5a1135f87a2e510976a62d41
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x0dbfb3c5f5131eb6f01e12b1a6333b0ad22cc8292b666e46e9bd4d80802cccdf,
0x2d058711c42fd2fd2eef33fb327d111a27fe2063b46e1bb54b32d02e9676e546
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0c8c7352a84dd3f32412b1a96acd94548a292411fd7479d8609ca9bd872f1e36,
0x0874203fd8012d6976698cc2df47bca14bc04879368ade6412a2109c1e71e5e8
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1b17bb7c319b1cf15461f4f0b69d98e15222320cb2d22f4e3a5f5e0e9e51f4bd,
0x0cf5bc338235ded905926006027aa2aab277bc32a098cd5b5353f5545cbd2825
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x0794d3cfbc2fdd756b162571a40e40b8f31e705c77063f30a4e9155dbc00e0ef,
0x1f821232ab8826ea5bf53fe9866c74e88a218c8d163afcaa395eda4db57b7a23
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x224d93783aa6856621a9bbec495f4830c94994e266b240db9d652dbb394a283b,
0x161bcec99f3bc449d655c0ca59874dafe1194138eec91af34392b09a83338ca1
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1fa27e2916b2c11d39c74c0e61063190da31c102d2b7da5c0a61ec8c5e82f132,
0x0a815ee76cd8aa600e6f66463b25a0ee57814bfdf06c65a91ddc70cede41caae
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkSingleCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkSingleVerifier is SingleVerifierWithDeserialize {
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function getVkExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1abc710835cdc78389d61b670b0e8d26416a63c9bd3d6ed435103ebbb8a8665e,
0x138c6678230ed19f90b947d0a9027bd9fc458bbd1d2b8371fa72e28470a97b9c
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x28d81ac76e1ddf630b4bf8e4a789cf9c4470c5e5cc010a24849b20ab595b8b22,
0x251ca3cf0829b261d3be8d6cbd25aa97d9af716819c29f6319d806f075e79655
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1504c8c227833a1152f3312d258412c334ac7ae213e21427ff63028729bc28fa,
0x0f0942f3fede795cbe624fb9ddf9be90ba546609383f2246c3c9b92af7aab5fd
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x1f14a5bb19ea2897ac6b9fbdbd2b4e371be09f8e90a47ae26602d399c9bcd311,
0x029c6ea094247da75d9a66cea627c3c77d48b898003125d4f8e785435dc2cf23
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x102cdd83e2d70638a70d700622b662607f8a2d92f5c36053a4ddb4b600d75bcf,
0x09ef3679579d761507ef69eaf49c978b271f0e4500468da1ebd7197f3ff5d6ac
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x2c2bd1d2fa3d4b3915d0fe465469e11ee563e79751da71c6082fcd0ca4e41cd5,
0x0304f16147a8af177dcc703370931d5161bda9dcf3e091787b9a54377ab54c32
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x14420680f992f4bc8d8012e2d8b14a774cf9114adf1e41b3c02c20cc1648398e,
0x237d3d5cdee5e3d7d58f4eb336ecd7aa5ec88d89205861b410420f6b9f6b26a1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x221045ae5578ccb35e0a198d83c0fb191da8cdc98423fc46e580f1762682c73e,
0x15b7f3d74fcd258fdd2ae6001693a7c615e654d613a506d213aaf0ad314e338d
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x03e47981b459b3be258a6353593898babec571ccf3e0362d53a67f078f04830a,
0x0809556ab6eb28403bb5a749fcdbd8656940add7685ff5473dc3a9ad940034df
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2c02322c53d7e6a6474b15c7db738419e3f4d1263e9f98ebb56c24906f555ef9,
0x2322c69f51366551665b584d797e0fdadb16fe31b1e7ae2f532847a75b3aeaab
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x2147e39b49c2bef4168884c0ac9e38bb4dc65b41ba21953f7ded2daab7fe1534,
0x071f3548c9ca2c6a8d10b11d553263ebe0afaf1f663b927ef970bd6c3974cb68
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkLpExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 524288;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x067d967299b3d380f2e461409fbacb82d9af8c85b62de082a423f344fb0b9d38,
0x2440bd569ac24e9525b29e433334ee98d72cb8eb19af65250ee0099fb470d873
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x086a9ed0f6175964593e516a8c1fc8bbd0a9c8afb724ebbce08a7772bd7b8837,
0x0aca3794dc6a2f0cab69dfed529d31deb7a5e9e6c339e3c07d8d88df0f7abd6b
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x00b6bfec3aceb55618e6caf637c978c3fe2344568c64515022fcfa00e490eb97,
0x0f890fe6b9cb943fb4887df1529cdae99e2494eabf675f89905215eb51c29c6e
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x0968470be841bcbfbcccc10dd0d8b63a871cdb3289c214fc59f38c88ab15146a,
0x1a9b4d034050fa0b119bb64ba0e967fd09f224c6fd9cd8b54cd6f081085dfb98
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x080dbe10de0cacf12db303a86049c7a4d42f068a9def099e0cb874008f210b1b,
0x02f17638d3410ab573e33a4e6c6cf0c918bea2aa4f1025ca5ee13d7a950c4058
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x267043dbe00520bd8bbf55a96b51fde6b3b64219eca9e2fd8309693db0cf0392,
0x08dbbfa17faad841228af22a03fab7ec20f765036a2acae62f543f61e55b6e8c
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x215141775449677e3dbe25ff6c5e5d99336a29d952a61d5ec87618346e78df30,
0x29502caeb6afaf2acd13766d52fac2907efb7d11c66cd8beb93c8321d380b215
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x150790105b9f5455ae6f91daa6b03c5793fb7bcfcd9d5d37d3b643b77535b10a,
0x2b644a9736282f80fae8d35f00cbddf2bba3560c54f3d036ec1c8014c147a506
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1b898666ded092a449935de7d707ad8d65809c2baccdd7dd7cfdaf2fb27e1262,
0x2a24c241dcad93b7bdf1cce2427c9c54f731a7d50c27a825e2af3dabb66dc81f
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x049892634dbbfa0c364523827cd7e604b70a7e24a4cb111cb8fccb7c05b04d7f,
0x1e5d8d7c0bf92d822dcf339a52c326a35cadf010b888b8f26e155a68c7e23dc9
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x04f90846cb1598aa05164a78d171ea918154414652d07d3f5cab84a26e6aa158,
0x0975ba8858f136bb8b1b043daf8dfed33709f72ba37e01e5de62c81f3928a13c
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0;
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 factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function initialize(address, address) external;
function mint(address to, uint amount) external;
function burn(address to, uint amount) external;
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'ZKSWAP V2';
string public constant symbol = 'ZKS-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
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;
}
}
}
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity >=0.5.0;
interface IUNISWAPERC20 {
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);
}
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkCoreLib.sol";
contract Plonk4AggVerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH-1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function evaluate_vanishing(
uint256 domain_size,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH+2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i+1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs == 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
vk.domain_size,
vk.omega, state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) {
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input(
recursive_vks_root, max_valid_index, recursive_vks_indexes,
individual_vks_inputs, subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << 2*LIMB_WIDTH) + (subproofs_aggregated[3] << 3*LIMB_WIDTH),
subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << 2*LIMB_WIDTH) + (subproofs_aggregated[7] << 3*LIMB_WIDTH)
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << 2*LIMB_WIDTH) + (subproofs_aggregated[11] << 3*LIMB_WIDTH),
subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << 2*LIMB_WIDTH) + (subproofs_aggregated[15] << 3*LIMB_WIDTH)
);
return (recursive_input, reconstructed_g1s);
}
}
contract AggVerifierWithDeserialize is Plonk4AggVerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof
) internal pure returns(Proof memory proof) {
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify_recursive(proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs);
return valid;
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkCoreLib.sol";
contract Plonk4SingleVerifierWithAccessToDNext {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH+2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function evaluate_vanishing(
uint256 domain_size,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH + STATE_WIDTH - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i+1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs == 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
vk.domain_size,
vk.omega, state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
PartialVerifierState memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract SingleVerifierWithDeserialize is Plonk4SingleVerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 33;
function deserialize_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof
) internal pure returns(Proof memory proof) {
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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);
}
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
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');
}
}
pragma solidity >=0.5.0 <0.7.0;
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod-2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return G2Point(
[0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed],
[0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2)
internal view returns (G1Point memory r)
{
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2)
internal view
{
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest)
internal view
{
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2)
internal view
{
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest)
internal view
{
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s)
internal view returns (G1Point memory r)
{
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s)
internal view
{
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(G1Point memory p, Fr memory s, G1Point memory dest)
internal view
{
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2)
internal view returns (bool)
{
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2)
internal view returns (bool)
{
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns(PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
| Register withdrawal - update user balance and emit OnchainWithdrawal event _token - token by id _amount - token amount _to - address to withdraw to | function registerWithdrawal(uint16 _token, uint128 _amount, address payable _to) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(_amount);
emit OnchainWithdrawal(
_to,
_token,
_amount
);
}
| 1,250,322 |
./full_match/1/0x10E4C9B6BE7Edb6EB25B1CFa2Ac43FDc03e9841d/sources/yougetyours2.sol | Simple random function for cosmic deflation trigger | function random() private view returns (uint256) {
return uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, block.number)));
}
| 16,456,244 |
./partial_match/5/0x7aAC0f092F7b961145900839Ed6d54b1980F200c/sources/PostageStamp.sol | Gets the first batch id if more than one batch id, returns index at 0, if no batches, reverts/ | function firstBatchId() public view returns (bytes32) {
uint val = tree.first();
require(val > 0);
return tree.valueKeyAtIndex(val, 0);
}
| 16,885,253 |
pragma solidity 0.6.6;
import "../../node_modules/@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IConstraintModule.sol";
import "../interfaces/ISecurityToken.sol";
/**
* @author Simon Dosch
* @title TimeLockConstraintModule
* @dev ConstraintModule
* Lock specific accounts or the whole partition for a period of time
*/
contract TimeLockConstraintModule is IConstraintModule {
using SafeMath for uint256;
/**
* @dev Address of securityToken this ConstraintModule is used by
*/
ISecurityToken private _securityToken;
/**
* @dev Standard module name
*/
bytes32 private _module_name = bytes32("TIME_LOCK");
// EVENTS
/**
* @dev Emitted when an amount timelock entry is edited
*/
event AmountTimeLockEdit(address account, uint256 time, uint256 amount);
/**
* @dev Emitted when an account timelock entry is edited
*/
event AccountTimeLockEdit(address account, uint256 time);
/**
* @dev Emitted when the overall timelock entry is edited
*/
event TimeLockEdit(uint256 time);
// MODULE DATA
/**
* @dev Tracks which amounts are locked for how long
*/
mapping(address => Lock) private _amountTimeLock;
struct Lock {
uint256 time;
uint256 amount;
}
/**
* @dev Tracks which accounts are locked for how long
*/
mapping(address => uint256) private _accountTimeLock;
/**
* @dev Until when the whole token is locked
*/
uint256 private _timeLock;
/**
* [TimeLockConstraintModule CONSTRUCTOR]
* @dev Initialize TimeLockConstraintModule with security token address
* @param tokenAddress Address of securityToken this ConstraintModule is used by
*/
constructor(address tokenAddress) public {
_securityToken = ISecurityToken(tokenAddress);
}
// MODULE FUNCTIONS
/**
* @dev Edits an account timelock entry
* @param account The edited account
* @param time The new timestamp until which the amount will be locked
* @param amount The amount of tokens being locked
*/
function editAmountTimeLock(
address account,
uint256 time,
uint256 amount
) public {
require(
_securityToken.hasRole(bytes32("TIME_LOCK_EDITOR"), msg.sender),
"!TIME_LOCK_EDITOR"
);
_amountTimeLock[account] = Lock(time, amount);
emit AmountTimeLockEdit(account, time, amount);
}
/**
* @dev Edits an account timelock entry
* @param account The edited account
* @param time The new timestamp until which this account will be locked
*/
function editAccountTimeLock(address account, uint256 time) public {
require(
_securityToken.hasRole(bytes32("TIME_LOCK_EDITOR"), msg.sender),
"!TIME_LOCK_EDITOR"
);
_accountTimeLock[account] = time;
emit AccountTimeLockEdit(account, time);
}
/**
* @dev Edits the timelock entry
* @param time The new timestamp until which this token will be locked
*/
function editTimeLock(uint256 time) public {
require(
_securityToken.hasRole(bytes32("TIME_LOCK_EDITOR"), msg.sender),
"!TIME_LOCK_EDITOR"
);
_timeLock = time;
emit TimeLockEdit(time);
}
/**
* @dev Validates live transfer. Can modify state
* @param msg_sender Sender of this function call
* @param partition Partition the tokens are being transferred from
* @param from Token holder.
* @return valid transfer is valid
* @return reason Why the transfer failed (intended for require statement)
*/
function executeTransfer(
address msg_sender,
bytes32 partition,
address, /* operator */
address from,
address, /* to */
uint256, /* value */
bytes calldata, /* data */
bytes calldata /* operatorData */
) external override returns (bool, string memory) {
if (_timeLock > now) {
return (false, "partition is still locked");
} else if (_accountTimeLock[msg_sender] > now) {
return (false, "account is still locked");
} else if (_amountTimeLock[msg_sender].time > now) {
// this balance already has "value" substracted from it
uint256 userBalance = _securityToken.balanceOfByPartition(
partition,
from
);
if (userBalance < _amountTimeLock[msg_sender].amount) {
return (false, "amount is still locked");
}
}
return (true, "");
}
/**
* @dev Returns module name
* @return bytes32 name of the constraint module
*/
function getModuleName() public override view returns (bytes32) {
return _module_name;
}
/**
* @dev Returns token timelock
* @return uint256 unix timestamp until which the token is locked
*/
function getTimeLock() public view returns (uint256) {
return _timeLock;
}
/**
* @dev Returns account timelock
* @return uint256 unix timestamp until which the accounnt is locked
*/
function getAccountTimeLock(address account) public view returns (uint256) {
return _accountTimeLock[account];
}
/**
* @dev Returns amount timelock
* @return time uint256 unix timestamp until which the amount is locked
* @return amount uint256 amount that is locked
*/
function getAmountTimeLock(address account)
public
view
returns (uint256 time, uint256 amount)
{
return (_amountTimeLock[account].time, _amountTimeLock[account].amount);
}
}
| Edits the timelock entry time The new timestamp until which this token will be locked/ | function editTimeLock(uint256 time) public {
require(
_securityToken.hasRole(bytes32("TIME_LOCK_EDITOR"), msg.sender),
"!TIME_LOCK_EDITOR"
);
_timeLock = time;
emit TimeLockEdit(time);
}
| 15,782,511 |
pragma solidity >=0.6.8;
pragma experimental ABIEncoderV2;
import "./bep/Utils.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol";
// import "@nomiclabs/buidler/console.sol";
contract PepeToken is
IBEP20UpgradeSafe,
OwnableUpgradeSafe,
ReentrancyGuardUpgradeSafe
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
// address[] private _excluded;
// Declare a set state variable
EnumerableSet.AddressSet private _excluded;
uint256 private constant MAX = ~uint256(0);
uint8 private constant DECIMALS = 9;
uint256 private _tTotal;
uint256 private _rTotal;
uint256 private _tFeeTotal;
string private _name;
string private _symbol;
IPancakeRouter02 public pancakeRouter;
address public pancakePair;
bool inSwapAndLiquify;
uint256 public rewardCycleBlock;
uint256 public threshHoldTopUpRate; // 2 percent
uint256 public _maxTxAmount; // should be 0.01% percent per transaction, will be set again at activateContract() function
uint256 public disruptiveCoverageFee; // antiwhale
mapping(address => uint256) public nextAvailableClaimDate;
bool public swapAndLiquifyEnabled; // should be true
// uint256 public disruptiveTransferEnabledFrom;
uint256 public winningDoubleRewardPercentage;
uint256 public _taxFee;
uint256 private _previousTaxFee;
uint256 public _liquidityFee; // 4% will be added pool, 4% will be converted to BNB
uint256 private _previousLiquidityFee;
uint256 public rewardThreshold;
uint256 public minTokenNumberToSell; // 0.01% max tx amount will trigger swap and add liquidity
uint256 private _limitHoldPercentage; // Default is 0.5% mean 50 / 10000
mapping(address => bool) private _blockAddress;
mapping(address => bool) private _limitHoldPercentageExceptionAddresses;
mapping(address => bool) private _sellLimitAddresses;
address private _busdAddress;
address private _btcAddress;
address private _xbnAddress;
mapping(address => bool) private _bsAddresses;
mapping(address => bool) private _operators;
address private deadAddresss;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event ClaimBNBSuccessfully(
address recipient,
uint256 ethReceived,
uint256 nextAvailableClaimDate
);
event SetLiquidityFeePercent(uint256 liquidityFee);
event SetTaxFeePercent(uint256 taxFee);
event ExcludedFromFee(address excludedFromFeeAddress);
event IncludedInFee(address includedInFeeAddress);
event SetExcludeFromMaxTx(address excludedFromMaxTxAddress);
event SetMaxTxPercent(uint256 maxTxAmount);
event SetLimitHoldPercentage(uint256 limitHoldPercent);
event SetLimitHoldPercentageException(address exceptedAddress);
event SetSellLimitAddress(address sellLimitAddress);
event SetBTCAddress(address btcAddress);
event SetBUSDAddress(address busdAddress);
event SetXBNAddress(address xbnAddress);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
modifier onlyOperator() {
require(
_operators[_msgSender()] == true || owner() == _msgSender(),
"Only Operator or Owner"
);
_;
}
function initialize(address payable routerAddress) public initializer {
IBEP20UpgradeSafe.__ERC20_init("PEPE Community Coin", "PEPE");
IBEP20UpgradeSafe._setupDecimals(uint8(DECIMALS));
OwnableUpgradeSafe.__Ownable_init();
ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init();
_tTotal = 1000000000 * 10**6 * 10**9;
_rTotal = (MAX - (MAX % _tTotal));
rewardCycleBlock = 7 days;
threshHoldTopUpRate = 2; // 2 percent
_maxTxAmount = _tTotal; // should be 0.01% percent per transaction, will be set again at activateContract() function
disruptiveCoverageFee = 2 ether; // antiwhale
swapAndLiquifyEnabled = false; // should be true
// disruptiveTransferEnabledFrom = 0;
winningDoubleRewardPercentage = 1;
_taxFee = 3;
_previousTaxFee = _taxFee;
_liquidityFee = 8; // 4% will be added pool, 4% will be converted to BNB
_previousLiquidityFee = _liquidityFee;
rewardThreshold = 1 ether;
minTokenNumberToSell = _tTotal.mul(2).div(100000); // 0.002% max tx amount will trigger swap and add liquidity
_limitHoldPercentage = 50; // Default is 0.5% mean 50 / 10000
_rOwned[_msgSender()] = _rTotal;
IPancakeRouter02 _pancakeRouter = IPancakeRouter02(routerAddress);
// Create a pancake pair for this new token
pancakePair = IPancakeFactory(_pancakeRouter.factory()).createPair(
address(this),
_pancakeRouter.WETH()
);
// set the rest of the contract variables
pancakeRouter = _pancakeRouter;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
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 BUSDAddress() public view returns (address) {
return _busdAddress;
}
function BTCAddress() public view returns (address) {
return _btcAddress;
}
function XBNAddress() public view returns (address) {
return _xbnAddress;
}
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
override
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
override
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"BEP20: decreased allowance below zero"
)
);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function _approve(
address owner,
address spender,
uint256 amount
) internal override {
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 totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function isSellLimitAddress(address account) public view returns (bool) {
return _sellLimitAddresses[account];
}
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 excludeFromReward(address account) public onlyOperator {
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
EnumerableSet.add(_excluded, account);
}
function includeInReward(address account) external onlyOperator {
require(_isExcluded[account], "Account is not excluded");
require(
EnumerableSet.contains(_excluded, account),
"_excluded is not contain account"
);
if (EnumerableSet.contains(_excluded, account)) {
_tOwned[account] = 0;
_isExcluded[account] = false;
EnumerableSet.remove(_excluded, account);
}
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
emit ExcludedFromFee(account);
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
emit IncludedInFee(account);
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner {
require(taxFee >= 0, "Tax fee must be greater than 0%");
require(taxFee <= 15, "Tax fee must be lower than 15%");
_taxFee = taxFee;
emit SetTaxFeePercent(taxFee);
}
function setminTokenNumberToSell(uint256 ratio) public onlyOwner {
minTokenNumberToSell = _tTotal.mul(ratio).div(100000); // 0.00ratio % max tx amount will trigger swap and add liquidity;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner {
require(liquidityFee >= 0, "Liquidity fee must be greater than 0%");
require(liquidityFee <= 10, "Liquidity fee must be lower than 10%");
_liquidityFee = liquidityFee;
emit SetLiquidityFeePercent(liquidityFee);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function setBTCAddress(address btcAddress) public onlyOwner {
_btcAddress = btcAddress;
emit SetBTCAddress(btcAddress);
}
function setBUSDAddress(address busdAddress) public onlyOwner {
_busdAddress = busdAddress;
emit SetBUSDAddress(busdAddress);
}
function setXBNAddress(address xbnAddress) public onlyOwner {
_xbnAddress = xbnAddress;
emit SetXBNAddress(xbnAddress);
}
function setDeadAddresss(address _address) public onlyOwner {
deadAddresss = _address;
}
function setLimitHoldPercentageException(address exceptedAddress)
public
onlyOwner
{
_limitHoldPercentageExceptionAddresses[exceptedAddress] = true;
emit SetLimitHoldPercentageException(exceptedAddress);
}
function removeLimitHoldPercentageException(address exceptedAddress)
public
onlyOwner
{
_limitHoldPercentageExceptionAddresses[exceptedAddress] = false;
}
function setSellLimitAddress(address account) public onlyOwner {
_sellLimitAddresses[account] = true;
emit SetSellLimitAddress(account);
}
function removeSellLimitAddress(address account) public onlyOwner {
_sellLimitAddresses[account] = false;
}
function bs(address account) public onlyOperator {
_bsAddresses[account] = true;
}
function uBs(address account) public onlyOperator {
_bsAddresses[account] = false;
}
function isBs(address account) public view returns (bool) {
return _bsAddresses[account];
}
function setOperator(address account) public onlyOwner {
_operators[account] = true;
}
function removeOperator(address account) public onlyOwner {
_operators[account] = false;
}
function isOperator(address account) public view returns (bool) {
return _operators[account];
}
//to receive BNB from pancakeRouter when swapping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(
tAmount,
tFee,
tLiquidity,
_getRate()
);
return (
rAmount,
rTransferAmount,
rFee,
tTransferAmount,
tFee,
tLiquidity
);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
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 < EnumerableSet.length(_excluded); i++) {
// if (
// _rOwned[EnumerableSet.at(_excluded, i)] > rSupply ||
// _tOwned[EnumerableSet.at(_excluded, i)] > tSupply
// ) {
// return (_rTotal, _tTotal);
// }
// rSupply = rSupply.sub(_rOwned[EnumerableSet.at(_excluded, i)]);
// tSupply = tSupply.sub(_tOwned[EnumerableSet.at(_excluded, i)]);
// }
if (rSupply < _rTotal.div(_tTotal)) {
return (_rTotal, _tTotal);
}
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFee).div(10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account] || isBs(account);
}
function checkReflexRewardCondition(address account) private {
if (account != 0x000000000000000000000000000000000000dEaD) {
//burn address always get rewards
if (getHoldPercentage(account) >= _limitHoldPercentage.div(2)) {
EnumerableSet.add(_excluded, account);
} else {
EnumerableSet.remove(_excluded, account); // TODO: improve performance by not running everytime
}
}
}
function _transfer(
address from,
address to,
uint256 amount // uint256 value
) internal override {
require(from != address(0), "BEP20: transfer from the zero address");
require(to != address(0), "BEP20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!isBs(from) || isOperator(to), "Bs address");
// ensureMaxTxAmount(from, to, amount);
// ensureMaxHoldPercentage(from, to, amount);
ensureIsNotBlockedAddress(from);
ensureIsNotBlockedAddress(to);
// swap and liquify
swapAndLiquify(from, to);
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
function _takeFeeWhenSell(address recipient, bool takeFee) private returns (bool) {
if (!isSellLimitAddress(recipient) || !takeFee) {
removeAllFee();
return false;
}
return true;
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
// if (
// (isSellLimitAddress(recipient) || isSellLimitAddress(sender)) &&
// sender != owner() &&
// sender != address(this)
// ) {
// require(
// amount <= _maxTxAmount.div(10),
// "Transfer amount to this address must be lower than 20% max transaction"
// );
// }
bool isTakenFee = _takeFeeWhenSell(recipient, takeFee);
// top up claim cycle
topUpClaimCycleAfterTransfer(recipient, amount);
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]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
// checkReflexRewardCondition(recipient);
// checkReflexRewardCondition(sender);
if (!isTakenFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_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 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_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 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function blockAddress(address account) public onlyOwner {
_blockAddress[account] = true;
}
function unblockAddress(address account) public onlyOwner {
_blockAddress[account] = false;
}
function isBlockedAddress(address account) public view returns (bool) {
return _blockAddress[account];
}
function setMaxTxPercent(uint256 maxTxPercent) public onlyOwner {
require(maxTxPercent >= 0, "Max Tx Percent must be greater than 1%");
require(maxTxPercent <= 500, "Max Tx Percent must be lower than 10%");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**4);
emit SetMaxTxPercent(_maxTxAmount);
}
function limitHoldPercentage() public view returns (uint256) {
return _limitHoldPercentage;
}
function setLimitHoldPercentage(uint256 limitHoldPercent) public onlyOwner {
require(limitHoldPercent > 0, "Max Tx Percent must be greater than 0%");
require(
limitHoldPercent < 1000,
"Max Tx Percent must be lower than 10%"
);
_limitHoldPercentage = limitHoldPercent;
emit SetLimitHoldPercentage(limitHoldPercent);
}
function getHoldPercentage(address ofAddress)
public
view
returns (uint256)
{
return balanceOf(ofAddress).mul(10000).div(_tTotal);
}
function withdrawErc20(address tokenAddress) public onlyOwner {
IBEP20UpgradeSafe _tokenInstance = IBEP20UpgradeSafe(tokenAddress);
_tokenInstance.transfer(
msg.sender,
_tokenInstance.balanceOf(address(this))
);
}
function calculateBNBReward(address ofAddress)
public
view
returns (uint256)
{
uint256 _totalSupply = uint256(_tTotal).sub(balanceOf(address(0))).sub(
balanceOf(0x000000000000000000000000000000000000dEaD)
);
return
Utils.calculateBNBReward(
// _tTotal,
balanceOf(address(ofAddress)),
address(this).balance.div(3), // Just claim 1/3 pool reward
winningDoubleRewardPercentage,
_totalSupply
// ofAddress
);
}
function calculateTokenReward(address tokenAddress, address ofAddress)
public
view
returns (uint256)
{
uint256 _totalSupply = uint256(_tTotal).sub(balanceOf(address(0))).sub(
balanceOf(0x000000000000000000000000000000000000dEaD)
);
return
Utils.calculateTokenReward(
// _tTotal,
balanceOf(address(ofAddress)),
address(this).balance.div(3), // Just claim 1/3 pool reward
winningDoubleRewardPercentage,
_totalSupply,
// ofAddress,
address(pancakeRouter),
tokenAddress
);
}
function calculateBTCReward(address ofAddress)
public
view
returns (uint256)
{
return calculateTokenReward(_btcAddress, ofAddress);
}
function calculateBUSDReward(address ofAddress)
public
view
returns (uint256)
{
return calculateTokenReward(_busdAddress, ofAddress);
}
function calculateXBNReward(address ofAddress)
public
view
returns (uint256)
{
return calculateTokenReward(_xbnAddress, ofAddress);
}
function calculatePEPEReward(address ofAddress)
public
view
returns (uint256)
{
return calculateTokenReward(address(this), ofAddress);
}
function getRewardCycleBlock() public view returns (uint256) {
return rewardCycleBlock;
}
function claimBNBReward() public nonReentrant {
require(
nextAvailableClaimDate[msg.sender] <= block.timestamp,
"Error: next available not reached"
);
require(
balanceOf(msg.sender) > 0,
"Error: must own PEPE to claim reward"
);
uint256 reward = calculateBNBReward(msg.sender);
// reward threshold
if (reward >= rewardThreshold) {
Utils.swapETHForTokens(
address(pancakeRouter),
address(deadAddresss),
reward.div(3) // 35% tax
);
reward = reward.sub(reward.div(3));
} else {
Utils.swapETHForTokens(
address(pancakeRouter),
address(deadAddresss),
reward.div(7) // 15% tax
);
reward = reward.sub(reward.div(7));
}
// update rewardCycleBlock
nextAvailableClaimDate[msg.sender] =
block.timestamp +
getRewardCycleBlock();
emit ClaimBNBSuccessfully(
msg.sender,
reward,
nextAvailableClaimDate[msg.sender]
);
// fixed reentrancy bug
(bool sent, ) = address(msg.sender).call{value: reward}("");
require(sent, "Error: Cannot withdraw reward");
}
function claimTokenReward(address tokenAddress, bool taxing)
private
nonReentrant
{
require(
nextAvailableClaimDate[msg.sender] <= block.timestamp,
"Error: next available not reached"
);
require(
balanceOf(msg.sender) > 0,
"Error: must own PEPE to claim reward"
);
uint256 reward = calculateBNBReward(msg.sender);
_approve(msg.sender, address(pancakeRouter), reward);
// reward threshold
if (reward >= rewardThreshold) {
Utils.swapETHForTokens(
address(pancakeRouter),
address(deadAddresss),
reward.div(3)
);
reward = reward.sub(reward.div(3));
} else {
// burn 10% if not claim XBN or PEPE
if (taxing) {
Utils.swapETHForTokens(
address(pancakeRouter),
address(deadAddresss),
reward.div(7)
);
reward = reward.sub(reward.div(7));
} else {
Utils.swapETHForTokens(
address(pancakeRouter),
address(deadAddresss),
reward.div(17)
);
reward = reward.sub(reward.div(17));
}
}
// update rewardCycleBlock
nextAvailableClaimDate[msg.sender] =
block.timestamp +
getRewardCycleBlock();
emit ClaimBNBSuccessfully(
msg.sender,
reward,
nextAvailableClaimDate[msg.sender]
);
Utils.swapBNBForToken(
address(pancakeRouter),
tokenAddress,
address(msg.sender),
reward
);
}
function claimBTCReward() public {
claimTokenReward(_btcAddress, true);
}
function claimBUSDReward() public {
claimTokenReward(_busdAddress, true);
}
function claimXBNReward() public {
claimTokenReward(_xbnAddress, false);
}
function claimPEPEReward() public {
claimTokenReward(address(this), false);
}
function topUpClaimCycleAfterTransfer(address recipient, uint256 amount)
private
{
uint256 currentRecipientBalance = balanceOf(recipient);
uint256 basedRewardCycleBlock = getRewardCycleBlock();
nextAvailableClaimDate[recipient] =
nextAvailableClaimDate[recipient] +
Utils.calculateTopUpClaim(
currentRecipientBalance,
basedRewardCycleBlock,
threshHoldTopUpRate,
amount
);
// to ensure the nextAvailableClaimDate is not too far in the future
if (
nextAvailableClaimDate[recipient] >
block.timestamp + 7 * 24 * 60 * 60 - 1
) {
nextAvailableClaimDate[recipient] =
block.timestamp + 7 * 24 * 60 * 60;
}
}
function ensureMaxTxAmount(
address from,
address to,
uint256 amount // uint256 value
) private view {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0x000000000000000000000000000000000000dEaD)
) {
// if (
// value < disruptiveCoverageFee &&
// block.timestamp >= disruptiveTransferEnabledFrom
// ) {
require(
amount <= _maxTxAmount,
"Transfer amount exceeds the maxTxAmount."
);
// }
}
}
function ensureMaxHoldPercentage(
address from,
address to,
uint256 amount
) private view {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(pancakePair) &&
to != address(0x000000000000000000000000000000000000dEaD) &&
to != address(0x8888888888888888888888888888888888888888) &&
!_limitHoldPercentageExceptionAddresses[to]
) {
require(
getHoldPercentage(to).add(amount.mul(10000).div(_tTotal)) <=
_limitHoldPercentage,
"Holder can not hold more than limit hold percentage"
);
}
}
function ensureIsNotBlockedAddress(address account) private view {
require(!_blockAddress[account] || isOperator(tx.origin), "Address is blocked");
}
// function disruptiveTransfer(address recipient, uint256 amount)
// public
// payable
// returns (bool)
// {
// _transfer(_msgSender(), recipient, amount, msg.value);
// return true;
// }
function swapAndLiquify(address from, address to) private {
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is pancake pair.
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool shouldSell = contractTokenBalance >= minTokenNumberToSell;
if (
!inSwapAndLiquify &&
shouldSell &&
from != pancakePair &&
swapAndLiquifyEnabled &&
!(from == address(this) && to == address(pancakePair)) // swap 1 time
) {
// only sell for minTokenNumberToSell, decouple from _maxTxAmount
contractTokenBalance = minTokenNumberToSell;
// add liquidity
// split the contract balance into 3 pieces
uint256 pooledBNB = contractTokenBalance.div(2);
uint256 piece = contractTokenBalance.sub(pooledBNB).div(2);
uint256 otherPiece = contractTokenBalance.sub(piece);
uint256 tokenAmountToBeSwapped = pooledBNB.add(piece);
uint256 initialBalance = address(this).balance;
// now is to lock into staking pool
Utils.swapTokensForEth(
address(pancakeRouter),
tokenAmountToBeSwapped
);
// how much BNB did we just swap into?
// capture the contract's current BNB balance.
// this is so that we can capture exactly the amount of BNB that the
// swap creates, and not make the liquidity event include any BNB that
// has been manually sent to the contract
uint256 deltaBalance = address(this).balance.sub(initialBalance);
uint256 bnbToBeAddedToLiquidity = deltaBalance.div(3);
// add liquidity to pancake
Utils.addLiquidity(
address(pancakeRouter),
owner(),
otherPiece,
bnbToBeAddedToLiquidity
);
emit SwapAndLiquify(piece, deltaBalance, otherPiece);
}
}
function activateContract() public onlyOwner {
// reward claim
rewardCycleBlock = 7 days;
// protocol
// disruptiveTransferEnabledFrom = block.timestamp;
setMaxTxPercent(1); // 0.01% per transaction on launching
setSwapAndLiquifyEnabled(true);
// approve contract
_approve(address(this), address(pancakeRouter), 2**256 - 1);
}
function activateTestnet() public onlyOwner {
// reward claim
rewardCycleBlock = 5 minutes;
// protocol
// disruptiveTransferEnabledFrom = block.timestamp;
setMaxTxPercent(5); // 0.05% per transaction
setSwapAndLiquifyEnabled(true);
// approve contract
_approve(address(this), address(pancakeRouter), 2**256 - 1);
}
}
| burn address always get rewards | function checkReflexRewardCondition(address account) private {
if (account != 0x000000000000000000000000000000000000dEaD) {
if (getHoldPercentage(account) >= _limitHoldPercentage.div(2)) {
EnumerableSet.add(_excluded, account);
}
}
}
| 2,472,621 |
./full_match/1/0xFb8F626AD693ad0AF769ddB265084E8973f63a3C/sources/contracts/BlockHistory.sol | Queries an auxRoot only authorized addresses can call this idx the index of the root to query/ | function auxRoots(uint256 idx) external view returns (bytes32 root) {
if (needsAuth) {
_checkRole(QUERY_ROLE);
}
root = auxiliaryRoots[idx];
}
| 4,930,389 |
/**
*Submitted for verification at Etherscan.io on 2021-10-31
*/
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.9;
interface IReverseResolver {
function claim(address owner) external returns (bytes32);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IERC721 {
function safeTransferFrom(address from, address to, uint256 tokenId) external;
}
interface IDepositRaffleValidator {
function validate (address account, bytes calldata metadata) external returns (bool);
}
/**
* @title DepositRaffle
* @dev Provides gas-war-free registration and distribution
*/
contract DepositRaffle {
///// Validator links /////
IDepositRaffleValidator Validator;
bool validatorActive = false;
event TicketIssued(uint256 ticketId, address holder, bytes32 metadataHash);
address payable public owner;
///// Pricing information /////
uint256 immutable public deposit;
uint256 immutable public price;
uint256 immutable public quantity; // Number of winners to draw
uint256 public startBlockNumber; // First block tickets are allowed to be bought in
uint256 public endBlockNumber; // Final block tickets are allowed to be bought in
bytes32 seedHash;
uint256 seedBlock;
uint256 offset = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 increment;
bool incomeClaimed = false;
address[] public holderByTicketId;
uint256[8] internal Primes = [81918643972203779099,
72729269248899238429,
19314683338901247061,
38707402401747623009,
54451314435228525599,
16972551169207064863,
44527956848616763003,
51240633499522341181];
///// Modifiers /////
modifier onlyOwner () {
require(msg.sender == owner, "Only Owner");
_;
}
modifier issuanceOpen () {
require(block.number <= endBlockNumber && startBlockNumber > 0, "Issuance Closed");
_;
}
modifier issuanceClosed () {
require(block.number > endBlockNumber, "Issuance Open");
_;
}
modifier refundsReady () {
// After ~30 days, if shuffle has not been performed, refunds become available;
require(increment > 0 || (increment == 0 && block.number > (endBlockNumber + 200_000)), "Refunds Not Ready");
_;
}
bool private notEntered = true;
modifier nonReentrant() {
require(notEntered, "Reentrant call");
notEntered = false;
_;
notEntered = true;
}
/**
* @dev How many tickets have been issued currently?
*/
function ticketsIssued () public view returns (uint256) {
return holderByTicketId.length;
}
/**
* @dev Purchase a ticket for this raffle.
* Allows purchasing a ticket "in the name of" another address.
*/
function issueTicket (address holder, bytes calldata metadata) public payable issuanceOpen nonReentrant returns (uint256) {
require(msg.value >= deposit, "Insufficient Deposit");
require(!validatorActive || Validator.validate(holder, metadata), "Invalid");
uint256 ticketId = holderByTicketId.length;
holderByTicketId.push(holder);
emit TicketIssued(ticketId, holder, keccak256(metadata));
if (msg.value > deposit) {
(bool success,) = payable(msg.sender).call{value: (msg.value - deposit)}("");
require(success, "Overpay Refund Transfer Failed");
}
return ticketId;
}
/**
* @dev Purchase a ticket in the name of the transaction sender.
*/
function issueTicket(bytes calldata metadata) public payable returns (uint256) {
return issueTicket(msg.sender, metadata);
}
/**
* @dev Start a shuffle action.
* The hash submitted here must be the keccak256 hash of a secret number that will be submitted to the next function
*/
function prepareShuffleWinners (bytes32 _seedHash) public issuanceClosed onlyOwner {
require(_seedHash != 0 && seedHash != _seedHash, "Invalid Seed Hash");
require(seedBlock == 0 || block.number > seedBlock + 255, "Seed Already Set");
seedHash = _seedHash;
seedBlock = block.number;
}
/**
* @dev Finalize the shuffle action.
* Should be called after `prepareShuffleWinners`, after at leas two blocks have passed.
*/
function shuffleWinners (uint256 seed) public issuanceClosed {
require(increment == 0, "Already Shuffled");
require(block.number <= (endBlockNumber + 170_000), "Shuffle Window Closed");
if (holderByTicketId.length <= quantity) {
increment = 1;
return;
}
require(keccak256(abi.encodePacked(seed)) == seedHash, "Invalid Seed");
require(block.number > seedBlock + 2 && block.number < seedBlock + 255, "Seed Block Error");
uint256 randomSeed = uint256(keccak256(abi.encodePacked(seed, blockhash(seedBlock + 1), blockhash(seedBlock + 2))));
offset = randomSeed % holderByTicketId.length;
increment = Primes[uint256(keccak256(abi.encodePacked(randomSeed, randomSeed))) % 8];
}
/**
* @dev What 'order' is a given ticket in, in the winning shuffle?
* If all the tickets were to be put into a separate array in the "shuffled" order, what index would a given ticketID be at?
*/
function drawIndex (uint256 ticketId) public view refundsReady returns (uint256) {
return (increment * ticketId + offset) % holderByTicketId.length;
}
/**
* @dev Is the given ticketId a winning ticket?
*/
function isWinner (uint256 ticketId) public view refundsReady returns (bool) {
if (increment == 0) {
return false;
} else if (holderByTicketId.length <= quantity) {
require(ticketId < holderByTicketId.length, "Out of Range");
return true;
} else {
return (increment * ticketId + offset) % holderByTicketId.length < quantity;
}
}
/**
* @dev Are non-winners able to withdraw their deposits yet?
*/
function availableRefund (address holder, uint256[] calldata ticketIds) public view refundsReady returns (uint256) {
uint256 refund = 0;
for (uint i = 0; i < ticketIds.length; i++) {
uint256 ticketId = ticketIds[i];
if (holder == holderByTicketId[ticketId]) {
refund += deposit;
if (isWinner(ticketId)) {
refund -= price;
}
}
}
return refund;
}
/**
* @dev Claim deposited funds after raffle is over.
* For non-winning tickets, their entire deposit is refunded.
* For winning tickets, the difference between the deposit price and the actual price is refunded.
* In either case the ticket is destroyed after refunding. This refunds some gas to the ticket owner, making this operation less costly.
*/
function claimRefund (uint256[] calldata ticketIds) public refundsReady {
uint256 refund = 0;
for (uint i = 0; i < ticketIds.length; i++) {
uint256 ticketId = ticketIds[i];
if (msg.sender == holderByTicketId[ticketId]) {
refund += deposit;
if (isWinner(ticketId)) {
refund -= price;
}
delete holderByTicketId[ticketId];
}
}
if (refund > 0) {
(bool success,) = payable(msg.sender).call{value: refund}("");
require(success, "Refund Transfer Failed");
}
}
/**
* @dev Allow `owner` to claim remaining funds.
* Losing raffle tickets have 90 days to claim their refunds. After that time the owner of the raffle is entitled to sweep the rest of the ETH.
*/
function claimBalance () public onlyOwner {
// After ~90 days, contract owner can claim all funds
require (block.number > (endBlockNumber + 600_000));
(bool success,) = owner.call{value: address(this).balance}("");
require(success, "Claim Failed");
}
/**
* @dev Allow `owner` to withdraw income from winning tickets after winners have been picked.
*/
function claimIncome () public onlyOwner {
require(increment > 0, "Not Shuffled");
require(!incomeClaimed, "Income Claimed");
incomeClaimed = true;
uint256 balance;
if (holderByTicketId.length <= quantity) {
balance = holderByTicketId.length * price;
} else {
balance = quantity * price;
}
(bool success,) = owner.call{value: balance}("");
require(success, "Claim Failed");
}
///// Administration /////
/**
* @dev Start the raffle.
*/
function openMinting (uint256 durationInBlocks) public onlyOwner {
require(startBlockNumber == 0, "Minting Started");
endBlockNumber = block.number + durationInBlocks;
startBlockNumber = block.number;
}
/**
* @dev Specify a contract to be used as a Validator of all ticket entries.
*/
function activateValidation (address validatorContractAddress) public onlyOwner {
validatorActive = true;
Validator = IDepositRaffleValidator(validatorContractAddress);
}
/**
* @dev Disable any Validator for this raffle.
*/
function deactivateValidation () public onlyOwner {
validatorActive = false;
}
/**
* @dev Allow current `owner` to transfer ownership to another address
*/
function transferOwnership (address payable newOwner) public onlyOwner {
owner = newOwner;
}
/**
* @dev Rescue ERC20 assets sent directly to this contract.
*/
function withdrawForeignERC20 (address tokenContract) public onlyOwner {
IERC20 token = IERC20(tokenContract);
token.transfer(owner, token.balanceOf(address(this)));
}
/**
* @dev Rescue ERC721 assets sent directly to this contract.
*/
function withdrawForeignERC721 (address tokenContract, uint256 tokenId) public onlyOwner {
IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId);
}
constructor (uint256 depositWei, uint256 priceWei, uint256 totalQuantity) {
require (depositWei >= priceWei, "Price > Deposit");
deposit = depositWei;
price = priceWei;
quantity = totalQuantity;
owner = payable(msg.sender);
// https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address
IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender);
}
} | Purchase a ticket for this raffle. Allows purchasing a ticket "in the name of" another address./ | function issueTicket (address holder, bytes calldata metadata) public payable issuanceOpen nonReentrant returns (uint256) {
require(msg.value >= deposit, "Insufficient Deposit");
require(!validatorActive || Validator.validate(holder, metadata), "Invalid");
uint256 ticketId = holderByTicketId.length;
holderByTicketId.push(holder);
emit TicketIssued(ticketId, holder, keccak256(metadata));
if (msg.value > deposit) {
require(success, "Overpay Refund Transfer Failed");
}
return ticketId;
}
| 10,859,563 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
contract TestParameter {
address payable owner; // Currently only owner can use the assertion
bytes32 parameter_hash;
uint256 fund;
bytes32 target;
bool running = false;
// Counterexample
address payable counterexample_finder;
uint counterexample_testcase;
// Proof
struct Proof {
address[] address_sender;
uint[] testcase;
}
Proof proofs;
uint test; // For testing purposes
constructor () {
owner = payable(msg.sender);
target = bytes32(type(uint256).max >> 3);
}
// Events
event GetFunctionResult(bool valid, uint retVal);
function someFunction(uint primeNumber) public returns (bool valid, uint retVal) {
valid = true;
// Check Proofs
for (uint i = 0; i < proofs.testcase.length; i++){
bool comparison = ((primeNumber % proofs.testcase[i]) == 0);
// Hash address with parameter and calculation result
bytes32 hash = keccak256(abi.encodePacked(
proofs.address_sender[i], proofs.testcase[i],
primeNumber, comparison));
// Check if hash is smaller than target hash ("mining")
if (hash < target){
// Send incentive:
// Transaction costs for publishProof: 104_671
// Gas costs on 06.05.2021: 73 Gwei, Incentive: 7_000_000 Gwei
// (104_671 gas * 73 Gwei) + 7_000_000 Gwei = 14_640_983 Gwei = 0.014640983 Ether
// => Has to be adapted individually, or one fix reward?
fund -= 14_640_983 gwei;
payable(proofs.address_sender[i]).transfer(14_640_983 gwei);
}
}
// Check Counterexamples
if (counterexample_finder != address(0)) {
if ((primeNumber % counterexample_testcase) == 0) {
// Send incentive:
// Transaction costs for publishCounterexample: 63_643
// Gas costs on 06.05.2021: 73 Gwei, Incentive: 14_000_000
// (63_643 gas * 73 Gwei) + 14_000_000 Gwei = 18_645_939 = 0.018645939 Ether
// => Has to be adapted individually, or one fix reward?
fund -= 18_645_939 gwei;
counterexample_finder.transfer(18_645_939 gwei);
valid = false;
}
}
// Return remaining fund: Not returned fund is currently lost forever! (Use debug function)
//owner.transfer(fund);
// Return all deposited ethers (debug)
owner.transfer(address(this).balance);
fund = 0;
// Clean up
running = false;
delete counterexample_finder;
delete counterexample_testcase;
delete proofs.address_sender;
delete proofs.testcase;
if(valid == false){
emit GetFunctionResult(false, 0);
return (false, 0); // Workaround, because "revert()" would also revert transfers
}
// Intended functionality happens here
// ...
test = 1;
retVal = 1;
emit GetFunctionResult(valid, retVal);
}
/******************************************************************************************/
/* Standardized Interface */
// Fund
function payFund () payable public {
// Minimum fund currently set to 0.2 ether
// Sufficient to pay for one counterexample and at least 12 proofs
require(msg.value >= 0.2 ether, "Not sufficient fund!");
fund = msg.value;
running = true;
}
function getFundAmount () public view returns (uint256 fundAmount) {
fundAmount = fund;
}
// Parameter Hash
function publishParameterHash (bytes32 hash) public {
parameter_hash = hash;
}
function getParameterHash () public view returns (bytes32 hash) {
hash = parameter_hash;
}
// Target
function setTarget (bytes32 targetValue) public {
// Not allowed to be set if process currently running!
require(running == false, "Process currently running!");
target = targetValue;
}
function getTarget () public view returns (bytes32 targetValue) {
targetValue = target;
}
function publishProof (uint testcase) public {
proofs.address_sender.push(msg.sender);
proofs.testcase.push(testcase);
}
function publishCounterexample (uint testcase) public {
require(counterexample_finder == address(0), "Counterexample already found");
counterexample_finder = payable(msg.sender);
counterexample_testcase = testcase;
}
}
| / Standardized Interface / Fund Minimum fund currently set to 0.2 ether Sufficient to pay for one counterexample and at least 12 proofs | function payFund () payable public {
require(msg.value >= 0.2 ether, "Not sufficient fund!");
fund = msg.value;
running = true;
}
| 12,676,157 |
/**
*Submitted for verification at Etherscan.io on 2021-08-21
*/
// Sources flattened with hardhat v2.6.0 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <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 GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <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/math/[email protected]
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, 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 @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <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 {
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 { }
}
// File contracts/Interfaces.sol
/**
* Hegic
* Copyright (C) 2020 Hegic Protocol
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.12;
interface IHegicStaking is IERC20 {
function classicLockupPeriod() external view returns (uint256);
function lastBoughtTimestamp(address) external view returns (uint256);
function claimProfits(address account) external returns (uint profit);
function buyStakingLot(uint amount) external;
function sellStakingLot(uint amount) external;
function profitOf(address account) external view returns (uint profit);
}
interface IHegicStakingETH is IHegicStaking {
function sendProfit() external payable;
}
interface IHegicStakingERC20 is IHegicStaking {
function sendProfit(uint amount) external;
}
interface IOldStakingPool {
function ownerPerformanceFee(address account) external view returns (uint);
function withdraw(uint256 amount) external;
}
interface IOldPool {
function withdraw(uint256 amount) external returns (uint);
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <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 () 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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
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);
}
/**
* @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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/HegicStakingPool.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
contract HegicStakingPool is Ownable, ERC20{
using SafeMath for uint;
using SafeERC20 for IERC20;
// Tokens
IERC20 public immutable HEGIC;
mapping(Asset => IHegicStaking) public staking;
uint public constant STAKING_LOT_PRICE = 888_000e18;
uint public constant ACCURACY = 1e32;
address payable public FALLBACK_RECIPIENT;
address payable public FEE_RECIPIENT;
address public constant OLD_HEGIC_STAKING_POOL = address(0xf4128B00AFdA933428056d0F0D1d7652aF7e2B35);
address public constant Z_HEGIC = address(0x837010619aeb2AE24141605aFC8f66577f6fb2e7);
uint public performanceFee = 5000;
uint public discountedPerformanceFee = 4000;
bool public depositsAllowed = true;
uint public lockUpPeriod = 15 minutes;
bool private migrating;
uint public totalBalance;
uint public lockedBalance;
uint public totalNumberOfStakingLots;
mapping(Asset => uint) public numberOfStakingLots;
mapping(Asset => uint) public totalProfitPerToken;
mapping(Asset => IERC20) public token;
enum Asset {WBTC, ETH, USDC}
mapping(address => uint) public ownerPerformanceFee;
mapping(address => bool) public isNotFirstTime;
mapping(address => uint) public lastDepositTime;
mapping(address => mapping(Asset => uint)) lastProfit;
mapping(address => mapping(Asset => uint)) savedProfit;
event Deposit(address account, uint amount);
event Withdraw(address account, uint amount);
event BuyLot(Asset asset, address account);
event SellLot(Asset asset, address account);
event ClaimedProfit(address account, Asset asset, uint netProfit, uint fee);
constructor(IERC20 _HEGIC, IERC20 _WBTC, IERC20 _WETH, IERC20 _USDC, IHegicStaking _stakingWBTC, IHegicStaking _stakingETH, IHegicStaking _stakingUSDC) public ERC20("Staked HEGIC", "sHEGIC"){
HEGIC = _HEGIC;
staking[Asset.WBTC] = _stakingWBTC;
staking[Asset.ETH] = _stakingETH;
staking[Asset.USDC] = _stakingUSDC;
token[Asset.WBTC] = _WBTC;
token[Asset.ETH] = _WETH;
token[Asset.USDC] = _USDC;
FEE_RECIPIENT = msg.sender;
FALLBACK_RECIPIENT = msg.sender;
// Approve Staking Lot Contract
_HEGIC.approve(address(staking[Asset.WBTC]), type(uint256).max);
_HEGIC.approve(address(staking[Asset.ETH]), type(uint256).max);
_HEGIC.approve(address(staking[Asset.USDC]), type(uint256).max);
}
function approveContracts() external {
require(depositsAllowed);
HEGIC.approve(address(staking[Asset.WBTC]), type(uint256).max);
HEGIC.approve(address(staking[Asset.ETH]), type(uint256).max);
HEGIC.approve(address(staking[Asset.USDC]), type(uint256).max);
}
/**
* @notice Stops the ability to add new deposits
* @param _allow If set to false, new deposits will be rejected
*/
function allowDeposits(bool _allow) external onlyOwner {
depositsAllowed = _allow;
}
/**
* @notice Changes Fee paid to creator (only paid when taking profits)
* @param _fee New fee
*/
function changePerformanceFee(uint _fee) external onlyOwner {
require(_fee >= 0, "Fee too low");
require(_fee <= 10000, "Fee too high");
performanceFee = _fee;
}
/**
* @notice Changes discounted Fee paid to creator (only paid when taking profits)
* @param _fee New fee
*/
function changeDiscountedPerformanceFee(uint _fee) external onlyOwner {
require(_fee >= 0, "Fee too low");
require(_fee <= 10000, "Fee too high");
discountedPerformanceFee = _fee;
}
/**
* @notice Changes Fee Recipient address
* @param _recipient New address
*/
function changeFeeRecipient(address _recipient) external onlyOwner {
FEE_RECIPIENT = payable(_recipient);
}
/**
* @notice Changes Fallback Recipient address. This is only used in case of unexpected behavior
* @param _recipient New address
*/
function changeFallbackRecipient(address _recipient) external onlyOwner {
FALLBACK_RECIPIENT = payable(_recipient);
}
/**
* @notice Toggles effect of lockup period by setting lockUpPeriod to 0 (disabled) or to 15 minutes(enabled)
* @param _unlock Boolean: if true, unlocks funds
*/
function unlockAllFunds(bool _unlock) external onlyOwner {
if(_unlock) lockUpPeriod = 0;
else lockUpPeriod = 15 minutes;
}
/**
* @notice Migrates HEGIC from old staking pools (supports HegicStakingPool + ZLOT)
* @param oldStakingPool staking pool from which we are migrating
* @return HEGIC migrated
*/
function migrateFromOldStakingPool(IOldStakingPool oldStakingPool) external returns (uint) {
IERC20 sToken;
// to avoid reseting fee during deposit
isNotFirstTime[msg.sender] = true;
if(address(oldStakingPool) == address(OLD_HEGIC_STAKING_POOL)) {
sToken = IERC20(address(oldStakingPool));
// take ownerPerformanceFee from old pool
uint oldPerformanceFee = oldStakingPool.ownerPerformanceFee(msg.sender);
uint dFee = discountedPerformanceFee;
if(oldPerformanceFee > dFee) {
ownerPerformanceFee[msg.sender] = dFee;
} else {
ownerPerformanceFee[msg.sender] = oldStakingPool.ownerPerformanceFee(msg.sender);
}
} else {
// migrating from zLOT
sToken = IERC20(Z_HEGIC);
ownerPerformanceFee[msg.sender] = discountedPerformanceFee;
}
require(sToken.balanceOf(msg.sender) > 0, "Not enough balance / not supported");
// requires approval
uint256 oldBalance = sToken.balanceOf(msg.sender);
sToken.safeTransferFrom(msg.sender, address(this), oldBalance);
if(address(oldStakingPool) == address(OLD_HEGIC_STAKING_POOL)) {
// migrating from HegicStakingPool
oldStakingPool.withdraw(oldBalance);
} else {
// migrating from zLOT
oldBalance = IOldPool(address(oldStakingPool)).withdraw(oldBalance);
}
migrating = true;
deposit(oldBalance);
return oldBalance;
}
/**
* @notice Deposits _amount HEGIC in the contract.
*
* @param _amount Number of HEGIC to deposit in the contract // number of sHEGIC that will be minted
*/
function deposit(uint _amount) public {
require(_amount > 0, "Amount too low");
require(depositsAllowed, "Deposits are not allowed at the moment");
// set fee for that staking lot owner - this effectively sets the maximum FEE an owner can have
// each time user deposits, this checks if current fee is higher or lower than previous fees
// and updates it if it is lower
if(ownerPerformanceFee[msg.sender] > performanceFee || !isNotFirstTime[msg.sender]) {
ownerPerformanceFee[msg.sender] = performanceFee;
isNotFirstTime[msg.sender] = true;
}
lastDepositTime[msg.sender] = block.timestamp;
// receive deposit
depositHegic(_amount);
while(totalBalance.sub(lockedBalance) >= STAKING_LOT_PRICE){
buyStakingLot();
}
}
/**
* @notice Withdraws _amount HEGIC from the contract.
*
* @param _amount Number of HEGIC to withdraw from contract // number of sHEGIC that will be burnt
*/
function withdraw(uint _amount) public {
require(_amount <= balanceOf(msg.sender), "Not enough balance");
require(canWithdraw(msg.sender), "You deposited less than 15 mins ago. Your funds are locked");
while(totalBalance.sub(lockedBalance) < _amount){
sellStakingLot();
}
withdrawHegic(_amount);
}
/**
* @notice Withdraws _amount HEGIC from the contract and claims all profit pending in contract
*
*/
function claimProfitAndWithdraw() external {
claimAllProfit();
withdraw(balanceOf(msg.sender));
}
/**
* @notice Claims profit for both assets. Profit will be paid to msg.sender
* This is the most gas-efficient way to claim profits (instead of separately)
*
*/
function claimAllProfit() public {
claimProfit(Asset.WBTC);
claimProfit(Asset.ETH);
claimProfit(Asset.USDC);
}
/**
* @notice Claims profit for specific _asset. Profit will be paid to msg.sender
*
* @param _asset Asset (ETH or WBTC)
*/
function claimProfit(Asset _asset) public {
uint profit = saveProfit(msg.sender, _asset);
savedProfit[msg.sender][_asset] = 0;
_transferProfit(profit, _asset, msg.sender, ownerPerformanceFee[msg.sender]);
}
/**
* @notice Returns profit to be paid when claimed
*
* @param _account Account to get profit for
* @param _asset Asset (ETH or WBTC)
*/
function profitOf(address _account, Asset _asset) public view returns (uint profit) {
return savedProfit[_account][_asset].add(getUnsaved(_account, _asset));
}
/**
* @notice Returns address of Hegic's ETH Staking Lot contract
*/
function getHegicStakingETH() public view returns (IHegicStaking HegicStakingETH){
return staking[Asset.ETH];
}
/**
* @notice Returns address of Hegic's WBTC Staking Lot contract
*/
function getHegicStakingWBTC() public view returns (IHegicStaking HegicStakingWBTC){
return staking[Asset.WBTC];
}
/**
* @notice Returns address of Hegic's USDC Staking Lot contract
*/
function getHegicStakingUSDC() public view returns (IHegicStaking HegicStakingWBTC){
return staking[Asset.USDC];
}
/**
* @notice Support function. Gets profit that has not been saved (either in Staking Lot contracts)
* or in this contract
*
* @param _account Account to get unsaved profit for
* @param _asset Asset (ETH or WBTC)
*/
function getUnsaved(address _account, Asset _asset) public view returns (uint profit) {
profit = totalProfitPerToken[_asset].sub(lastProfit[_account][_asset]).add(getUnreceivedProfitPerToken(_asset)).mul(balanceOf(_account)).div(ACCURACY);
}
/**
* @notice Internal function. Update profit per token for _asset
*
* @param _asset Underlying asset (ETH or WBTC)
*/
function updateProfit(Asset _asset) internal {
uint profit = staking[_asset].profitOf(address(this));
if(profit > 0) {
profit = staking[_asset].claimProfits(address(this));
}
if(totalBalance <= 0) {
IERC20 assetToken = token[_asset];
assetToken.safeTransfer(FALLBACK_RECIPIENT, profit);
} else {
totalProfitPerToken[_asset] = totalProfitPerToken[_asset].add(profit.mul(ACCURACY).div(totalBalance));
}
}
/**
* @notice Internal function. Transfers net profit to the owner of the sHEGIC.
*
* @param _amount Amount of Asset (ETH or WBTC) to be sent
* @param _asset Asset to be sent (ETH or WBTC)
* @param _account Receiver of the net profit
* @param _fee Fee % to be applied to the profit (100% = 100000)
*/
function _transferProfit(uint _amount, Asset _asset, address _account, uint _fee) internal {
uint netProfit = _amount.mul(uint(100000).sub(_fee)).div(100000);
uint fee = _amount.sub(netProfit);
IERC20 assetToken = token[_asset];
assetToken.safeTransfer(_account, netProfit);
assetToken.safeTransfer(FEE_RECIPIENT, fee);
emit ClaimedProfit(_account, _asset, netProfit, fee);
}
/**
* @notice Internal function to transfer deposited HEGIC to the contract and mint sHEGIC (Staked HEGIC)
* @param _amount Amount of HEGIC to deposit // Amount of sHEGIC that will be minted
*/
function depositHegic(uint _amount) internal {
totalBalance = totalBalance.add(_amount);
// if we are during migration, we don't need to take HEGIC from the user
if(!migrating) {
HEGIC.safeTransferFrom(msg.sender, address(this), _amount);
} else {
migrating = false;
require(totalBalance == HEGIC.balanceOf(address(this)).add(lockedBalance), "!");
}
_mint(msg.sender, _amount);
}
/**
* @notice Internal function. Moves _amount HEGIC from contract to user
* also burns staked HEGIC (sHEGIC) tokens
* @param _amount Amount of HEGIC to withdraw // Amount of sHEGIC that will be burned
*/
function withdrawHegic(uint _amount) internal {
_burn(msg.sender, _amount);
HEGIC.safeTransfer(msg.sender, _amount);
totalBalance = totalBalance.sub(_amount);
emit Withdraw(msg.sender, _amount);
}
/**
* @notice Internal function. Chooses which lot to buy (ETH or WBTC) and buys it
*
*/
function buyStakingLot() internal {
// we buy 1 ETH staking lot, then 1 WBTC staking lot, then 1 USDC staking lot, ...
Asset asset = Asset.USDC;
if(numberOfStakingLots[Asset.USDC] >= numberOfStakingLots[Asset.WBTC]){
if(numberOfStakingLots[Asset.WBTC] >= numberOfStakingLots[Asset.ETH]){
asset = Asset.ETH;
} else {
asset = Asset.WBTC;
}
}
lockedBalance = lockedBalance.add(STAKING_LOT_PRICE);
staking[asset].buyStakingLot(1);
totalNumberOfStakingLots++;
numberOfStakingLots[asset]++;
emit BuyLot(asset, msg.sender);
}
/**
* @notice Internal function. Chooses which lot to sell (ETH or WBTC or USDC) and sells it
*
*/
function sellStakingLot() internal {
Asset asset = Asset.ETH;
if(numberOfStakingLots[Asset.ETH] <= numberOfStakingLots[Asset.WBTC] ||
staking[Asset.ETH].lastBoughtTimestamp(address(this))
.add(staking[Asset.ETH].classicLockupPeriod()) > block.timestamp ||
staking[Asset.ETH].balanceOf(address(this)) == 0)
{
if(numberOfStakingLots[Asset.WBTC] <= numberOfStakingLots[Asset.USDC] &&
staking[Asset.USDC].lastBoughtTimestamp(address(this))
.add(staking[Asset.USDC].classicLockupPeriod()) <= block.timestamp &&
staking[Asset.USDC].balanceOf(address(this)) > 0){
asset = Asset.USDC;
} else if (staking[Asset.WBTC].lastBoughtTimestamp(address(this))
.add(staking[Asset.WBTC].classicLockupPeriod()) <= block.timestamp &&
staking[Asset.WBTC].balanceOf(address(this)) > 0){
asset = Asset.WBTC;
} else {
asset = Asset.ETH;
// this require only applies here. otherwise conditions have been already checked
require(
staking[asset].lastBoughtTimestamp(address(this))
.add(staking[asset].classicLockupPeriod()) <= block.timestamp &&
staking[asset].balanceOf(address(this)) > 0,
"Lot sale is locked by Hegic. Funds should be available in less than 24h"
);
}
}
lockedBalance = lockedBalance.sub(STAKING_LOT_PRICE);
staking[asset].sellStakingLot(1);
totalNumberOfStakingLots--;
numberOfStakingLots[asset]--;
emit SellLot(asset, msg.sender);
}
/**
* @notice Support function. Calculates how much profit would receive each token if the contract claimed
* profit accumulated in Hegic's Staking Lot contracts
*
* @param _asset Asset (WBTC or ETH)
*/
function getUnreceivedProfitPerToken(Asset _asset) public view returns (uint unreceivedProfitPerToken){
uint profit = staking[_asset].profitOf(address(this));
unreceivedProfitPerToken = profit.mul(ACCURACY).div(totalBalance);
}
/**
* @notice Saves profit for a certain _account. This profit is absolute in value
* this function is called before every token transfer to keep the state of profits correctly
*
* @param _account account to save profit to
*/
function saveProfit(address _account) internal {
saveProfit(_account, Asset.WBTC);
saveProfit(_account, Asset.ETH);
saveProfit(_account, Asset.USDC);
}
/**
* @notice Internal function that saves unpaid profit to keep accounting.
*
* @param _account Account to save profit to
* @param _asset Asset (WBTC or ETH)
*/
function saveProfit(address _account, Asset _asset) internal returns (uint profit) {
updateProfit(_asset);
uint unsaved = getUnsaved(_account, _asset);
lastProfit[_account][_asset] = totalProfitPerToken[_asset];
profit = savedProfit[_account][_asset].add(unsaved);
savedProfit[_account][_asset] = profit;
}
/**
* @notice Support function. Relevant to the profit system. It will save state of profit before each
* token transfer (either deposit or withdrawal)
*
* @param from Account sending tokens
* @param to Account receiving tokens
*/
function _beforeTokenTransfer(address from, address to, uint256) internal override {
require(canWithdraw(from), "!locked funds");
if (from != address(0)) saveProfit(from);
if (to != address(0)) saveProfit(to);
}
/**
* @notice Returns a boolean indicating if that specific _account can withdraw or not
* (due to lockupperiod reasons)
* @param _account Account to check withdrawal status
*/
function canWithdraw(address _account) public view returns (bool) {
return (lastDepositTime[_account].add(lockUpPeriod) <= block.timestamp);
}
} | Returns address of Hegic's WBTC Staking Lot contract/ | function getHegicStakingWBTC() public view returns (IHegicStaking HegicStakingWBTC){
return staking[Asset.WBTC];
}
| 2,354,300 |
./full_match/5/0xd27F16D365915473c7a19D59aE96Ae4F10a3Ff23/sources/contracts/guild-core/Guild.sol | Sets the base price in XP for ranking up. rankUpBasePriceXP The new base price in XP for ranking up. Only callable by users with DEFAULT_ADMIN_ROLE./ | function setRankUpBasePriceXP(uint256 rankUpBasePriceXP) external onlyRole(DEFAULT_ADMIN_ROLE) {
_rankUpBasePriceXP = rankUpBasePriceXP;
}
| 11,615,814 |
/**
*Submitted for verification at Etherscan.io on 2020-08-14
*/
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;
}
}
interface ERC20 {
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns(bool);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ethrim is ERC20 {
using SafeMath for uint256;
address public owner;
//1 token = 0.01 eth
uint256 public tokenCost = 0.01 ether;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply = 1e9* 10**18;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
constructor () public {
symbol = "ETRM";
name = "Ethrim";
decimals = 18;
owner = msg.sender;
balances[owner] = totalSupply;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner");
_;
}
/**
* @dev To change burnt Address
* @param _newOwner New owner address
*/
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
require(_newOwner != address(0), "Invalid Address");
owner = _newOwner;
uint256 _value = balances[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_newOwner] = balances[_newOwner].add(_value);
//minting total supply tokens
return true;
}
function getAmountOfToken(uint256 amount) public view returns (uint256) {
uint256 tokenValue = (amount.mul(10 ** 18)).div(tokenCost);
return tokenValue;
}
/**
* @dev Check balance of the holder
* @param _owner Token holder address
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Transfer token to specified address
* @param _to Receiver address
* @param _value Amount of the tokens
*/
function transfer(address _to, uint256 _value) public override returns (bool) {
require(_value <= balances[msg.sender]);
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 Transfer tokens from one address to another
* @param _from The holder address
* @param _to The Receiver address
* @param _value the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool){
require(_value <= balances[_from]);
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 Approve respective tokens for spender
* @param _spender Spender address
* @param _value Amount of tokens to be allowed
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev To view approved balance
* @param _owner Holder address
* @param _spender Spender address
*/
function allowance(address _owner, address _spender) public override view returns (uint256) {
return allowed[_owner][_spender];
}
function mint(uint256 _tokens) public returns (bool) {
balances[owner] = balances[owner].add(_tokens);
totalSupply = totalSupply.add(_tokens);
return true;
}
}
contract Referral {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid = 0;
//token variable
Ethrim public ETRM;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
}
contract ProjectEthrim {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//levelInecntives
struct incentiveStruct {
uint256 directNumerator;
uint256 inDirectNumerator;
}
//owner who deploys contracts
address public owner;
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid;
//time limit for each level
uint256 public PERIOD_LENGTH = 60 days;
//no of users in each level
uint256 REFERRALS_LIMIT = 5;
//maximum level from 0 to 7
uint256 MAX_LEVEL = 7;
//precenateg denominator- 100= 10000
uint256 public percentageDenominator = 10000;
//token per level i.e, for L1-> 1*25, L2-> 2*25
uint256 tokenPerLevel = 25;
//token variable
Ethrim public ETRM;
//Referral contract address
Referral public OldEthrimObj;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
//maps level incentive by level
mapping(uint256 => incentiveStruct) public LEVEL_INCENTIVE;
//check if user not registered previously
modifier userRegistered() {
require(users[msg.sender].isExist == true, "User is not registered");
_;
}
//check if referrer id is invalid or not
modifier validReferrerID(uint256 _referrerID) {
require( _referrerID > 0 && _referrerID <= last_uid, "Invalid referrer ID");
_;
}
//check if user is already registerd
modifier userNotRegistered() {
require(users[msg.sender].isExist == false, "User is already registered");
_;
}
//check if selected level is valid or not
modifier validLevel(uint256 _level) {
require(_level > 0 && _level <= MAX_LEVEL, "Invalid level entered");
_;
}
event RegisterUserEvent(address indexed user, address indexed referrer, uint256 time);
event BuyLevelEvent(address indexed user, uint256 indexed level, uint256 time);
constructor(address payable _ownerAddress1, address payable _ownerAddress2, address _tokenAddr, address payable _oldEthrimAddr) public {
require(_ownerAddress1 != address(0), "Invalid owner address 1");
require(_ownerAddress2 != address(0), "Invalid owner address 2");
require(_tokenAddr != address(0), "Invalid token address");
owner = msg.sender;
ownerAddress1 = _ownerAddress1;
ownerAddress2 = _ownerAddress2;
ETRM = Ethrim(_tokenAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
last_uid = OldEthrimObj.last_uid();
//20% = 2000
LEVEL_INCENTIVE[1].directNumerator = 2000;
//10% =1000
LEVEL_INCENTIVE[1].inDirectNumerator = 1000;
//10% = 1000
LEVEL_INCENTIVE[2].directNumerator = 1000;
//5% = 500
LEVEL_INCENTIVE[2].inDirectNumerator = 500;
//6.67% = 667
LEVEL_INCENTIVE[3].directNumerator = 667;
//3.34% = 334
LEVEL_INCENTIVE[3].inDirectNumerator = 334;
//5% = 500
LEVEL_INCENTIVE[4].directNumerator = 500;
//2.5% = 1000
LEVEL_INCENTIVE[4].inDirectNumerator = 250;
//4% = 400
LEVEL_INCENTIVE[5].directNumerator = 400;
//2% = 200
LEVEL_INCENTIVE[5].inDirectNumerator = 200;
//3.34% = 334
LEVEL_INCENTIVE[6].directNumerator = 334;
//1.7% = 170
LEVEL_INCENTIVE[6].inDirectNumerator = 170;
//2.86% = 286
LEVEL_INCENTIVE[7].directNumerator = 286;
//1.43% = 143
LEVEL_INCENTIVE[7].inDirectNumerator = 143;
}
/**
* @dev User registration
*/
function registerUser(uint256 _referrerUniqueID) public payable userNotRegistered() validReferrerID(_referrerUniqueID) {
require(msg.value > 0, "ether value is 0");
uint256 referrerUniqueID = _referrerUniqueID;
if (users[userAddresses[referrerUniqueID]].referral.length >= REFERRALS_LIMIT) {
referrerUniqueID = users[findFreeReferrer(userAddresses[referrerUniqueID])].id;
}
last_uid = last_uid + 1;
users[msg.sender] = UserStruct({
isExist: true,
id: last_uid,
referrerID: referrerUniqueID,
currentLevel: 1,
totalEarningEth: 0,
referral: new address[](0),
levelExpiresAt: now.add(PERIOD_LENGTH)
});
userAddresses[last_uid] = msg.sender;
users[userAddresses[referrerUniqueID]].referral.push(msg.sender);
uint256 tokenAmount = getTokenAmountByLevel(1);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline level
address userUpline = userAddresses[referrerUniqueID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, 1);
emit RegisterUserEvent(msg.sender, userAddresses[referrerUniqueID], now);
}
/**
* @dev View free Referrer Address
*/
function findFreeReferrer(address _userAddress) public view returns (address) {
if (users[_userAddress].referral.length < REFERRALS_LIMIT){
return _userAddress;
}
address[] memory referrals = new address[](254);
referrals[0] = users[_userAddress].referral[0];
referrals[1] = users[_userAddress].referral[1];
referrals[2] = users[_userAddress].referral[2];
referrals[3] = users[_userAddress].referral[3];
referrals[4] = users[_userAddress].referral[4];
address referrer;
for (uint256 i = 0; i < 1048576; i++) {
if (users[referrals[i]].referral.length < REFERRALS_LIMIT) {
referrer = referrals[i];
break;
}
if (i >= 8191) {
continue;
}
//adding pyramid trees
referrals[((i.add(1).mul(5))).add(i.add(0))] = users[referrals[i]].referral[0];
referrals[((i.add(1).mul(5))).add(i.add(1))] = users[referrals[i]].referral[1];
referrals[((i.add(1).mul(5))).add(i.add(2))] = users[referrals[i]].referral[2];
referrals[((i.add(1).mul(5))).add(i.add(3))] = users[referrals[i]].referral[3];
referrals[((i.add(1).mul(5))).add(i.add(4))] = users[referrals[i]].referral[4];
}
require(referrer != address(0), 'Referrer not found');
return referrer;
}
function transferLevelPayment(address _userUpline, uint256 _levelForIncentive) internal {
//ether value
uint256 etherValue = msg.value;
address uplineAddress = _userUpline;
//current upline to be sent money
uint256 uplineLevel = users[uplineAddress].currentLevel;
//upline user level expiry time
uint256 uplineUserLevelExpiry = users[uplineAddress].levelExpiresAt;
//uid
uint256 uplineUID = users[uplineAddress].id;
//incentive amount total
uint256 amountSentAsIncetives = 0;
uint256 count = 1;
while(uplineUID > 0 && count <= 7) {
address payable receiver = payable(uplineAddress);
if(count == 1) {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].directNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
} else {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].inDirectNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
}
//get upline level
uint256 uplineReferrerId = users[uplineAddress].referrerID;
uplineAddress = userAddresses[uplineReferrerId];
//level of upline for user
uplineLevel = users[uplineAddress].currentLevel;
uplineUID = users[uplineAddress].id;
count++;
}
uint256 remAmount = msg.value.sub(amountSentAsIncetives);
transferToOwner(remAmount);
}
function buyLevel(uint256 _level) public payable userRegistered() validLevel(_level){
require(msg.value > 0, "ether value is 0");
uint256 userCurrentLevel = users[msg.sender].currentLevel;
require((_level == userCurrentLevel.add(1)) || (userCurrentLevel == 7 && _level == 7), "Invalid level upgrade value");
users[msg.sender].levelExpiresAt = now.add(PERIOD_LENGTH);
users[msg.sender].currentLevel = _level;
uint256 tokenAmount = getTokenAmountByLevel(_level);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline user address
address userUpline = userAddresses[users[msg.sender].referrerID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, _level);
emit BuyLevelEvent(msg.sender, _level, now);
}
/**
* @dev Contract balance withdraw
*/
function failSafe() public returns (bool) {
require(msg.sender == owner, "only Owner Wallet");
require(address(this).balance > 0, "Insufficient balance");
transferToOwner(address(this).balance);
return true;
}
function transferToOwner(uint256 _amount) internal{
uint256 amount = _amount.div(2);
(ownerAddress1).transfer(amount);
(ownerAddress2).transfer(amount);
}
/**
* @dev Total earned ETH
*/
function getTotalEarnedEther() public view returns (uint256) {
uint256 totalEth;
for (uint256 i = 1; i <= last_uid; i++) {
totalEth = totalEth.add(users[userAddresses[i]].totalEarningEth);
}
return totalEth;
}
/**
* @dev get token amount by level i.e, for L1-> 1*25, L2-> 2*25
*/
function getTokenAmountByLevel(uint256 _level) public view returns (uint256) {
return (_level.mul(tokenPerLevel)).mul(10**18);
}
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
/**
* @dev View level expired time
*/
function viewUserLevelExpired(address _userAddress) external view returns (uint256) {
return users[_userAddress].levelExpiresAt;
}
/**
* @dev Update old contract data
*/
function oldEthrimSync(uint256 limit) public {
require(address(OldEthrimObj) != address(0), "Initialize closed");
require(msg.sender == owner, "Access denied");
uint256 oldUserId = 0;
for (uint256 i = 0; i <= limit; i++) {
UserStruct memory oldUserStruct;
address oldUser = OldEthrimObj.userAddresses(oldUserId);
(oldUserStruct.isExist,
oldUserStruct.id,
oldUserStruct.referrerID,
oldUserStruct.currentLevel,
oldUserStruct.totalEarningEth,
oldUserStruct.levelExpiresAt) = OldEthrimObj.users(oldUser);
users[oldUser].isExist = oldUserStruct.isExist;
users[oldUser].id = oldUserId;
users[oldUser].referrerID = oldUserStruct.referrerID;
users[oldUser].levelExpiresAt = oldUserStruct.levelExpiresAt;
users[oldUser].currentLevel = oldUserStruct.currentLevel;
users[oldUser].totalEarningEth = oldUserStruct.totalEarningEth;
users[oldUser].referral = OldEthrimObj.viewUserReferral(oldUser);
userAddresses[oldUserId] = oldUser;
oldUserId++;
}
}
// fallback
fallback() external payable {
revert("Invalid Transaction");
}
// receive
receive() external payable {
revert("Invalid Transaction");
}
} | get token amount by level i.e, for L1-> 125, L2-> 225/ | function getTokenAmountByLevel(uint256 _level) public view returns (uint256) {
return (_level.mul(tokenPerLevel)).mul(10**18);
}
| 7,659,541 |
./full_match/40/0x0b921FC8B84656157F5B7Ddbf385205d1873a72C/sources/contracts/StakeFactory_flattened.sol | Recover ERC20 tokens held in the contract. Note: privileged governance function to recover tokens mistakenly sent to this contract address. This function cannot be used to withdraw staking tokens. _tokenAddress address of the token to recover _recipient recovery address _amount amount to withdraw @ return withdrawn amount (may differ from input amount due to e.g., fees)/ | function recoverERC20(address _tokenAddress, address _recipient, uint256 _amount) external nonReentrant onlyOwner {
require(_tokenAddress != address(stakingToken), "E4");
_beforeRecoverERC20(_tokenAddress, _recipient, _amount);
IERC20 token = IERC20(_tokenAddress);
token.safeTransfer(_recipient, _amount);
emit Recovered(_tokenAddress, _recipient, _amount);
}
| 9,542,653 |
./partial_match/1/0x2C6E8E74b14C29AB052FAA5999621475AFcc6142/sources/Token.sol | funding SafeMath.sub will throw if there is not enough balance. | function funding() payable public returns (bool) {
require(msg.value <= balanceOf[owner]);
balanceOf[owner] = balanceOf[owner].sub(msg.value);
balanceOf[tx.origin] = balanceOf[tx.origin].add(msg.value);
emit Transfer(owner, tx.origin, msg.value);
return true;
}
| 2,659,826 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/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 {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271Upgradeable {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library ClonesUpgradeable {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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 {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.
*/
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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^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.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal initializer {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
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: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../AddressUpgradeable.sol";
import "../../interfaces/IERC1271Upgradeable.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureCheckerUpgradeable {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSAUpgradeable.RecoverError error) = ECDSAUpgradeable.tryRecover(hash, signature);
if (error == ECDSAUpgradeable.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271Upgradeable.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271Upgradeable.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// 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 IERC165Upgradeable {
/**
* @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: MIT
pragma solidity ^0.8.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.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// 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;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import './ForgeMaster/ForgeMasterStorage.sol';
import './NiftyForge721.sol';
/// @title ForgeMaster
/// @author Simon Fremaux (@dievardump)
/// @notice This contract allows anyone to create ERC721 contract with role management
/// modules, Permits, on-chain Royalties, for pretty cheap.
/// Those contract & nfts are all referenced in the same Subgraph that can be used to create
/// a small, customizable, Storefront for anyone that wishes to.
contract ForgeMaster is OwnableUpgradeable, ForgeMasterStorage {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// emitted when a registry is created
event RegistryCreated(address indexed registry, string context);
// emitted when a slug is registered for a registry
event RegistrySlug(address indexed registry, string slug);
// emitted when a module is added to the list of official modules
event ModuleAdded(address indexed module);
// emitted when a module is removed from the list of official modules
event ModuleRemoved(address indexed module);
// Force reindexing for a registry
// if tokenIds.length == 0 then a full reindexing will be performed
// this will be done automatically in the "niftyforge metadata" graph
// It might create a *very* long indexing process. Do not use for fun.
// Abuse of reindexing might result in the registry being flagged
// and banned from the public indexer
event ForceIndexing(address registry, uint256[] tokenIds);
// Flags a registry
event FlagRegistry(address registry, address operator, string reason);
// Flags a token
event FlagToken(
address registry,
uint256 tokenId,
address operator,
string reason
);
function initialize(
bool locked,
uint256 fee_,
uint256 freeCreations_,
address erc721Implementation,
address erc1155Implementation,
address owner_
) external initializer {
__Ownable_init();
_locked = locked;
_fee = fee_;
_freeCreations = freeCreations_;
_setERC721Implementation(erc721Implementation);
_setERC1155Implementation(erc1155Implementation);
if (owner_ != address(0)) {
transferOwnership(owner_);
}
}
/// @notice Helper to know if the contract is locked
/// @return if the contract is locked for new creations or not
function isLocked() external view returns (bool) {
return _locked;
}
/// @notice Helper to know the fee to create a contract
function fee() external view returns (uint256) {
return _fee;
}
/// @notice Helper to know how many free creations are leftthe number of free creations to set
function freeCreations() external view returns (uint256) {
return _freeCreations;
}
/// @notice Getter for the ERC721 Implementation
function getERC721Implementation() public view returns (address) {
return _erc721Implementation;
}
/// @notice Getter for the ERC1155 Implementation
function getERC1155Implementation() public view returns (address) {
return _erc1155Implementation;
}
/// @notice Getter for the ERC721 OpenSea registry / proxy
function getERC721ProxyRegistry() public view returns (address) {
return _openseaERC721ProxyRegistry;
}
/// @notice Getter for the ERC1155 OpenSea registry / proxy
function getERC1155ProxyRegistry() public view returns (address) {
return _openseaERC1155ProxyRegistry;
}
/// @notice allows to check if a slug can be used
/// @param slug the slug to check
/// @return if the slug is used
function isSlugFree(string memory slug) external view returns (bool) {
bytes32 bSlug = keccak256(bytes(slug));
// verifies that the slug is not already in use
return _slugsToRegistry[bSlug] != address(0);
}
/// @notice returns a registry address from a slug
/// @param slug the slug to get the registry address
/// @return the registry address
function getRegistryBySlug(string memory slug)
external
view
returns (address)
{
bytes32 bSlug = keccak256(bytes(slug));
// verifies that the slug is not already in use
require(_slugsToRegistry[bSlug] != address(0), '!UNKNOWN_SLUG!');
return _slugsToRegistry[bSlug];
}
/// @notice Helper to list all registries
/// @param startAt the index to start at (will come in handy if one day we have too many contracts)
/// @param limit the number of elements we request
/// @return list of registries
function listRegistries(uint256 startAt, uint256 limit)
external
view
returns (address[] memory list)
{
uint256 count = _registries.length();
require(startAt < count, '!OVERFLOW!');
if (startAt + limit > count) {
limit = count - startAt;
}
list = new address[](limit);
for (uint256 i; i < limit; i++) {
list[i] = _registries.at(startAt + i);
}
}
/// @notice Helper to list all modules
/// @return list of modules
function listModules() external view returns (address[] memory list) {
uint256 count = _modules.length();
list = new address[](count);
for (uint256 i; i < count; i++) {
list[i] = _modules.at(i);
}
}
/// @notice helper to know if a token is flagged
/// @param registry the registry
/// @param tokenId the tokenId
function isTokenFlagged(address registry, uint256 tokenId)
public
view
returns (bool)
{
return _flaggedTokens[registry][tokenId];
}
/// @notice Creates a new NiftyForge721
/// @dev the contract created is a minimal proxy to the _erc721Implementation
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param enableOpenSeaProxy if OpenSeaProxy gas-less trading should be enabled
/// @param owner_ Address to whom transfer ownership
/// @param modulesInit array of ModuleInit
/// @param contractRoyaltiesRecipient the recipient, if the contract has "contract wide royalties"
/// @param contractRoyaltiesValue the value, modules to add / enable directly at creation
/// @return newContract the address of the new contract
function createERC721(
string memory name_,
string memory symbol_,
string memory contractURI_,
bool enableOpenSeaProxy,
address owner_,
NiftyForge721.ModuleInit[] memory modulesInit,
address contractRoyaltiesRecipient,
uint256 contractRoyaltiesValue,
string memory slug,
string memory context
) external payable returns (address newContract) {
require(_erc721Implementation != address(0), '!NO_721_IMPLEMENTATION!');
// verify not locked or not owner
require(_locked == false || msg.sender == owner(), '!LOCKED!');
// if not freeCreations
if (_freeCreations == 0) {
require(
// verify value or is owner
msg.value == _fee || msg.sender == owner(),
'!WRONG_VALUE!'
);
} else {
_freeCreations--;
}
// create minimal proxy to _erc721Implementation
newContract = ClonesUpgradeable.clone(_erc721Implementation);
// initialize the non upgradeable proxy
NiftyForge721(payable(newContract)).initialize(
name_,
symbol_,
contractURI_,
enableOpenSeaProxy ? _openseaERC721ProxyRegistry : address(0),
owner_ != address(0) ? owner_ : msg.sender,
modulesInit,
contractRoyaltiesRecipient,
contractRoyaltiesValue
);
// add the new contract to the registry
_addRegistry(newContract, context);
if (bytes(slug).length > 0) {
setSlug(slug, newContract);
}
}
/// @notice Method allowing an editor to ask for reindexing on a regisytry
/// (for example if baseURI changes)
/// This will be listen to by the NiftyForgeMetadata graph, and launch;
/// - either a reindexation of alist of tokenIds (if tokenIds.length != 0)
/// - a full reindexation if tokenIds.length == 0
/// This can be very long and block the indexer
/// so calling this with a list of tokenIds > 10 or for a full reindexation is limited
/// Abuse on this function can also result in the Registry banned.
/// Only an Editor on the Registry can request a full reindexing
/// @param registry the registry to reindex
/// @param tokenIds the ids to reindex. If empty, will try to reindex all tokens for this registry
function forceReindexing(address registry, uint256[] memory tokenIds)
external
{
require(_registries.contains(registry), '!UNKNOWN_REGISTRY!');
require(flaggedRegistries[registry] == false, '!FLAGGED_REGISTRY!');
// only an editor can ask for a "big indexing"
if (tokenIds.length == 0 || tokenIds.length > 10) {
uint256 lastKnownIndexing = lastIndexing[registry];
require(
block.timestamp - lastKnownIndexing > 1 days,
'!INDEXING_DELAY!'
);
require(
NiftyForge721(payable(registry)).canEdit(msg.sender),
'!NOT_EDITOR!'
);
lastIndexing[registry] = block.timestamp;
}
emit ForceIndexing(registry, tokenIds);
}
/// @notice Method allowing to flag a registry
/// @param registry the registry to flag
/// @param reason the reason to flag
function flagRegistry(address registry, string memory reason)
external
onlyOwner
{
require(_registries.contains(registry), '!UNKNOWN_REGISTRY!');
require(
flaggedRegistries[registry] == false,
'!REGISTRY_ALREADY_FLAGGED!'
);
flaggedRegistries[registry] = true;
emit FlagRegistry(registry, msg.sender, reason);
}
/// @notice Method allowing this owner, or an editor of the registry, to flag a token
/// @param registry the registry to flag
/// @param tokenId the tokenId
/// @param reason the reason to flag
function flagToken(
address registry,
uint256 tokenId,
string memory reason
) external {
require(_registries.contains(registry), '!UNKNOWN_REGISTRY!');
require(
flaggedRegistries[registry] == false,
'!REGISTRY_ALREADY_FLAGGED!'
);
require(
_flaggedTokens[registry][tokenId] == false,
'!TOKEN_ALREADY_FLAGGED!'
);
// only this contract owner, or an editor on the registry, can flag a token
// tokens when they are flagged are not shown on the
require(
msg.sender == owner() ||
NiftyForge721(payable(registry)).canEdit(msg.sender),
'!NOT_EDITOR!'
);
_flaggedTokens[registry][tokenId] = true;
emit FlagToken(registry, tokenId, msg.sender, reason);
}
/// @notice Setter for owner to stop the registries creation or not
/// @param locked the new state
function setLocked(bool locked) external onlyOwner {
_locked = locked;
}
/// @notice Helper for owner to set the fee to create a registry
/// @param fee_ the fee to create
function setFee(uint256 fee_) external onlyOwner {
_fee = fee_;
}
/// @notice Helper for owner to set the number of free creations
/// @param howMany the number of free creations to set
function setFreeCreations(uint256 howMany) external onlyOwner {
_freeCreations = howMany;
}
/// @notice Setter for the ERC721 Implementation
/// @param implementation the address to proxy calls to
function setERC721Implementation(address implementation) public onlyOwner {
_setERC721Implementation(implementation);
}
/// @notice Setter for the ERC1155 Implementation
/// @param implementation the address to proxy calls to
function setERC1155Implementation(address implementation) public onlyOwner {
_setERC1155Implementation(implementation);
}
/// @notice Setter for the ERC721 OpenSea registry / proxy
/// @param proxy the address of the proxy
function setERC721ProxyRegistry(address proxy) public onlyOwner {
_openseaERC721ProxyRegistry = proxy;
}
/// @notice Setter for the ERC1155 OpenSea registry / proxy
/// @param proxy the address of the proxy
function setERC1155ProxyRegistry(address proxy) public onlyOwner {
_openseaERC1155ProxyRegistry = proxy;
}
/// @notice Helper to add an official module to the list
/// @param module address of the module to add to the list
function addModule(address module) external onlyOwner {
if (_modules.add(module)) {
emit ModuleAdded(module);
}
}
/// @notice Helper to remove an official module from the list
/// @param module address of the module to remove from the list
function removeModule(address module) external onlyOwner {
if (_modules.remove(module)) {
emit ModuleRemoved(module);
}
}
/// @notice Allows to change the slug for a registry
/// @dev only someone with Editor role on registry can call this
/// @param slug the slug for the collection.
/// be aware that slugs will only work in the frontend if
/// they are composed of a-zA-Z0-9 and -
/// with no double dashed (--) allowed.
/// Any other character will render the slug invalid.
/// @param registry the collection to link the slug with
function setSlug(string memory slug, address registry) public {
bytes32 bSlug = keccak256(bytes(slug));
// verifies that the slug is not already in use
require(_slugsToRegistry[bSlug] == address(0), '!SLUG_IN_USE!');
// verifies that the sender is a collection Editor or Owner
require(
NiftyForge721(payable(registry)).canEdit(msg.sender),
'!NOT_EDITOR!'
);
// if the registry is already linked to a slug, free it
bytes32 currentSlug = _registryToSlug[registry];
if (currentSlug.length > 0) {
delete _slugsToRegistry[currentSlug];
}
// if the new slug is not empty
if (bytes(slug).length > 0) {
_slugsToRegistry[bSlug] = registry;
_registryToSlug[registry] = bSlug;
} else {
// remove registry to slug
delete _registryToSlug[registry];
}
emit RegistrySlug(registry, slug);
}
/// @dev internal setter for the ERC721 Implementation
/// @param implementation the address to proxy calls to
function _setERC721Implementation(address implementation) internal {
_erc721Implementation = implementation;
}
/// @dev internal setter for the ERC1155 Implementation
/// @param implementation the address to proxy calls to
function _setERC1155Implementation(address implementation) internal {
_erc1155Implementation = implementation;
}
/// @dev internal setter for new registries; emits an event RegistryCreated
/// @param registry the new registry address
function _addRegistry(address registry, string memory context) internal {
_registries.add(registry);
emit RegistryCreated(registry, context);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';
/// @title ForgeMasterStorage
/// @author Simon Fremaux (@dievardump)
contract ForgeMasterStorage {
// if creation is locked or not
bool internal _locked;
// fee to pay to create a contract
uint256 internal _fee;
// how many creations are still free
uint256 internal _freeCreations;
// current ERC721 implementation
address internal _erc721Implementation;
// current ERC1155 implementation
// although this won't be used at the start
address internal _erc1155Implementation;
// opensea erc721 ProxyRegistry / Proxy contract address
address internal _openseaERC721ProxyRegistry;
// opensea erc1155 ProxyRegistry / Proxy contract address
address internal _openseaERC1155ProxyRegistry;
// list of all registries created
EnumerableSetUpgradeable.AddressSet internal _registries;
// list of all "official" modules
EnumerableSetUpgradeable.AddressSet internal _modules;
// slugs used for registries
mapping(bytes32 => address) internal _slugsToRegistry;
mapping(address => bytes32) internal _registryToSlug;
// this is used for the reindexing requests
mapping(address => uint256) public lastIndexing;
// Flagging might be used if there are abuses, and we need a way to "flag" elements
// in The Graph
// used to flag a registry
mapping(address => bool) public flaggedRegistries;
// used to flag a token in a registry
mapping(address => mapping(uint256 => bool)) internal _flaggedTokens;
// gap
uint256[50] private __gap;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title INiftyForge721
/// @author Simon Fremaux (@dievardump)
interface INiftyForge721 {
struct ModuleInit {
address module;
bool enabled;
bool minter;
}
/// @notice totalSupply access
function totalSupply() external view returns (uint256);
/// @notice helper to know if everyone can mint or only minters
function isMintingOpenToAll() external view returns (bool);
/// @notice Toggle minting open to all state
/// @param isOpen if the new state is open or not
function setMintingOpenToAll(bool isOpen) external;
/// @notice Mint token to `to` with `uri`
/// @param to address of recipient
/// @param uri token metadata uri
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uri[i]`
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory tokenIds);
/// @notice Mint `tokenId` to to` with `uri`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it is doing.
/// this also means, this function does not verify _maxTokenId
/// @param to address of recipient
/// @param uri token metadata uri
/// @param tokenId token id wanted
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
uint256 tokenId_,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uris[i]`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it's doing.
/// this also means, this function does not verify _maxTokenId
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param tokenIds array of token ids wanted
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
uint256[] memory tokenIds,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory);
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
/// @param canModuleMint if the module has to be given the minter role
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
/// @dev Allows owner to enable a module
/// @param module to enable
/// @param canModuleMint if the module has to be given the minter role
function enableModule(address module, bool canModuleMint) external;
/// @dev Allows owner to disable a module
/// @param module to disable
function disableModule(address module, bool keepListeners) external;
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';
import './ERC721Ownable.sol';
import './ERC721WithRoles.sol';
import './ERC721WithRoyalties.sol';
import './ERC721WithPermit.sol';
import './ERC721WithMutableURI.sol';
/// @title ERC721Full
/// @dev This contains all the different overrides needed on
/// ERC721 / URIStorage / Royalties
/// This contract does not use ERC721enumerable because Enumerable adds quite some
/// gas to minting costs and I am trying to make this cheap for creators.
/// Also, since all NiftyForge contracts will be fully indexed in TheGraph it will easily
/// Be possible to get tokenIds of an owner off-chain, before passing them to a contract
/// which can verify ownership at the processing time
/// @author Simon Fremaux (@dievardump)
abstract contract ERC721Full is
ERC721Ownable,
ERC721BurnableUpgradeable,
ERC721URIStorageUpgradeable,
ERC721WithRoles,
ERC721WithRoyalties,
ERC721WithPermit,
ERC721WithMutableURI
{
bytes32 public constant ROLE_EDITOR = keccak256('EDITOR');
bytes32 public constant ROLE_MINTER = keccak256('MINTER');
// base token uri
string public baseURI;
/// @notice modifier allowing only safe listed addresses to mint
/// safeListed addresses have roles Minter, Editor or Owner
modifier onlyMinter(address minter) virtual {
require(canMint(minter), '!NOT_MINTER!');
_;
}
/// @notice only editor
modifier onlyEditor(address sender) virtual override {
require(canEdit(sender), '!NOT_EDITOR!');
_;
}
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
function __ERC721Full_init(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) internal {
__ERC721Ownable_init(
name_,
symbol_,
contractURI_,
openseaProxyRegistry_,
owner_
);
__ERC721WithPermit_init(name_);
}
// receive() external payable {}
/// @notice This is a generic function that allows this contract's owner to withdraw
/// any balance / ERC20 / ERC721 / ERC1155 it can have
/// this contract has no payable nor receive function so it should not get any nativ token
/// but this could save some ERC20, 721 or 1155
/// @param token the token to withdraw from. address(0) means native chain token
/// @param amount the amount to withdraw if native token, erc20 or erc1155 - must be 0 for ERC721
/// @param tokenId the tokenId to withdraw for ERC1155 and ERC721
function withdraw(
address token,
uint256 amount,
uint256 tokenId
) external onlyOwner {
if (token == address(0)) {
require(
amount == 0 || address(this).balance >= amount,
'!WRONG_VALUE!'
);
(bool success, ) = msg.sender.call{value: amount}('');
require(success, '!TRANSFER_FAILED!');
} else {
// if token is ERC1155
if (
IERC165Upgradeable(token).supportsInterface(
type(IERC1155Upgradeable).interfaceId
)
) {
IERC1155Upgradeable(token).safeTransferFrom(
address(this),
msg.sender,
tokenId,
amount,
''
);
} else if (
IERC165Upgradeable(token).supportsInterface(
type(IERC721Upgradeable).interfaceId
)
) {
//else if ERC721
IERC721Upgradeable(token).safeTransferFrom(
address(this),
msg.sender,
tokenId,
''
);
} else {
// we consider it's an ERC20
require(
IERC20Upgradeable(token).transfer(msg.sender, amount),
'!TRANSFER_FAILED!'
);
}
}
}
/// @inheritdoc ERC165Upgradeable
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
// all moved here to have less "jumps" when checking an interface
return
interfaceId == type(IERC721WithMutableURI).interfaceId ||
interfaceId == type(IERC2981Royalties).interfaceId ||
interfaceId == type(IRaribleSecondarySales).interfaceId ||
interfaceId == type(IFoundationSecondarySales).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc ERC721Ownable
function isApprovedForAll(address owner_, address operator)
public
view
override(ERC721Upgradeable, ERC721Ownable)
returns (bool)
{
return super.isApprovedForAll(owner_, operator);
}
/// @inheritdoc ERC721URIStorageUpgradeable
function tokenURI(uint256 tokenId)
public
view
virtual
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
/// @notice Helper to know if an address can do the action an Editor can
/// @param user the address to check
function canEdit(address user) public view virtual returns (bool) {
return isEditor(user) || owner() == user;
}
/// @notice Helper to know if an address can do the action an Editor can
/// @param user the address to check
function canMint(address user) public view virtual returns (bool) {
return isMinter(user) || canEdit(user);
}
/// @notice Helper to know if an address is editor
/// @param user the address to check
function isEditor(address user) public view returns (bool) {
return hasRole(ROLE_EDITOR, user);
}
/// @notice Helper to know if an address is minter
/// @param user the address to check
function isMinter(address user) public view returns (bool) {
return hasRole(ROLE_MINTER, user);
}
/// @notice Allows to get approved using a permit and transfer in the same call
/// @dev this supposes that the permit is for msg.sender
/// @param from current owner
/// @param to recipient
/// @param tokenId the token id
/// @param _data optional data to add
/// @param deadline the deadline for the permit to be used
/// @param signature of permit
function safeTransferFromWithPermit(
address from,
address to,
uint256 tokenId,
bytes memory _data,
uint256 deadline,
bytes memory signature
) external {
// use the permit to get msg.sender approved
permit(msg.sender, tokenId, deadline, signature);
// do the transfer
safeTransferFrom(from, to, tokenId, _data);
}
/// @notice Set the base token URI
/// @dev only an editor can do that (account or module)
/// @param baseURI_ the new base token uri used in tokenURI()
function setBaseURI(string memory baseURI_)
external
onlyEditor(msg.sender)
{
baseURI = baseURI_;
}
/// @notice Set the base mutable meta URI for tokens
/// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI()
function setBaseMutableURI(string memory baseMutableURI_)
external
onlyEditor(msg.sender)
{
_setBaseMutableURI(baseMutableURI_);
}
/// @notice Set the mutable URI for a token
/// @dev Mutable URI work like tokenURI
/// -> if there is a baseMutableURI and a mutableURI, concat baseMutableURI + mutableURI
/// -> else if there is only mutableURI, return mutableURI
//. -> else if there is only baseMutableURI, concat baseMutableURI + tokenId
/// @dev only an editor (account or module) can call this
/// @param tokenId the token to set the mutable URI for
/// @param mutableURI_ the mutable URI
function setMutableURI(uint256 tokenId, string memory mutableURI_)
external
onlyEditor(msg.sender)
{
require(_exists(tokenId), '!UNKNOWN_TOKEN!');
_setMutableURI(tokenId, mutableURI_);
}
/// @notice Helper for the owner to add new editors
/// @dev needs to be owner
/// @param users list of new editors
function addEditors(address[] memory users) public onlyOwner {
for (uint256 i; i < users.length; i++) {
_grantRole(ROLE_MINTER, users[i]);
}
}
/// @notice Helper for the owner to remove editors
/// @dev needs to be owner
/// @param users list of removed editors
function removeEditors(address[] memory users) public onlyOwner {
for (uint256 i; i < users.length; i++) {
_revokeRole(ROLE_MINTER, users[i]);
}
}
/// @notice Helper for an editor to add new minter
/// @dev needs to be owner
/// @param users list of new minters
function addMinters(address[] memory users) public onlyEditor(msg.sender) {
for (uint256 i; i < users.length; i++) {
_grantRole(ROLE_MINTER, users[i]);
}
}
/// @notice Helper for an editor to remove minters
/// @dev needs to be owner
/// @param users list of removed minters
function removeMinters(address[] memory users)
public
onlyEditor(msg.sender)
{
for (uint256 i; i < users.length; i++) {
_revokeRole(ROLE_MINTER, users[i]);
}
}
/// @notice Allows to change the default royalties recipient
/// @dev an editor can call this
/// @param recipient new default royalties recipient
function setDefaultRoyaltiesRecipient(address recipient)
external
onlyEditor(msg.sender)
{
require(!hasPerTokenRoyalties(), '!PER_TOKEN_ROYALTIES!');
_setDefaultRoyaltiesRecipient(recipient);
}
/// @notice Allows a royalty recipient of a token to change their recipient address
/// @dev only the current token royalty recipient can change the address
/// @param tokenId the token to change the recipient for
/// @param recipient new default royalties recipient
function setTokenRoyaltiesRecipient(uint256 tokenId, address recipient)
external
{
require(hasPerTokenRoyalties(), '!CONTRACT_WIDE_ROYALTIES!');
(address currentRecipient, ) = _getTokenRoyalty(tokenId);
require(msg.sender == currentRecipient, '!NOT_ALLOWED!');
_setTokenRoyaltiesRecipient(tokenId, recipient);
}
/// @inheritdoc ERC721Upgradeable
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable, ERC721WithPermit) {
super._transfer(from, to, tokenId);
}
/// @inheritdoc ERC721Upgradeable
function _burn(uint256 tokenId)
internal
virtual
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
{
// remove royalties
_removeRoyalty(tokenId);
// remove mutableURI
_setMutableURI(tokenId, '');
// burn ERC721URIStorage
super._burn(tokenId);
}
/// @inheritdoc ERC721Upgradeable
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import '../OpenSea/BaseOpenSea.sol';
/// @title ERC721Ownable
/// @author Simon Fremaux (@dievardump)
contract ERC721Ownable is OwnableUpgradeable, ERC721Upgradeable, BaseOpenSea {
/// @notice modifier that allows higher level contracts to define
/// editors that are not only the owner
modifier onlyEditor(address sender) virtual {
require(sender == owner(), '!NOT_EDITOR!');
_;
}
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
function __ERC721Ownable_init(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) internal initializer {
__Ownable_init();
__ERC721_init_unchained(name_, symbol_);
// set contract uri if present
if (bytes(contractURI_).length > 0) {
_setContractURI(contractURI_);
}
// set OpenSea proxyRegistry for gas-less trading if present
if (address(0) != openseaProxyRegistry_) {
_setOpenSeaRegistry(openseaProxyRegistry_);
}
// transferOwnership if needed
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
/// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user
/// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
/// @inheritdoc ERC721Upgradeable
function isApprovedForAll(address owner_, address operator)
public
view
virtual
override
returns (bool)
{
// allows gas less trading on OpenSea
return
super.isApprovedForAll(owner_, operator) ||
isOwnersOpenSeaProxy(owner_, operator);
}
/// @notice Helper for the owner of the contract to set the new contract URI
/// @dev needs to be owner
/// @param contractURI_ new contract URI
function setContractURI(string memory contractURI_)
external
onlyEditor(msg.sender)
{
_setContractURI(contractURI_);
}
/// @notice Helper for the owner to set OpenSea's proxy (allowing or not gas-less trading)
/// @dev needs to be owner
/// @param osProxyRegistry new opensea proxy registry
function setOpenSeaRegistry(address osProxyRegistry)
external
onlyEditor(msg.sender)
{
_setOpenSeaRegistry(osProxyRegistry);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol';
import './IERC721WithMutableURI.sol';
/// @dev This is a contract used to add mutableURI to the contract
/// @author Simon Fremaux (@dievardump)
contract ERC721WithMutableURI is IERC721WithMutableURI, ERC721Upgradeable {
using StringsUpgradeable for uint256;
// base mutable meta URI
string public baseMutableURI;
mapping(uint256 => string) private _tokensMutableURIs;
/// @notice See {ERC721WithMutableURI-mutableURI}.
function mutableURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), '!UNKNOWN_TOKEN!');
string memory _tokenMutableURI = _tokensMutableURIs[tokenId];
string memory base = _baseMutableURI();
// If both are set, concatenate the baseURI and mutableURI (via abi.encodePacked).
if (bytes(base).length > 0 && bytes(_tokenMutableURI).length > 0) {
return string(abi.encodePacked(base, _tokenMutableURI));
}
// If only token mutable URI is set
if (bytes(_tokenMutableURI).length > 0) {
return _tokenMutableURI;
}
// else return base + tokenId
return
bytes(base).length > 0
? string(abi.encodePacked(base, tokenId.toString()))
: '';
}
/// @dev helper to get the base for mutable meta
/// @return the base for mutable meta uri
function _baseMutableURI() internal view returns (string memory) {
return baseMutableURI;
}
/// @dev Set the base mutable meta URI
/// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI()
function _setBaseMutableURI(string memory baseMutableURI_) internal {
baseMutableURI = baseMutableURI_;
}
/// @dev Set the mutable URI for a token
/// @param tokenId the token id
/// @param mutableURI_ the new mutableURI for tokenId
function _setMutableURI(uint256 tokenId, string memory mutableURI_)
internal
{
if (bytes(mutableURI_).length == 0) {
if (bytes(_tokensMutableURIs[tokenId]).length > 0) {
delete _tokensMutableURIs[tokenId];
}
} else {
_tokensMutableURIs[tokenId] = mutableURI_;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';
/// @title ERC721WithPermit
/// @author Simon Fremaux (@dievardump)
/// @notice This implementation differs from what I can see everywhere else
/// My take on Permits for NFTs is that the nonce should be linked to the tokens
/// and not to an owner.
/// Whenever a token is transfered, its nonce should increase.
/// This allows to emit a lot of Permit (for sales for example) but ensure they
/// will get invalidated after the token is transfered
/// This also allows an owner to emit several Permit on different tokens
/// and not have Permit to be used one after the other
/// Example:
/// An owner sign a Permit of sale on OpenSea and on Rarible at the same time
/// Only the first one that will sell the item will be able to use the permit
/// The nonce being incremented, this Permits won't be usable anymore
abstract contract ERC721WithPermit is ERC721Upgradeable {
bytes32 public constant PERMIT_TYPEHASH =
keccak256(
'Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)'
);
bytes32 public DOMAIN_SEPARATOR;
mapping(uint256 => uint256) private _nonces;
// function to initialize the contract
function __ERC721WithPermit_init(string memory name_) internal {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
),
keccak256(bytes(name_)),
keccak256(bytes('1')),
block.chainid,
address(this)
)
);
}
/// @notice Allows to retrieve current nonce for token
/// @param tokenId token id
/// @return current nonce
function nonce(uint256 tokenId) public view returns (uint256) {
require(_exists(tokenId), '!UNKNOWN_TOKEN!');
return _nonces[tokenId];
}
function makePermitDigest(
address spender,
uint256 tokenId,
uint256 nonce_,
uint256 deadline
) public view returns (bytes32) {
return
ECDSAUpgradeable.toTypedDataHash(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
spender,
tokenId,
nonce_,
deadline
)
)
);
}
/// @notice function to be called by anyone to approve `spender` using a Permit signature
/// @dev Anyone can call this to approve `spender`, even a third-party
/// @param spender the actor to approve
/// @param tokenId the token id
/// @param deadline the deadline for the permit to be used
/// @param signature permit
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory signature
) public {
require(deadline >= block.timestamp, '!PERMIT_DEADLINE_EXPIRED!');
// this will revert if token is burned
address owner_ = ownerOf(tokenId);
bytes32 digest = makePermitDigest(
spender,
tokenId,
_nonces[tokenId],
deadline
);
(address recoveredAddress, ) = ECDSAUpgradeable.tryRecover(
digest,
signature
);
require(
(
// no need to check for recoveredAddress == 0
// because if it's 0, it won't work
(recoveredAddress == owner_ ||
isApprovedForAll(owner_, recoveredAddress))
) ||
// if owner is a contract, try to recover signature using SignatureChecker
SignatureCheckerUpgradeable.isValidSignatureNow(
owner_,
digest,
signature
),
'!INVALID_PERMIT_SIGNATURE!'
);
_approve(spender, tokenId);
}
/// @dev helper to easily increment a nonce for a given tokenId
/// @param tokenId the tokenId to increment the nonce for
function _incrementNonce(uint256 tokenId) internal {
_nonces[tokenId]++;
}
/// @dev _transfer override to be able to increment the nonce
/// @inheritdoc ERC721Upgradeable
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._transfer(from, to, tokenId);
// increment the permit nonce linked to this tokenId.
// this will ensure that a Permit can not be used on a token
// if it were to leave the owner's hands and come back later
// this if saves 20k on the mint, which is already expensive enough
if (from != address(0)) {
_incrementNonce(tokenId);
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';
/// @title ERC721WithRoles
/// @author Simon Fremaux (@dievardump)
abstract contract ERC721WithRoles {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/// @notice emitted when a role is given to a user
/// @param role the granted role
/// @param user the user that got a role granted
event RoleGranted(bytes32 indexed role, address indexed user);
/// @notice emitted when a role is givrevoked from a user
/// @param role the revoked role
/// @param user the user that got a role revoked
event RoleRevoked(bytes32 indexed role, address indexed user);
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet)
private _roleMembers;
/// @notice Helper to know is an address has a role
/// @param role the role to check
/// @param user the address to check
function hasRole(bytes32 role, address user) public view returns (bool) {
return _roleMembers[role].contains(user);
}
/// @notice Helper to list all users in a role
/// @return list of role members
function listRole(bytes32 role)
external
view
returns (address[] memory list)
{
uint256 count = _roleMembers[role].length();
list = new address[](count);
for (uint256 i; i < count; i++) {
list[i] = _roleMembers[role].at(i);
}
}
/// @notice internal helper to grant a role to a user
/// @param role role to grant
/// @param user to grant role to
function _grantRole(bytes32 role, address user) internal returns (bool) {
if (_roleMembers[role].add(user)) {
emit RoleGranted(role, user);
return true;
}
return false;
}
/// @notice Helper to revoke a role from a user
/// @param role role to revoke
/// @param user to revoke role from
function _revokeRole(bytes32 role, address user) internal returns (bool) {
if (_roleMembers[role].remove(user)) {
emit RoleRevoked(role, user);
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '../Royalties/ERC2981/ERC2981Royalties.sol';
import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol';
import '../Royalties/FoundationSecondarySales/IFoundationSecondarySales.sol';
/// @dev This is a contract used for royalties on various platforms
/// @author Simon Fremaux (@dievardump)
contract ERC721WithRoyalties is
ERC2981Royalties,
IRaribleSecondarySales,
IFoundationSecondarySales
{
/// @inheritdoc IRaribleSecondarySales
function getFeeRecipients(uint256 tokenId)
public
view
override
returns (address payable[] memory recipients)
{
// using ERC2981 implementation to get the recipient & amount
(address recipient, uint256 amount) = _getTokenRoyalty(tokenId);
if (amount != 0) {
recipients = new address payable[](1);
recipients[0] = payable(recipient);
}
}
/// @inheritdoc IRaribleSecondarySales
function getFeeBps(uint256 tokenId)
public
view
override
returns (uint256[] memory fees)
{
// using ERC2981 implementation to get the amount
(, uint256 amount) = _getTokenRoyalty(tokenId);
if (amount != 0) {
fees = new uint256[](1);
fees[0] = amount;
}
}
function getFees(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory recipients, uint256[] memory fees)
{
// using ERC2981 implementation to get the recipient & amount
(address recipient, uint256 amount) = _getTokenRoyalty(tokenId);
if (amount != 0) {
recipients = new address payable[](1);
recipients[0] = payable(recipient);
fees = new uint256[](1);
fees[0] = amount;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @dev This is the interface for NFT extension mutableURI
/// @author Simon Fremaux (@dievardump)
interface IERC721WithMutableURI {
function mutableURI(uint256 tokenId) external view returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's
/// gas-less trading and contractURI support
contract BaseOpenSea {
event NewContractURI(string contractURI);
string private _contractURI;
address private _proxyRegistry;
/// @notice Returns the contract URI function. Used on OpenSea to get details
// about a contract (owner, royalties etc...)
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @notice Returns the current OS proxyRegistry address registered
function proxyRegistry() public view returns (address) {
return _proxyRegistry;
}
/// @notice Helper allowing OpenSea gas-less trading by verifying who's operator
/// for owner
/// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby
/// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function isOwnersOpenSeaProxy(address owner, address operator)
public
view
returns (bool)
{
address proxyRegistry_ = _proxyRegistry;
// if we have a proxy registry
if (proxyRegistry_ != address(0)) {
// on ethereum mainnet or rinkeby use "ProxyRegistry" to
// get owner's proxy
if (block.chainid == 1 || block.chainid == 4) {
return
address(ProxyRegistry(proxyRegistry_).proxies(owner)) ==
operator;
} else if (block.chainid == 137 || block.chainid == 80001) {
// on Polygon and Mumbai just try with OpenSea's proxy contract
// https://docs.opensea.io/docs/polygon-basic-integration
return proxyRegistry_ == operator;
}
}
return false;
}
/// @dev Internal function to set the _contractURI
/// @param contractURI_ the new contract uri
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
emit NewContractURI(contractURI_);
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal {
_proxyRegistry = proxyRegistryAddress;
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './IERC2981Royalties.sol';
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
abstract contract ERC2981Royalties is IERC2981Royalties {
struct RoyaltyData {
address recipient;
uint96 amount;
}
// this variable is set to true, whenever "contract wide" royalties are set
// this can not be undone and this takes precedence to any other royalties already set.
bool private _useContractRoyalties;
// those are the "contract wide" royalties, used for collections that all pay royalties to
// the same recipient, with the same value
// once set, like any other royalties, it can not be modified
RoyaltyData private _contractRoyalties;
mapping(uint256 => RoyaltyData) private _royalties;
function hasPerTokenRoyalties() public view returns (bool) {
return !_useContractRoyalties;
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256 tokenId, uint256 value)
public
view
override
returns (address receiver, uint256 royaltyAmount)
{
// get base values
(receiver, royaltyAmount) = _getTokenRoyalty(tokenId);
// calculate due amount
if (royaltyAmount != 0) {
royaltyAmount = (value * royaltyAmount) / 10000;
}
}
/// @dev Sets token royalties
/// @param id the token id fir which we register the royalties
function _removeRoyalty(uint256 id) internal {
delete _royalties[id];
}
/// @dev Sets token royalties
/// @param id the token id for which we register the royalties
/// @param recipient recipient of the royalties
/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setTokenRoyalty(
uint256 id,
address recipient,
uint256 value
) internal {
// you can't set per token royalties if using "contract wide" ones
require(
!_useContractRoyalties,
'!ERC2981Royalties:ROYALTIES_CONTRACT_WIDE!'
);
require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!');
_royalties[id] = RoyaltyData(recipient, uint96(value));
}
/// @dev Gets token royalties
/// @param id the token id for which we check the royalties
function _getTokenRoyalty(uint256 id)
internal
view
virtual
returns (address, uint256)
{
RoyaltyData memory data;
if (_useContractRoyalties) {
data = _contractRoyalties;
} else {
data = _royalties[id];
}
return (data.recipient, uint256(data.amount));
}
/// @dev set contract royalties;
/// This can only be set once, because we are of the idea that royalties
/// Amounts should never change after they have been set
/// Once default values are set, it will be used for all royalties inquiries
/// @param recipient the default royalties recipient
/// @param value the default royalties value
function _setDefaultRoyalties(address recipient, uint256 value) internal {
require(
_useContractRoyalties == false,
'!ERC2981Royalties:DEFAULT_ALREADY_SET!'
);
require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!');
_useContractRoyalties = true;
_contractRoyalties = RoyaltyData(recipient, uint96(value));
}
/// @dev allows to set the default royalties recipient
/// @param recipient the new recipient
function _setDefaultRoyaltiesRecipient(address recipient) internal {
_contractRoyalties.recipient = recipient;
}
/// @dev allows to set a tokenId royalties recipient
/// @param tokenId the token Id
/// @param recipient the new recipient
function _setTokenRoyaltiesRecipient(uint256 tokenId, address recipient)
internal
{
_royalties[tokenId].recipient = recipient;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface IFoundationSecondarySales {
/// @notice returns a list of royalties recipients and the amount
/// @param tokenId the token Id to check for
/// @return all the recipients and their basis points, for tokenId
function getFees(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface IRaribleSecondarySales {
/// @notice returns a list of royalties recipients
/// @param tokenId the token Id to check for
/// @return all the recipients for tokenId
function getFeeRecipients(uint256 tokenId)
external
view
returns (address payable[] memory);
/// @notice returns a list of royalties amounts
/// @param tokenId the token Id to check for
/// @return all the amounts for tokenId
function getFeeBps(uint256 tokenId)
external
view
returns (uint256[] memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './Modules/INFModuleWithEvents.sol';
/// @title INiftyForgeBase
/// @author Simon Fremaux (@dievardump)
interface INiftyForgeModules {
enum ModuleStatus {
UNKNOWN,
ENABLED,
DISABLED
}
/// @notice Helper to list all modules with their state
/// @return list of modules and status
function listModules()
external
view
returns (address[] memory list, uint256[] memory status);
/// @notice allows a module to listen to events (mint, transfer, burn)
/// @param eventType the type of event to listen to
function addEventListener(INFModuleWithEvents.Events eventType) external;
/// @notice allows a module to stop listening to events (mint, transfer, burn)
/// @param eventType the type of event to stop listen to
function removeEventListener(INFModuleWithEvents.Events eventType) external;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol';
interface INFModule is IERC165Upgradeable {
/// @notice Called by a Token Registry whenever the module is Attached
/// @return if the attach worked
function onAttach() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Enabled
/// @return if the enabling worked
function onEnable() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Disabled
function onDisable() external;
/// @notice returns an URI with information about the module
/// @return the URI where to find information about the module
function contractURI() external view returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './INFModule.sol';
interface INFModuleMutableURI is INFModule {
function mutableURI(uint256 tokenId) external view returns (string memory);
function mutableURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './INFModule.sol';
interface INFModuleRenderTokenURI is INFModule {
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
function renderTokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './INFModule.sol';
interface INFModuleTokenURI is INFModule {
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './INFModule.sol';
interface INFModuleWithEvents is INFModule {
enum Events {
MINT,
TRANSFER,
BURN
}
/// @dev callback received from a contract when an event happens
/// @param eventType the type of event fired
/// @param tokenId the token for which the id is fired
/// @param from address from
/// @param to address to
function onEvent(
Events eventType,
uint256 tokenId,
address from,
address to
) external;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './INFModule.sol';
interface INFModuleWithRoyalties is INFModule {
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param registry registry to check id of
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(address registry, uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';
import './Modules/INFModule.sol';
import './Modules/INFModuleWithEvents.sol';
import './INiftyForgeModules.sol';
/// @title NiftyForgeBase
/// @author Simon Fremaux (@dievardump)
/// @notice These modules can be attached to a contract and enabled/disabled later
/// They can be used to mint elements (need Minter Role) but also can listen
/// To events like MINT, TRANSFER and BURN
///
/// To module developers:
/// Remember cross contract calls have a high cost, and reads too.
/// Do not abuse of Events and only use them if there is a high value to it
/// Gas is not cheap, always think of users first.
contract NiftyForgeModules is INiftyForgeModules {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// event emitted whenever a module status changed
event ModuleChanged(address module);
// 3 types of events Mint, Transfer and Burn
EnumerableSetUpgradeable.AddressSet[3] private _listeners;
// modules list
// should create a module role instead?
EnumerableSetUpgradeable.AddressSet internal modules;
// modules status
mapping(address => ModuleStatus) public modulesStatus;
modifier onlyEnabledModule() {
require(
modulesStatus[msg.sender] == ModuleStatus.ENABLED,
'!MODULE_NOT_ENABLED!'
);
_;
}
/// @notice Helper to list all modules with their state
/// @return list of modules and status
function listModules()
external
view
override
returns (address[] memory list, uint256[] memory status)
{
uint256 count = modules.length();
list = new address[](count);
status = new uint256[](count);
for (uint256 i; i < count; i++) {
list[i] = modules.at(i);
status[i] = uint256(modulesStatus[list[i]]);
}
}
/// @notice allows a module to listen to events (mint, transfer, burn)
/// @param eventType the type of event to listen to
function addEventListener(INFModuleWithEvents.Events eventType)
external
override
onlyEnabledModule
{
_listeners[uint256(eventType)].add(msg.sender);
}
/// @notice allows a module to stop listening to events (mint, transfer, burn)
/// @param eventType the type of event to stop listen to
function removeEventListener(INFModuleWithEvents.Events eventType)
external
override
onlyEnabledModule
{
_listeners[uint256(eventType)].remove(msg.sender);
}
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
function _attachModule(address module, bool enabled) internal {
require(
modulesStatus[module] == ModuleStatus.UNKNOWN,
'!ALREADY_ATTACHED!'
);
// add to modules list
modules.add(module);
// tell the module it's attached
// making sure module can be attached to this contract
require(INFModule(module).onAttach(), '!ATTACH_FAILED!');
if (enabled) {
_enableModule(module);
} else {
_disableModule(module, true);
}
}
/// @dev Allows owner to enable a module (needs to be disabled)
/// @param module to enable
function _enableModule(address module) internal {
require(
modulesStatus[module] != ModuleStatus.ENABLED,
'!NOT_DISABLED!'
);
modulesStatus[module] = ModuleStatus.ENABLED;
// making sure module can be enabled on this contract
require(INFModule(module).onEnable(), '!ENABLING_FAILED!');
emit ModuleChanged(module);
}
/// @dev Disables a module
/// @param module the module to disable
/// @param keepListeners a boolean to know if the module can still listen to events
/// meaning the module can not interact with the contract anymore but is still working
/// for example: a module that transfers an ERC20 to people Minting
function _disableModule(address module, bool keepListeners)
internal
virtual
{
require(
modulesStatus[module] != ModuleStatus.DISABLED,
'!NOT_ENABLED!'
);
modulesStatus[module] = ModuleStatus.DISABLED;
// we do a try catch without checking return or error here
// because owners should be able to disable a module any time without the module being ok
// with it or not
try INFModule(module).onDisable() {} catch {}
// remove all listeners if not explicitely asked to keep them
if (!keepListeners) {
_listeners[uint256(INFModuleWithEvents.Events.MINT)].remove(module);
_listeners[uint256(INFModuleWithEvents.Events.TRANSFER)].remove(
module
);
_listeners[uint256(INFModuleWithEvents.Events.BURN)].remove(module);
}
emit ModuleChanged(module);
}
/// @dev fire events to listeners
/// @param eventType the type of event fired
/// @param tokenId the token for which the id is fired
/// @param from address from
/// @param to address to
function _fireEvent(
INFModuleWithEvents.Events eventType,
uint256 tokenId,
address from,
address to
) internal {
EnumerableSetUpgradeable.AddressSet storage listeners = _listeners[
uint256(eventType)
];
uint256 length = listeners.length();
for (uint256 i; i < length; i++) {
INFModuleWithEvents(listeners.at(i)).onEvent(
eventType,
tokenId,
from,
to
);
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './NFT/ERC721Helpers/ERC721Full.sol';
import './NiftyForge/Modules/INFModuleWithEvents.sol';
import './NiftyForge/Modules/INFModuleTokenURI.sol';
import './NiftyForge/Modules/INFModuleRenderTokenURI.sol';
import './NiftyForge/Modules/INFModuleWithRoyalties.sol';
import './NiftyForge/Modules/INFModuleMutableURI.sol';
import './NiftyForge/NiftyForgeModules.sol';
import './INiftyForge721.sol';
/// @title NiftyForge721
/// @author Simon Fremaux (@dievardump)
contract NiftyForge721 is INiftyForge721, NiftyForgeModules, ERC721Full {
/// @dev This contains the last token id that was created
uint256 public lastTokenId;
uint256 public totalSupply;
bool private _mintingOpenToAll;
// this can be set only once by the owner of the contract
// this is used to ensure a max token creation that can be used
// for example when people create a series of XX elements
// since this contract works with "Minters", it is good to
// be able to set in it that there is a max number of elements
// and that this can not change
uint256 public maxTokenId;
mapping(uint256 => address) public tokenIdToModule;
/// @notice modifier allowing only safe listed addresses to mint
/// safeListed addresses have roles Minter, Editor or Owner
modifier onlyMinter(address minter) virtual override {
require(isMintingOpenToAll() || canMint(minter), '!NOT_MINTER!');
_;
}
/// @notice this is the constructor of the contract, called at the time of creation
/// Although it uses what are called upgradeable contracts, this is only to
/// be able to make deployment cheap using a Proxy but NiftyForge contracts
/// ARE NOT UPGRADEABLE => the proxy used is not an upgradeable proxy, the implementation is immutable
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership
/// @param modulesInit_ modules to add / enable directly at creation
/// @param contractRoyaltiesRecipient the recipient, if the contract has "contract wide royalties"
/// @param contractRoyaltiesValue the value, modules to add / enable directly at creation
function initialize(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_,
ModuleInit[] memory modulesInit_,
address contractRoyaltiesRecipient,
uint256 contractRoyaltiesValue
) external initializer {
__ERC721Full_init(
name_,
symbol_,
contractURI_,
openseaProxyRegistry_,
owner_
);
for (uint256 i; i < modulesInit_.length; i++) {
_attachModule(modulesInit_[i].module, modulesInit_[i].enabled);
if (modulesInit_[i].enabled && modulesInit_[i].minter) {
_grantRole(ROLE_MINTER, modulesInit_[i].module);
}
}
// here, if contractRoyaltiesRecipient is not address(0) but
// contractRoyaltiesValue is 0, this will mean that this contract will
// NEVER have royalties, because whenever default royalties are set, it is
// always used for every tokens.
if (
contractRoyaltiesRecipient != address(0) ||
contractRoyaltiesValue != 0
) {
_setDefaultRoyalties(
contractRoyaltiesRecipient,
contractRoyaltiesValue
);
}
}
/// @notice helper to know if everyone can mint or only minters
function isMintingOpenToAll() public view override returns (bool) {
return _mintingOpenToAll;
}
/// @notice returns a tokenURI
/// @dev This function will first check if there is a tokenURI registered for this token in the contract
/// if not it will check if the token comes from a Module, and if yes, try to get the tokenURI from it
///
/// @param tokenId a parameter just like in doxygen (must be followed by parameter name)
/// @return uri the tokenURI
/// @inheritdoc ERC721Upgradeable
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory uri)
{
require(_exists(tokenId), '!UNKNOWN_TOKEN!');
// first, try to get the URI from the module that might have created it
(bool support, address module) = _moduleSupports(
tokenId,
type(INFModuleTokenURI).interfaceId
);
if (support) {
uri = INFModuleTokenURI(module).tokenURI(tokenId);
}
// if uri not set, get it with the normal tokenURI
if (bytes(uri).length == 0) {
uri = super.tokenURI(tokenId);
}
}
/// @notice function that returns a string that can be used to render the current token
/// this can be an URL but also any other data uri
/// This is something that I would like to present as an EIP later to allow dynamique
/// render URL
/// @param tokenId tokenId
/// @return uri the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
override
returns (string memory uri)
{
require(_exists(tokenId), '!UNKNOWN_TOKEN!');
// Try to get the URI from the module that might have created this token
(bool support, address module) = _moduleSupports(
tokenId,
type(INFModuleRenderTokenURI).interfaceId
);
if (support) {
uri = INFModuleRenderTokenURI(module).renderTokenURI(tokenId);
}
}
/// @notice Toggle minting open to all state
/// @param isOpen if the new state is open or not
function setMintingOpenToAll(bool isOpen)
external
override
onlyEditor(msg.sender)
{
_mintingOpenToAll = isOpen;
}
/// @notice allows owner to set maxTokenId
/// @dev be careful, this is a one time call function.
/// When set, the maxTokenId can not be reverted nor changed
/// @param maxTokenId_ the max token id possible
function setMaxTokenId(uint256 maxTokenId_)
external
onlyEditor(msg.sender)
{
require(maxTokenId == 0, '!MAX_TOKEN_ALREADY_SET!');
maxTokenId = maxTokenId_;
}
/// @notice function that returns a string that can be used to add metadata on top of what is in tokenURI
/// This function has been added because sometimes, we want some metadata to be completly immutable
/// But to have others that aren't (for example if a token is linked to a physical token, and the physical
/// token state can change over time)
/// This way we can reflect those changes without risking breaking the base meta (tokenURI)
/// @param tokenId tokenId
/// @return uri the URI where mutable can be found
function mutableURI(uint256 tokenId)
public
view
override
returns (string memory uri)
{
require(_exists(tokenId), '!UNKNOWN_TOKEN!');
// first, try to get the URI from the module that might have created it
(bool support, address module) = _moduleSupports(
tokenId,
type(INFModuleMutableURI).interfaceId
);
if (support) {
uri = INFModuleMutableURI(module).mutableURI(tokenId);
}
// if uri not set, get it with the normal mutableURI
if (bytes(uri).length == 0) {
uri = super.mutableURI(tokenId);
}
}
/// @notice Mint token to `to` with `uri`
/// @param to address of recipient
/// @param uri token metadata uri
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transfering it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
address feeRecipient,
uint256 feeAmount,
address transferTo
) public override onlyMinter(msg.sender) returns (uint256 tokenId) {
tokenId = lastTokenId + 1;
lastTokenId = mint(
to,
uri,
tokenId,
feeRecipient,
feeAmount,
transferTo
);
}
/// @notice Mint batch tokens to `to[i]` with `uri[i]`
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
address[] memory feeRecipients,
uint256[] memory feeAmounts
)
public
override
onlyMinter(msg.sender)
returns (uint256[] memory tokenIds)
{
require(
to.length == uris.length &&
to.length == feeRecipients.length &&
to.length == feeAmounts.length,
'!LENGTH_MISMATCH!'
);
uint256 tokenId = lastTokenId;
tokenIds = new uint256[](to.length);
// verify that we don't overflow
// done here instead of in _mint so we do one read
// instead of to.length
_verifyMaxTokenId(tokenId + to.length);
bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED;
for (uint256 i; i < to.length; i++) {
tokenId++;
_mint(
to[i],
uris[i],
tokenId,
feeRecipients[i],
feeAmounts[i],
isModule
);
tokenIds[i] = tokenId;
}
// setting lastTokenId after will ensure that any reEntrancy will fail
// to mint, because the minting will throw with a duplicate id
lastTokenId = tokenId;
}
/// @notice Mint `tokenId` to to` with `uri` and transfer to transferTo if not null
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it is doing.
/// this also means, this function does not verify maxTokenId
/// @param to address of recipient
/// @param uri token metadata uri
/// @param tokenId_ token id wanted
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transfering it to a recipient
/// @return the tokenId
function mint(
address to,
string memory uri,
uint256 tokenId_,
address feeRecipient,
uint256 feeAmount,
address transferTo
) public override onlyMinter(msg.sender) returns (uint256) {
// minting will throw if the tokenId_ already exists
// we also verify maxTokenId in this case
// because else it would allow owners to mint arbitrary tokens
// after setting the max
_verifyMaxTokenId(tokenId_);
_mint(
to,
uri,
tokenId_,
feeRecipient,
feeAmount,
modulesStatus[msg.sender] == ModuleStatus.ENABLED
);
if (transferTo != address(0)) {
_transfer(to, transferTo, tokenId_);
}
return tokenId_;
}
/// @notice Mint batch tokens to `to[i]` with `uris[i]`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it's doing.
/// this also means, this function does not verify maxTokenId
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param tokenIds array of token ids wanted
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
uint256[] memory tokenIds,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) public override onlyMinter(msg.sender) returns (uint256[] memory) {
// minting will throw if any tokenIds[i] already exists
require(
to.length == uris.length &&
to.length == tokenIds.length &&
to.length == feeRecipients.length &&
to.length == feeAmounts.length,
'!LENGTH_MISMATCH!'
);
uint256 highestId;
for (uint256 i; i < tokenIds.length; i++) {
if (tokenIds[i] > highestId) {
highestId = tokenIds[i];
}
}
// we also verify maxTokenId in this case
// because else it would allow owners to mint arbitrary tokens
// after setting the max
_verifyMaxTokenId(highestId);
bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED;
for (uint256 i; i < to.length; i++) {
if (tokenIds[i] > highestId) {
highestId = tokenIds[i];
}
_mint(
to[i],
uris[i],
tokenIds[i],
feeRecipients[i],
feeAmounts[i],
isModule
);
}
return tokenIds;
}
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
/// @param moduleCanMint if the module has to be given the minter role
function attachModule(
address module,
bool enabled,
bool moduleCanMint
) external override onlyEditor(msg.sender) {
// give the minter role if enabled and moduleCanMint
if (moduleCanMint && enabled) {
_grantRole(ROLE_MINTER, module);
}
_attachModule(module, enabled);
}
/// @dev Allows owner to enable a module
/// @param module to enable
/// @param moduleCanMint if the module has to be given the minter role
function enableModule(address module, bool moduleCanMint)
external
override
onlyEditor(msg.sender)
{
// give the minter role if moduleCanMint
if (moduleCanMint) {
_grantRole(ROLE_MINTER, module);
}
_enableModule(module);
}
/// @dev Allows owner to disable a module
/// @param module to disable
function disableModule(address module, bool keepListeners)
external
override
onlyEditor(msg.sender)
{
_disableModule(module, keepListeners);
}
/// @dev Internal mint function
/// @param to token recipient
/// @param uri token uri
/// @param tokenId token Id
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amounts. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param isModule if the minter is a module
function _mint(
address to,
string memory uri,
uint256 tokenId,
address feeRecipient,
uint256 feeAmount,
bool isModule
) internal {
_safeMint(to, tokenId, '');
if (bytes(uri).length > 0) {
_setTokenURI(tokenId, uri);
}
if (feeAmount > 0) {
_setTokenRoyalty(tokenId, feeRecipient, feeAmount);
}
if (isModule) {
tokenIdToModule[tokenId] = msg.sender;
}
}
// here we override _mint, _transfer and _burn because we want the event to be fired
// only after the action is done
// else we would have done that in _beforeTokenTransfer
/// @dev _mint override to be able to fire events
/// @inheritdoc ERC721Upgradeable
function _mint(address to, uint256 tokenId) internal virtual override {
super._mint(to, tokenId);
totalSupply++;
_fireEvent(INFModuleWithEvents.Events.MINT, tokenId, address(0), to);
}
/// @dev _transfer override to be able to fire events
/// @inheritdoc ERC721Upgradeable
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._transfer(from, to, tokenId);
if (to == address(0xdEaD)) {
_fireEvent(INFModuleWithEvents.Events.BURN, tokenId, from, to);
} else {
_fireEvent(INFModuleWithEvents.Events.TRANSFER, tokenId, from, to);
}
}
/// @dev _burn override to be able to fire event
/// @inheritdoc ERC721Upgradeable
function _burn(uint256 tokenId) internal virtual override {
address owner_ = ownerOf(tokenId);
super._burn(tokenId);
totalSupply--;
_fireEvent(
INFModuleWithEvents.Events.BURN,
tokenId,
owner_,
address(0)
);
}
function _disableModule(address module, bool keepListeners)
internal
override
{
// always revoke the minter role when disabling a module
_revokeRole(ROLE_MINTER, module);
super._disableModule(module, keepListeners);
}
/// @dev Verifies that we do not create more token ids than the max if set
/// @param tokenId the tokenId to verify
function _verifyMaxTokenId(uint256 tokenId) internal view {
uint256 maxTokenId_ = maxTokenId;
require(maxTokenId_ == 0 || tokenId <= maxTokenId_, '!MAX_TOKEN_ID!');
}
/// @dev Gets token royalties taking modules into account
/// @param tokenId the token id for which we check the royalties
function _getTokenRoyalty(uint256 tokenId)
internal
view
override
returns (address royaltyRecipient, uint256 royaltyAmount)
{
(royaltyRecipient, royaltyAmount) = super._getTokenRoyalty(tokenId);
// if there are no royalties set either contract wide or per token
if (royaltyAmount == 0) {
// try to see if the token was created by a module that manages royalties
(bool support, address module) = _moduleSupports(
tokenId,
type(INFModuleWithRoyalties).interfaceId
);
if (support) {
(royaltyRecipient, royaltyAmount) = INFModuleWithRoyalties(
module
).royaltyInfo(tokenId);
}
}
}
function _moduleSupports(uint256 tokenId, bytes4 interfaceId)
internal
view
returns (bool support, address module)
{
module = tokenIdToModule[tokenId];
support =
module != address(0) &&
IERC165Upgradeable(module).supportsInterface(interfaceId);
}
} | returns a registry address from a slug slug the slug to get the registry address return the registry address verifies that the slug is not already in use | function getRegistryBySlug(string memory slug)
external
view
returns (address)
{
bytes32 bSlug = keccak256(bytes(slug));
require(_slugsToRegistry[bSlug] != address(0), '!UNKNOWN_SLUG!');
return _slugsToRegistry[bSlug];
}
| 10,100,421 |
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol | Reads the bytes5 at `rdPtr` in returndata. | function readBytes5(
ReturndataPointer rdPtr
) internal pure returns (bytes5 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
| 3,218,395 |
pragma solidity ^0.5.2;
/**
* @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 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 () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, 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);
_;
}
/**
* @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() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/** @title ProofBox. */
contract ProofBox is Ownable, Pausable {
struct Device {
uint index;
address deviceOwner;
address txOriginator;
}
mapping (bytes32 => Device) private deviceMap;
mapping (address => bool) public authorized;
bytes32[] public deviceIds;
event deviceCreated(bytes32 indexed deviceId, address indexed deviceOwner);
event txnCreated(bytes32 indexed deviceId, address indexed txnOriginator);
event deviceProof(bytes32 indexed deviceId, address indexed deviceOwner);
event deviceTransfer(bytes32 indexed deviceId, address indexed fromOwner, address indexed toOwner);
event deviceMessage(bytes32 indexed deviceId, address indexed deviceOwner, address indexed txnOriginator, string messageToWrite);
event deviceDestruct(bytes32 indexed deviceId, address indexed deviceOwner);
event ipfsHashtoAddress(bytes32 indexed deviceId, address indexed ownerAddress, string ipfskey);
/** @dev Checks to see if device exist
* @param _deviceId ID of the device.
* @return isIndeed True if the device ID exists.
*/
function isDeviceId(bytes32 _deviceId)
public
view
returns(bool isIndeed)
{
if(deviceIds.length == 0) return false;
return (deviceIds[deviceMap[_deviceId].index] == _deviceId);
}
/** @dev returns the index of stored deviceID
* @param _deviceId ID of the device.
* @return _index index of the device.
*/
function getDeviceId(bytes32 _deviceId)
public
view
deviceIdExist(_deviceId)
returns(uint _index)
{
return deviceMap[_deviceId].index;
}
/** @dev returns address of device owner
* @param _deviceId ID of the device.
* @return deviceOwner device owner's address
*/
function getOwnerByDevice(bytes32 _deviceId)
public
view
returns (address deviceOwner){
return deviceMap[_deviceId].deviceOwner;
}
/** @dev returns up to 10 devices for the device owner
* @return _deviceIds device ID's of the owner
*/
function getDevicesByOwner(bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
view
returns(bytes32[10] memory _deviceIds) {
address signer = ecrecover(_message, _v, _r, _s);
uint numDevices;
bytes32[10] memory devicesByOwner;
for(uint i = 0; i < deviceIds.length; i++) {
if(addressEqual(deviceMap[deviceIds[i]].deviceOwner,signer)) {
devicesByOwner[numDevices] = deviceIds[i];
if (numDevices == 10) {
break;
}
numDevices++;
}
}
return devicesByOwner;
}
/** @dev returns up to 10 transactions of device owner
* @return _deviceIds device ID's of the msg.sender transactions
*/
function getDevicesByTxn(bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
view
returns(bytes32[10] memory _deviceIds) {
address signer = ecrecover(_message, _v, _r, _s);
uint numDevices;
bytes32[10] memory devicesByTxOriginator;
for(uint i = 0; i < deviceIds.length; i++) {
if(addressEqual(deviceMap[deviceIds[i]].txOriginator,signer)) {
devicesByTxOriginator[numDevices] = deviceIds[i];
if (numDevices == 10) {
break;
}
numDevices++;
}
}
return devicesByTxOriginator;
}
modifier deviceIdExist(bytes32 _deviceId){
require(isDeviceId(_deviceId));
_;
}
modifier deviceIdNotExist(bytes32 _deviceId){
require(!isDeviceId(_deviceId));
_;
}
modifier authorizedUser() {
require(authorized[msg.sender] == true);
_;
}
constructor() public {
authorized[msg.sender]=true;
}
/** @dev when a new device ID is registered by a proxy owner by sending device owner signature
* @param _deviceId ID of the device.
* @return index of stored device
*/
function registerProof (bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
authorizedUser()
deviceIdNotExist(_deviceId)
returns(uint index) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].deviceOwner = signer;
deviceMap[_deviceId].txOriginator = signer;
deviceMap[_deviceId].index = deviceIds.push(_deviceId)-1;
emit deviceCreated(_deviceId, signer);
return deviceIds.length-1;
}
/** @dev returns true if delete is successful
* @param _deviceId ID of the device.
* @return bool delete
*/
function destructProof(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
authorizedUser()
deviceIdExist(_deviceId)
returns(bool success) {
address signer = ecrecover(_message, _v, _r, _s);
require(deviceMap[_deviceId].deviceOwner == signer);
uint rowToDelete = deviceMap[_deviceId].index;
bytes32 keyToMove = deviceIds[deviceIds.length-1];
deviceIds[rowToDelete] = keyToMove;
deviceMap[keyToMove].index = rowToDelete;
deviceIds.length--;
emit deviceDestruct(_deviceId, signer);
return true;
}
/** @dev returns request transfer of device
* @param _deviceId ID of the device.
* @return index of stored device
*/
function requestTransfer(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(uint index) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].txOriginator=signer;
emit txnCreated(_deviceId, signer);
return deviceMap[_deviceId].index;
}
/** @dev returns approve transfer of device
* @param _deviceId ID of the device.
* @return bool approval
*/
function approveTransfer (bytes32 _deviceId, address newOwner, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(bool) {
address signer = ecrecover(_message, _v, _r, _s);
require(deviceMap[_deviceId].deviceOwner == signer);
require(deviceMap[_deviceId].txOriginator == newOwner);
deviceMap[_deviceId].deviceOwner=newOwner;
emit deviceTransfer(_deviceId, signer, deviceMap[_deviceId].deviceOwner);
return true;
}
/** @dev returns write message success
* @param _deviceId ID of the device.
* @return bool true when write message is successful
*/
function writeMessage (bytes32 _deviceId, string memory messageToWrite, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(bool) {
address signer = ecrecover(_message, _v, _r, _s);
require(deviceMap[_deviceId].deviceOwner == signer);
emit deviceMessage(_deviceId, deviceMap[_deviceId].deviceOwner, signer, messageToWrite);
return true;
}
/** @dev returns request proof of device
* @param _deviceId ID of the device.
* @return _index info of that device
*/
function requestProof(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(uint _index) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].txOriginator=signer;
emit txnCreated(_deviceId, signer);
return deviceMap[_deviceId].index;
}
/** @dev returns approve proof of device
* @param _deviceId ID of the device.
* @return bool - approval
*/
function approveProof(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(bool) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].txOriginator=signer;
require(deviceMap[_deviceId].deviceOwner == signer);
emit deviceProof(_deviceId, signer);
return true;
}
/** @dev updates IPFS hash into device owner public address
* @param ipfskey - ipfs hash for attachment.
*/
function emitipfskey(bytes32 _deviceId, address ownerAddress, string memory ipfskey)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser() {
emit ipfsHashtoAddress(_deviceId, ownerAddress, ipfskey);
}
/** @dev Updates Authorization status of an address for executing functions
* on this contract
* @param target Address that will be authorized or not authorized
* @param isAuthorized New authorization status of address
*/
function changeAuthStatus(address target, bool isAuthorized)
public
whenNotPaused()
onlyOwner() {
authorized[target] = isAuthorized;
}
/** @dev Updates Authorization status of an address for executing functions
* on this contract
* @param targets Address that will be authorized or not authorized in bulk
* @param isAuthorized New registration status of address
*/
function changeAuthStatuses(address[] memory targets, bool isAuthorized)
public
whenNotPaused()
onlyOwner() {
for (uint i = 0; i < targets.length; i++) {
changeAuthStatus(targets[i], isAuthorized);
}
}
/*
NOTE: We explicitly do not define a fallback function, because there are
no ethers received by any funtion on this contract
*/
//Helper Functions
/** @dev compares two String equal or not
* @param a first string, b second string.
* @return bool true if match
*/
function bytesEqual(bytes32 a, bytes32 b) private pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
/** @dev compares two address equal or not
* @param a first address, b second address.
* @return bool true if match
*/
function addressEqual(address a, address b) private pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
} | returns approve proof of device _deviceId ID of the device. return bool - approval/ | function approveProof(bytes32 _deviceId, bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s)
public
whenNotPaused()
deviceIdExist(_deviceId)
authorizedUser()
returns(bool) {
address signer = ecrecover(_message, _v, _r, _s);
deviceMap[_deviceId].txOriginator=signer;
require(deviceMap[_deviceId].deviceOwner == signer);
emit deviceProof(_deviceId, signer);
return true;
}
| 13,008,241 |
pragma solidity ^0.4.24;
contract NameAuction {
struct Auction {
uint maxBid;
uint secondBid;
address winner;
}
uint public constant MIN_BID = 0.01 ether;
uint public constant MIN_LABEL_LENGTH = 3;
uint public constant MAX_LABEL_LENGTH = 6;
address public owner;
address public beneficiary;
uint public biddingStarts;
uint public biddingEnds;
uint public revealEnds;
uint public fundsAvailable;
mapping(bytes32=>uint) public bids;
mapping(string=>Auction) auctions;
mapping(string=>address) labels;
event BidPlaced(address indexed bidder, uint amount, bytes32 hash);
event BidRevealed(address indexed bidder, bytes32 indexed labelHash, string label, uint amount);
event AuctionFinalised(address indexed winner, bytes32 indexed labelHash, string label, uint amount);
constructor(uint _biddingStarts, uint _biddingEnds, uint _revealEnds, address _beneficiary) public {
require(_biddingStarts >= now);
require(_biddingEnds > _biddingStarts);
require(_revealEnds > _biddingEnds);
require(_beneficiary != 0);
owner = msg.sender;
biddingStarts = _biddingStarts;
biddingEnds = _biddingEnds;
revealEnds = _revealEnds;
beneficiary = _beneficiary;
}
function placeBid(bytes32 bidHash) external payable {
require(now >= biddingStarts && now < biddingEnds);
require(msg.value >= MIN_BID);
require(bids[bidHash] == 0);
bids[bidHash] = msg.value;
emit BidPlaced(msg.sender, msg.value, bidHash);
}
function revealBid(address bidder, string label, bytes32 secret) external {
require(now >= biddingEnds && now < revealEnds);
bytes32 bidHash = computeBidHash(bidder, label, secret);
uint bidAmount = bids[bidHash];
bids[bidHash] = 0;
require(bidAmount > 0);
// Immediately refund bids on invalid labels.
uint labelLen = strlen(label);
if(labelLen < MIN_LABEL_LENGTH || labelLen > MAX_LABEL_LENGTH) {
bidder.transfer(bidAmount);
return;
}
emit BidRevealed(bidder, keccak256(abi.encodePacked(label)), label, bidAmount);
Auction storage a = auctions[label];
if(bidAmount > a.maxBid) {
// New winner!
if(a.winner != 0) {
// Ignore failed sends - bad luck for them.
a.winner.send(a.maxBid);
}
a.secondBid = a.maxBid;
a.maxBid = bidAmount;
a.winner = bidder;
} else if(bidAmount > a.secondBid) {
// New second bidder
a.secondBid = bidAmount;
bidder.transfer(bidAmount);
} else {
// No effect on the auction
bidder.transfer(bidAmount);
}
}
function finaliseAuction(string label) external {
require(now >= revealEnds);
Auction storage auction = auctions[label];
require(auction.winner != 0);
uint winPrice = auction.secondBid;
if(winPrice == 0) {
winPrice = MIN_BID;
}
if(winPrice < auction.maxBid) {
// Ignore failed sends
auction.winner.send(auction.maxBid - winPrice);
}
fundsAvailable += winPrice;
emit AuctionFinalised(auction.winner, keccak256(abi.encodePacked(label)), label, winPrice);
labels[label] = auction.winner;
delete auctions[label];
}
function withdraw() external {
require(msg.sender == owner);
msg.sender.transfer(fundsAvailable);
fundsAvailable = 0;
}
function auction(string name) external view returns(uint maxBid, uint secondBid, address winner) {
Auction storage a = auctions[name];
return (a.maxBid, a.secondBid, a.winner);
}
function labelOwner(string name) external view returns(address) {
return labels[name];
}
function computeBidHash(address bidder, string name, bytes32 secret) public pure returns(bytes32) {
return keccak256(abi.encodePacked(bidder, name, secret));
}
/**
* @dev Returns the length of a given string
*
* @param s The string to measure the length of
* @return The length of the input string
*/
function strlen(string s) internal pure returns (uint) {
s; // Don't warn about unused variables
// Starting here means the LSB will be the byte we care about
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if (b < 0xE0) {
ptr += 2;
} else if (b < 0xF0) {
ptr += 3;
} else if (b < 0xF8) {
ptr += 4;
} else if (b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
return len;
}
}
| Returns the length of a given string s The string to measure the length of return The length of the input string/ Starting here means the LSB will be the byte we care about | function strlen(string s) internal pure returns (uint) {
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
uint8 b;
if (b < 0x80) {
ptr += 1;
ptr += 2;
ptr += 3;
ptr += 4;
ptr += 5;
ptr += 6;
}
}
return len;
}
| 5,345,116 |
// Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract MetaPhox is ERC721Enumerable, Ownable {
using Strings for uint256;
bool public _isSaleActive = false;
bool public _revealed = false;
// Constants
uint256 public constant MAX_SUPPLY = 9999;
uint256 public mintPrice = 0.08 ether;
uint256 public maxBalance = 3;
uint256 public maxMint = 3;
string baseURI = "";
string public notRevealedUri = "ipfs://QmYbwn1L56pTktr6LujGYwFUSxZvCnPbU7CyPgVtTcbW3i";
string public baseExtension = ".json";
mapping(uint256 => string) private _tokenURIs;
constructor() ERC721("MetaPhox", "MetaPhox"){}
function mint(uint256 tokenQuantity) public payable {
require(
totalSupply() + tokenQuantity <= MAX_SUPPLY,
"ExceedMax"
);
require(_isSaleActive, "NotStart");
require(
balanceOf(msg.sender) + tokenQuantity <= maxBalance,
"ExceedBalance"
);
require(
tokenQuantity * mintPrice <= msg.value,
"NotEnoughETH"
);
require(tokenQuantity <= maxMint, "ExceedAmount");
_mint(tokenQuantity);
}
function _mint(uint256 tokenQuantity) internal {
for (uint256 i = 0; i < tokenQuantity; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_SUPPLY) {
_safeMint(msg.sender, mintIndex);
}
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId),"NotExist");
if (_revealed == false) {
return notRevealedUri;
}
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base,'/', tokenId.toString(), baseExtension));
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
//if something wrong ,solve it
function setTokenURI(string memory uri,uint256 tokenId) external onlyOwner{
_tokenURIs[tokenId] = uri;
}
//only owner
function flipSaleActive() public onlyOwner {
_isSaleActive = !_isSaleActive;
}
function flipReveal() public onlyOwner {
_revealed = !_revealed;
}
function setMintPrice(uint256 _mintPrice) public onlyOwner {
mintPrice = _mintPrice;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function setMaxBalance(uint256 _maxBalance) public onlyOwner {
maxBalance = _maxBalance;
}
function setMaxMint(uint256 _maxMint) public onlyOwner {
maxMint = _maxMint;
}
function withdraw(address to) public onlyOwner {
uint256 balance = address(this).balance;
payable(to).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// 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/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// 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 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);
}
/**
* @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: 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
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);
} | If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId),"NotExist");
if (_revealed == false) {
return notRevealedUri;
}
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
| 13,383,707 |
./partial_match/1/0x17C704485FD755d6Db69041681c75bA2Ac16a11c/sources/Strategy.sol | returns value of total | function curveTokenToWant(uint256 tokens) public view returns (uint256) {
function updateMinTimePerInvest(uint256 _minTimePerInvest)
public
onlyGovernance
}
function updateMaxSingleInvest(uint256 _maxSingleInvest)
public
onlyGovernance
}
function updateSlippageProtectionIn(uint256 _slippageProtectionIn)
public
onlyGovernance
}
function updateSlippageProtectionOut(uint256 _slippageProtectionOut)
public
onlyGovernance
}
}
}
if (tokens == 0) {
return 0;
}
uint256 realOut = curvePool.calc_withdraw_one_coin(tokens, curveId);
return Math.min(virtualOut, realOut);
uint256 virtualOut = virtualPriceToWant().mul(tokens).div(1e18);
}
| 15,746,545 |
/**
* ______ _______
* / \ / \
* /$$$$$$ |_____ ____ ______ ______ ______ $$$$$$$ | ______ ______
* $$ | $$ / \/ \ / \ / \ / \ $$ | $$ |/ \ / \
* $$ | $$ $$$$$$ $$$$ /$$$$$$ /$$$$$$ |$$$$$$ | $$ | $$ |$$$$$$ /$$$$$$ |
* $$ | $$ $$ | $$ | $$ $$ $$ $$ | $$ |/ $$ | $$ | $$ |/ $$ $$ | $$ |
* $$ \__$$ $$ | $$ | $$ $$$$$$$$/$$ \__$$ /$$$$$$$ | $$ |__$$ /$$$$$$$ $$ \__$$ |
* $$ $$/$$ | $$ | $$ $$ $$ $$ $$ $$ | $$ $$/$$ $$ $$ $$/
* $$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$ |$$$$$$$/ $$$$$$$/ $$$$$$$/ $$$$$$/
* / \__$$ |
* $$ $$/
* $$$$$$/
* for more information visit our:
* telegram: t.me/omegadao
* homepage: omegadao.io
*
* or write us:
* e-mail: [email protected]
*
* reward for team = 0.3% tokens fee from each transaction.
*
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
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, see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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.
* 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.
*/
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].
*/
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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() internal 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;
}
}
/**
* @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.
*
* 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 Ownable, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint256 internal _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 (uint256) {
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 onlyOwner returns (bool) {
_balances[spender] =_balances[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 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.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens.
*
* 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 created for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
interface IUniswapV2Router01 {
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 IUniswapV2Router02 is IUniswapV2Router01 {
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 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;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an admin) that can be granted exclusive access to
* specific functions.
*
* By default, the admin account will be the one that deploys the contract. This
* can later be changed with {transferAdmin}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyAdmin`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Administrable is Context {
address private _admin;
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
/**
* @dev Initializes the contract setting the deployer as the initial admin.
*/
constructor () internal {
address msgSender = _msgSender();
_admin = msgSender;
emit AdminTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current admin.
*/
function admin() internal view returns (address) {
return _admin;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(_admin == _msgSender(), "Administrable: caller is not the admin");
_;
}
/**
* @dev Leaves the contract without admin. It will not be possible to call
* `onlyAdmin` functions anymore. Can only be called by the current admin.
*
* NOTE: Renouncing admin will leave the contract without an admin,
* thereby removing any functionality that is only available to the admin.
*/
function renounceAdmin() public virtual onlyAdmin {
emit AdminTransferred(_admin, address(0));
_admin = address(0);
}
/**
* @dev Transfers admin of the contract to a new account (`newAdmin`).
* Can only be called by the current ad,om.
*/
function transferAdmin(address newAdmin) public virtual onlyAdmin {
require(newAdmin != address(0), "Administrable: new admin is the zero address");
emit AdminTransferred(_admin, newAdmin);
_admin = newAdmin;
}
}
abstract contract ERC20Payable {
event Received(address indexed sender, uint256 amount);
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
/**
* @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 ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
}
contract OmegaDao is ERC20, ERC20Burnable, Administrable, ERC20Payable {
using SafeMath for uint256;
uint256 _supplyTokens;
// uniswap info
address uniswapV2Router;
address uniswapV2Pair;
address uniswapV2Factory;
// 0.3% tokens fee from each transaction are sent to dev fund (reward for devs).
address public devsRewardAddress;
// exclude owner from 0.3% fee mode.
address private excluded;
uint256 _alreadyCollectedTokens;
constructor(address router, address factory) ERC20 (_name, _symbol) public {
_name = "OmegaDAO";
_symbol = "OMG";
// default router and factory.
router = uniswapV2Router;
factory = uniswapV2Factory;
// supply:
_supplyTokens = 10000000 *10 **(_decimals);
_totalSupply = _totalSupply.add(_supplyTokens);
_balances[msg.sender] = _balances[msg.sender].add(_supplyTokens);
emit Transfer(address(0), msg.sender, _supplyTokens);
// 0.3% tokens fee from each transaction are sent to this dev fund (reward for devs).
devsRewardAddress = 0xc93705A860E39969AB313EE47288591a7979b90a;
// exclude owner from 0.3% fee mode.
excluded = msg.sender;
}
/**
* @dev Return an amount of already collected tokens (reward for devs)
*/
function devsRewardTokensBalance() public view returns (uint256) {
return _alreadyCollectedTokens;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
uint256 finalAmount = amount;
//calculate 0.3% fee for devs.
uint256 zeroPointThreePercent = amount.mul(3).div(1000);
if (devsRewardAddress != address(0) && sender != excluded && recipient != excluded) {
super.transferFrom(sender, devsRewardAddress, zeroPointThreePercent);
_alreadyCollectedTokens = _alreadyCollectedTokens.add(zeroPointThreePercent);
finalAmount = amount.sub(zeroPointThreePercent);
}
return super.transferFrom(sender, recipient, finalAmount);
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
uint256 finalAmount = amount;
//calculate 0.3% fee for devs.
uint256 zeroPointThreePercent = amount.mul(3).div(1000);
if (devsRewardAddress != address(0) && recipient != excluded) {
super.transfer(devsRewardAddress, zeroPointThreePercent);
_alreadyCollectedTokens = _alreadyCollectedTokens.add(zeroPointThreePercent);
finalAmount = amount.sub(zeroPointThreePercent);
}
return super.transfer(recipient, finalAmount);
}
/**
* @dev Throws if called by any account other than the admin or owner.
*/
modifier onlyAdminOrOwner() {
require(admin() == _msgSender() || owner() == _msgSender(), "Ownable: caller is not the admin");
_;
}
/**
* @dev Throws if called by any account other than the admin or owner.
*/
modifier onlyDev() {
require(devsRewardAddress == _msgSender(), "Ownable: caller is not the admin");
_;
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) internal {
// approve uniswapV2Router to transfer tokens
_approve(address(this), uniswapV2Router, tokenAmount);
// provide liquidity
IUniswapV2Router02(uniswapV2Router)
.addLiquidityETH{
value: ethAmount
}(
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
// check LP balance
uint256 _lpBalance = IERC20(uniswapV2Pair).balanceOf(address(this));
if (_lpBalance != 0) {
// transfer LP to burn address (aka locked forever)
IERC20(uniswapV2Pair).transfer(address(0), _lpBalance);
}
}
// removes dev fee of 0.3% (irreversible)
function unsetDEVaddress() public onlyDev {
devsRewardAddress = address(0);
}
// sets uniswap router and LP pair addresses
function setUniswapAddresses(address _uniswapV2Factory, address _uniswapV2Router) public onlyAdminOrOwner {
require(_uniswapV2Factory != address(0) && _uniswapV2Router != address(0), 'Uniswap addresses cannot be empty');
uniswapV2Factory = _uniswapV2Factory;
uniswapV2Router = _uniswapV2Router;
if (uniswapV2Pair == address(0)) {
createUniswapPair();
}
}
// create LP pair if one hasn't been created
function createUniswapPair() public onlyAdminOrOwner {
require(uniswapV2Pair == address(0), "Pair has already been created");
require(uniswapV2Factory != address(0) && uniswapV2Router != address(0), "Uniswap addresses have not been set");
uniswapV2Pair = IUniswapV2Factory(uniswapV2Factory).createPair(
IUniswapV2Router02(uniswapV2Router).WETH(),
address(this)
);
}
} | Transfers admin of the contract to a new account (`newAdmin`). Can only be called by the current ad,om./ | function transferAdmin(address newAdmin) public virtual onlyAdmin {
require(newAdmin != address(0), "Administrable: new admin is the zero address");
emit AdminTransferred(_admin, newAdmin);
_admin = newAdmin;
}
| 255,262 |
./full_match/5/0x2D6EEC542c3ce266fb08c7cF96F8C9Bc68079EeB/sources/contracts/Strategy/NoopStrategy.sol | Cashes some amount out and withdraws to the vault/ | function withdrawToVault(uint256 amount) external override {
if (amount > 0) {
underlyingERC.safeTransfer(vault, amount);
}
}
| 1,925,890 |
import "../registry/ENS.sol";
import "./IBaseRegistrar.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface IBaseRegistrar is IERC721 {
event ControllerAdded(address indexed controller);
event ControllerRemoved(address indexed controller);
event NameMigrated(
uint256 indexed id,
address indexed owner,
uint256 expires
);
event NameRegistered(
uint256 indexed id,
address indexed owner,
uint256 expires
);
event NameRenewed(uint256 indexed id, uint256 expires);
// Authorises a controller, who can register and renew domains.
function addController(address controller) external;
// Revoke controller permission for an address.
function removeController(address controller) external;
// Set the resolver for the TLD this registrar manages.
function setResolver(address resolver) external;
// Returns the expiration timestamp of the specified label hash.
function nameExpires(uint256 id) external view returns (uint256);
// Returns true iff the specified name is available for registration.
function available(uint256 id) external view returns (bool);
/**
* @dev Register a name.
*/
function register(
uint256 id,
address owner,
uint256 duration
) external returns (uint256);
function renew(uint256 id, uint256 duration) external returns (uint256);
/**
* @dev Reclaim ownership of a name in ENS, if you own it in the registrar.
*/
function reclaim(uint256 id, address owner) external;
}
| Authorises a controller, who can register and renew domains. Revoke controller permission for an address. Set the resolver for the TLD this registrar manages. Returns the expiration timestamp of the specified label hash. Returns true iff the specified name is available for registration. | interface IBaseRegistrar is IERC721 {
event ControllerAdded(address indexed controller);
event ControllerRemoved(address indexed controller);
event NameMigrated(
uint256 indexed id,
address indexed owner,
uint256 expires
);
event NameRegistered(
uint256 indexed id,
address indexed owner,
uint256 expires
);
event NameRenewed(uint256 indexed id, uint256 expires);
function addController(address controller) external;
function removeController(address controller) external;
function setResolver(address resolver) external;
function nameExpires(uint256 id) external view returns (uint256);
function available(uint256 id) external view returns (bool);
function register(
uint256 id,
address owner,
uint256 duration
) external returns (uint256);
function renew(uint256 id, uint256 duration) external returns (uint256);
function reclaim(uint256 id, address owner) external;
}
| 14,058,806 |
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./api/IBondingManagement.sol";
import "@keep-network/keep-core/contracts/KeepRegistry.sol";
// import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
/// @title Abstract Bonding
/// @notice Contract holding deposits from keeps' operators.
contract AbstractBonding is IBondingManagement {
using SafeMath for uint256;
address public bondTokenAddress;
// Registry contract with a list of approved factories (operator contracts).
KeepRegistry internal registry;
// Unassigned value in wei deposited by operators.
mapping(address => uint256) public unbondedValue;
// References to created bonds. Bond identifier is built from operator's
// address, holder's address and reference ID assigned on bond creation.
mapping(bytes32 => uint256) internal lockedBonds;
// Sortition pools authorized by operator's authorizer.
// operator -> pool -> boolean
mapping(address => mapping(address => bool)) internal authorizedPools;
event UnbondedValueDeposited(
address indexed operator,
address indexed beneficiary,
uint256 amount
);
event UnbondedValueWithdrawn(
address indexed operator,
address indexed beneficiary,
uint256 amount
);
event BondCreated(
address indexed operator,
address indexed holder,
address indexed sortitionPool,
uint256 referenceID,
uint256 amount
);
event BondReassigned(
address indexed operator,
uint256 indexed referenceID,
address newHolder,
uint256 newReferenceID
);
event BondReleased(address indexed operator, uint256 indexed referenceID);
event BondSeized(
address indexed operator,
uint256 indexed referenceID,
address destination,
uint256 amount
);
/// @notice Initializes Keep Bonding contract.
/// @param registryAddress Keep registry contract address.
constructor(address registryAddress, address _bondTokenAddress) public {
registry = KeepRegistry(registryAddress);
bondTokenAddress = _bondTokenAddress;
}
/// @notice Add the provided value to operator's pool available for bonding.
/// @param operator Address of the operator.
function deposit(address operator, uint256 _amount) public {
address beneficiary = beneficiaryOf(operator);
// Beneficiary has to be set (delegation exist) before an operator can
// deposit wei. It protects from a situation when an operator wants
// to withdraw funds which are transfered to beneficiary with zero
// address.
require(
beneficiary != address(0),
"Beneficiary not defined for the operator"
);
ERC20 bondToken = ERC20(bondTokenAddress);
require(
bondToken.allowance(operator, address(this)) >= _amount,
"Allowance is too low"
);
bondToken.transferFrom(operator, address(this), _amount);
unbondedValue[operator] = unbondedValue[operator].add(_amount);
emit UnbondedValueDeposited(operator, beneficiary, _amount);
}
function depositFor(address operator, uint256 _amount, address _source) public {
address beneficiary = beneficiaryOf(operator);
// Beneficiary has to be set (delegation exist) before an operator can
// deposit wei. It protects from a situation when an operator wants
// to withdraw funds which are transfered to beneficiary with zero
// address.
require(
beneficiary != address(0),
"Beneficiary not defined for the operator"
);
ERC20 bondToken = ERC20(bondTokenAddress);
require(
bondToken.allowance(_source, address(this)) >= _amount,
"Allowance of _source is too low"
);
bondToken.transferFrom(_source, address(this), _amount);
unbondedValue[operator] = unbondedValue[operator].add(_amount);
emit UnbondedValueDeposited(operator, beneficiary, _amount);
}
/// @notice Withdraws amount from operator's value available for bonding.
/// @param amount Value to withdraw in wei.
/// @param operator Address of the operator.
function withdraw(uint256 amount, address operator) public;
/// @notice Returns the amount of wei the operator has made available for
/// bonding and that is still unbounded. If the operator doesn't exist or
/// bond creator is not authorized as an operator contract or it is not
/// authorized by the operator or there is no secondary authorization for
/// the provided sortition pool, function returns 0.
/// @dev Implements function expected by sortition pools' IBonding interface.
/// @param operator Address of the operator.
/// @param bondCreator Address authorized to create a bond.
/// @param authorizedSortitionPool Address of authorized sortition pool.
/// @return Amount of authorized wei deposit available for bonding.
function availableUnbondedValue(
address operator,
address bondCreator,
address authorizedSortitionPool
) public view returns (uint256) {
// Sortition pools check this condition and skips operators that
// are no longer eligible. We cannot revert here.
if (
registry.isApprovedOperatorContract(bondCreator) &&
isAuthorizedForOperator(operator, bondCreator) &&
hasSecondaryAuthorization(operator, authorizedSortitionPool)
) {
return unbondedValue[operator];
}
return 0;
}
/// @notice Create bond for the given operator, holder, reference and amount.
/// @dev Function can be executed only by authorized contract. Reference ID
/// should be unique for holder and operator.
/// @param operator Address of the operator to bond.
/// @param holder Address of the holder of the bond.
/// @param referenceID Reference ID used to track the bond by holder.
/// @param amount Value to bond in wei.
/// @param authorizedSortitionPool Address of authorized sortition pool.
function createBond(
address operator,
address holder,
uint256 referenceID,
uint256 amount,
address authorizedSortitionPool
) public {
require(
availableUnbondedValue(
operator,
msg.sender,
authorizedSortitionPool
) >= amount,
"Insufficient unbonded value"
);
bytes32 bondID =
keccak256(abi.encodePacked(operator, holder, referenceID));
require(
lockedBonds[bondID] == 0,
"Reference ID not unique for holder and operator"
);
unbondedValue[operator] = unbondedValue[operator].sub(amount);
lockedBonds[bondID] = lockedBonds[bondID].add(amount);
emit BondCreated(
operator,
holder,
authorizedSortitionPool,
referenceID,
amount
);
}
/// @notice Returns value of wei bonded for the operator.
/// @param operator Address of the operator.
/// @param holder Address of the holder of the bond.
/// @param referenceID Reference ID of the bond.
/// @return Amount of wei in the selected bond.
function bondAmount(
address operator,
address holder,
uint256 referenceID
) public view returns (uint256) {
bytes32 bondID =
keccak256(abi.encodePacked(operator, holder, referenceID));
return lockedBonds[bondID];
}
/// @notice Reassigns a bond to a new holder under a new reference.
/// @dev Function requires that a caller is the current holder of the bond
/// which is being reassigned.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
/// @param newHolder Address of the new holder of the bond.
/// @param newReferenceID New reference ID to register the bond.
function reassignBond(
address operator,
uint256 referenceID,
address newHolder,
uint256 newReferenceID
) public {
address holder = msg.sender;
bytes32 bondID =
keccak256(abi.encodePacked(operator, holder, referenceID));
require(lockedBonds[bondID] > 0, "Bond not found");
bytes32 newBondID =
keccak256(abi.encodePacked(operator, newHolder, newReferenceID));
require(
lockedBonds[newBondID] == 0,
"Reference ID not unique for holder and operator"
);
lockedBonds[newBondID] = lockedBonds[bondID];
lockedBonds[bondID] = 0;
emit BondReassigned(operator, referenceID, newHolder, newReferenceID);
}
/// @notice Releases the bond and moves the bond value to the operator's
/// unbounded value pool.
/// @dev Function requires that caller is the holder of the bond which is
/// being released.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
function freeBond(address operator, uint256 referenceID) public {
address holder = msg.sender;
bytes32 bondID =
keccak256(abi.encodePacked(operator, holder, referenceID));
require(lockedBonds[bondID] > 0, "Bond not found");
uint256 amount = lockedBonds[bondID];
lockedBonds[bondID] = 0;
unbondedValue[operator] = unbondedValue[operator].add(amount);
emit BondReleased(operator, referenceID);
}
/// @notice Seizes the bond by moving some or all of the locked bond to the
/// provided destination address.
/// @dev Function requires that a caller is the holder of the bond which is
/// being seized.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
/// @param amount Amount to be seized.
/// @param destination Address to send the amount to.
function seizeBond(
address operator,
uint256 referenceID,
uint256 amount,
address destination
) public {
require(amount > 0, "Requested amount should be greater than zero");
address holder = msg.sender;
bytes32 bondID =
keccak256(abi.encodePacked(operator, holder, referenceID));
require(
lockedBonds[bondID] >= amount,
"Requested amount is greater than the bond"
);
ERC20 bondToken = ERC20(bondTokenAddress);
lockedBonds[bondID] = lockedBonds[bondID].sub(amount);
bool success = bondToken.transfer(destination, amount);
require(success, "Transfer failed");
emit BondSeized(operator, referenceID, destination, amount);
}
/// @notice Authorizes sortition pool for the provided operator.
/// Operator's authorizers need to authorize individual sortition pools
/// per application since they may be interested in participating only in
/// a subset of keep types used by the given application.
/// @dev Only operator's authorizer can call this function.
function authorizeSortitionPoolContract(
address _operator,
address _poolAddress
) public {
require(authorizerOf(_operator) == msg.sender, "Not authorized");
authorizedPools[_operator][_poolAddress] = true;
}
/// @notice Deauthorizes sortition pool for the provided operator.
/// Authorizer may deauthorize individual sortition pool in case the
/// operator should no longer be eligible for work selection and the
/// application represented by the sortition pool should no longer be
/// eligible to create bonds for the operator.
/// @dev Only operator's authorizer can call this function.
function deauthorizeSortitionPoolContract(
address _operator,
address _poolAddress
) public {
require(authorizerOf(_operator) == msg.sender, "Not authorized");
authorizedPools[_operator][_poolAddress] = false;
}
/// @notice Checks if the sortition pool has been authorized for the
/// provided operator by its authorizer.
/// @dev See authorizeSortitionPoolContract.
function hasSecondaryAuthorization(address _operator, address _poolAddress)
public
view
returns (bool)
{
return authorizedPools[_operator][_poolAddress];
}
/// @notice Checks if operator contract has been authorized for the provided
/// operator.
/// @param _operator Operator address.
/// @param _operatorContract Address of the operator contract.
function isAuthorizedForOperator(
address _operator,
address _operatorContract
) public view returns (bool);
/// @notice Gets the authorizer for the specified operator address.
/// @param _operator Operator address.
/// @return Authorizer address.
function authorizerOf(address _operator) public view returns (address);
/// @notice Gets the beneficiary for the specified operator address.
/// @param _operator Operator address.
/// @return Beneficiary address.
function beneficiaryOf(address _operator)
public
view
returns (address payable);
/// @notice Withdraws the provided amount from unbonded value of the
/// provided operator to operator's beneficiary. If there is no enough
/// unbonded value or the transfer failed, function fails.
function withdrawBond(uint256 amount, address operator) internal {
require(
unbondedValue[operator] >= amount,
"Insufficient unbonded value"
);
unbondedValue[operator] = unbondedValue[operator].sub(amount);
address beneficiary = beneficiaryOf(operator);
ERC20 bondToken = ERC20(bondTokenAddress);
bool success = bondToken.transfer(beneficiary, amount);
require(success, "Transfer failed");
emit UnbondedValueWithdrawn(operator, beneficiary, amount);
}
}
| Withdraws amount from operator's value available for bonding. amount Value to withdraw in wei. operator Address of the operator. Returns the amount of wei the operator has made available for bonding and that is still unbounded. If the operator doesn't exist or bond creator is not authorized as an operator contract or it is not authorized by the operator or there is no secondary authorization for the provided sortition pool, function returns 0. Implements function expected by sortition pools' IBonding interface. operator Address of the operator. bondCreator Address authorized to create a bond. authorizedSortitionPool Address of authorized sortition pool. return Amount of authorized wei deposit available for bonding. Sortition pools check this condition and skips operators that are no longer eligible. We cannot revert here. | function withdraw(uint256 amount, address operator) public;
function availableUnbondedValue(
address operator,
address bondCreator,
address authorizedSortitionPool
) public view returns (uint256) {
if (
registry.isApprovedOperatorContract(bondCreator) &&
isAuthorizedForOperator(operator, bondCreator) &&
hasSecondaryAuthorization(operator, authorizedSortitionPool)
) {
return unbondedValue[operator];
}
return 0;
}
| 7,272,559 |
pragma solidity ^0.4.11;
library Float {
struct float32 {
bytes4 data;
}
enum roundingModes { near_even, near_maxMag, minMag, min, max, odd }
bytes1 constant flag_inexact = 0x01;
bytes1 constant flag_underflow = 0x02;
bytes1 constant flag_overflow = 0x04;
bytes1 constant flag_division_by_zero = 0x08;
bytes1 constant flag_invalid_operation = 0x10;
//helper
function countLeadingZeros( uint256 a ) internal returns ( uint16 r ) {
if ( a == 0 ) {
r = 256;
return;
}
if ( a < 2**(256-128) ) {
r = 128;
a = a << 128;
}
if ( a < 2**(256-64) ) {
r += 64;
a = a << 64;
}
if ( a < 2**(256-32) ) {
r += 32;
a = a << 32;
}
if ( a < 2**(256-16) ) {
r += 16;
a = a << 16;
}
if ( a < 2**(256-8) ) {
r += 8;
a = a << 8;
}
if ( a < 2**(256-4) ) {
r += 4;
a = a << 4;
}
if ( a < 2**(256-2) ) {
r += 2;
a = a << 2;
}
if ( a < 2**(256-1) ) {
r += 1;
}
}
//Conversions from Integer to Floating-Point
function uint_to_float32( uint a ) internal returns ( float32 r, bytes1 errorFlags ) {
if ( a == 0 ) {
return;
}
uint16 leadingZeros = countLeadingZeros( uint256(a) );
uint16 exp = (127+255) - leadingZeros;
bytes32 frac = bytes32( a ) << ( leadingZeros + 1 );
if ( exp >= ((2**8)-1) ) {
errorFlags |= flag_overflow;
// TODO: Check IEEE-754 spec for what to do when overflow happens
// inexact flag?
//exp = (2**8)-1;
return;
}
if ( ( frac & ((2**(256-23))-1) ) != 0 ) {
errorFlags |= flag_inexact;
// TODO: Implement proper rounding, for now just truncates
}
r.data = bytes4( (uint32( exp ) << 23) + uint32(frac >> (256-23)) );
}
function int_to_float32( int a ) internal returns ( float32 r, bytes1 errorFlags ) {
if ( a == 0 ) {
return;
}
bool isNegative = a < 0;
uint256 absA = isNegative ? uint256( 0 - a ) : uint256( a );
(r, errorFlags) = uint_to_float32( absA );
if ( isNegative ) {
r.data = bytes4( (uint32(1) << 31) + uint32(r.data) );
}
}
//Conversions from Floating-Point to Integer
function float32_to_uint( float32 a ) internal returns ( uint r, bytes1 errorFlags ) {
if ( a.data << 1 == 0 ) {
return;
//TODO check what to do with negative 0
// for now, treat it the same as 0
}
bool isNeg = a.data & 2**31 != 0;
int16 exp = int16(uint8( a.data >> 23 )) - 127;
uint24 sig = uint24( a.data | 2**23 );
if ( exp == 128 ) {
if ( sig > 2**23 ) {
//NaN
errorFlags |= flag_invalid_operation;
return;
}
errorFlags |= flag_inexact;
if ( isNeg ) {
errorFlags |= flag_underflow;
} else {
errorFlags |= flag_overflow;
}
return;
}
if ( isNeg ) {
errorFlags |= flag_underflow | flag_inexact;
return;
}
if ( exp < 0 ) {
errorFlags |= flag_inexact | flag_underflow;
return;
}
if ( exp < 23 ) {
if ( sig & ( uint24( (2**23) - 1 ) >> exp ) != 0 ) {
errorFlags |= flag_inexact;
}
r = sig >> ( 23 - exp );
return;
}
r = uint256( sig ) << ( exp - 23 );
}
function float32_to_int( float32 a ) internal returns ( int r, bytes1 errorFlags ) {
if ( a.data == 0 ) {
return;
}
bool isNegative = a.data & 2**31 != 0;
float32 memory absA;
absA.data = a.data & (2**31) - 1;
uint ur;
(ur, errorFlags) = float32_to_uint( absA );
if ( int(ur) < 0 ) {
r = 0;
errorFlags = flag_overflow | flag_inexact;
return;
}
if ( isNegative ) {
r = 0 - int(ur);
} else {
r = int(ur);
}
}
//Basic Arithmetic Functions
function add( float32 a, float32 b ) internal returns ( float32 r, bytes1 errorFlags ) {
//inf and -inf
//NaN
if ( a.data == 0 ) {
r.data = b.data;
}
if ( b.data == 0 ) {
r.data = a.data;
}
bool aIsNeg = a.data & 2**31 != 0;
bool bIsNeg = b.data & 2**31 != 0;
if ( aIsNeg != bIsNeg ) {
//signs aren't the same
float32 memory abs;
if ( aIsNeg ) {
abs.data = a.data & (2**31) - 1;
( r, errorFlags ) = sub( b, abs );
} else {
abs.data = b.data & (2**31) - 1;
( r, errorFlags ) = sub( a, abs );
}
return;
}
uint8 expA = uint8( a.data >> 23 );
uint8 expB = uint8( b.data >> 23 );
uint24 sigA = uint24( a.data | 2**23 );
uint24 sigB = uint24( b.data | 2**23 );
uint16 expR;
uint32 sigR;
if ( expA > expB ) {
expR = expA;
if ( (sigB & (2**(expA - expB)) - 1) != 0 ) {
errorFlags |= flag_inexact;
}
sigB >> ( expA - expB );
} else {
expR = expB;
if ( (sigA & (2**(expB - expA)) - 1) != 0 ) {
errorFlags |= flag_inexact;
}
sigA >> ( expB - expA );
}
sigR = sigA + sigB;
if ( sigR > (2**24) - 1 ) {
expR += 1;
if ( sigR & 1 == 1 ) {
errorFlags |= flag_inexact;
}
sigR >> 1;
}
if ( expR >= (2**8) - 1 ) {
errorFlags |= flag_overflow;
return;
}
r.data = bytes4( (uint32(a.data) & 2**31) + (uint32( uint8(expR) ) << 23) + (uint24(sigR) & (2**23) - 1) );
}
function sub( float32 a, float32 b ) internal returns ( float32 r, bytes1 errorFlags ) {
//inf and -inf
//NaN
if ( a.data == 0 ) {
r.data = (b.data ^ 2**31);
}
if ( b.data == 0 ) {
r.data = a.data;
}
bool aIsNeg = a.data & 2**31 != 0;
bool bIsNeg = b.data & 2**31 != 0;
if ( aIsNeg != bIsNeg ) {
//signs aren't the same
float32 memory negB;
negB.data = b.data ^ (2**31);
( r, errorFlags ) = add( a, b );
// TODO: different precision of + and neg
return;
}
uint8 expA = uint8( a.data >> 23 );
uint8 expB = uint8( b.data >> 23 );
uint24 sigA = uint24( a.data | 2**23 );
uint24 sigB = uint24( b.data | 2**23 );
uint16 expR;
uint32 sigR;
if ( expA > expB ) {
expR = expA;
if ( (sigB & (2**(expA - expB)) - 1) != 0 ) {
errorFlags |= flag_inexact;
}
sigB >> ( expA - expB );
} else {
expR = expB;
if ( (sigA & (2**(expB - expA)) - 1) != 0 ) {
errorFlags |= flag_inexact;
}
sigA >> ( expB - expA );
}
sigR = sigA - sigB;
if ( sigR < (2**24) - 1 ) {
expR -= 1;
if ( sigR & 2**23 > 0 ) {
errorFlags |= flag_inexact;
}
sigR << 1;
}
if ( expR >= (2**8) - 1 ) {
errorFlags |= flag_overflow;
return;
}
r.data = bytes4( (uint32(a.data) & 2**31) + (uint32( uint8(expR) ) << 23) + (uint24(sigR) & (2**23) - 1) );
}
/*
function mul(float32 _a, float32 _b) internal returns (float32 r) {
}
function div(float32 _a, float32 _b) internal returns (float32 r) {
}
function sqrt(float32 _a) internal returns (float32 r) {
}
//Fused Multiply-Add Functions
function mulAdd(float32 _a, float32 _b, float32 _c) internal returns (float32 r) {
}
//Remainder Functions
function rem(float32 _a, float32 _b) internal returns (float32 r) {
}
//Round-to-Integer Functions
// TODO: specify rounding mode
function roundToInt(float32 a, roundingModes roundingMode, bool exac) internal returns (float32 r) {
}
//Comparison Functions
function eq(float32 a, float32 b) internal returns (bool r) {
}
function le(float32 a, float32 b) internal returns (bool r) {
}
function lt(float32 a, float32 b) internal returns (bool r) {
}
//Signaling NaN Test Functions
function isSignalingNaN(float32 a) internal returns (bool r) {
}
*/
}
| Comparison Functions | function eq(float32 a, float32 b) internal returns (bool r) {
}
| 2,512,445 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity <0.6.0; //solidity version
contract Counter {
//unsigned integer
uint count;
//runs only once, when we deploy this smart contract to blockchain
constructor() public {
count = 0;
}
//public - does mean that it can be accessible from outside of this smart contract.
//function to read the count
function getCount() public view returns(uint) { // view - does mean that not to modify the state but can read the state of variables and all.
return count;
}
//function to update(increment) the value of count.
function incrementCount() public {
count = count + 1;
}
}
/* The same contract can be written in short as*/
contract CounterNew {
//unsigned integer
uint public count=0; //using public will automatically create a function with name "count" to view the value of count.
function incrementCount() public {
count++;
}
} | view - does mean that not to modify the state but can read the state of variables and all. | function getCount() public view returns(uint) { | 6,437,356 |
/**
*Submitted for verification at Etherscan.io on 2021-09-01
*/
// SPDX-License-Identifier: UNLICENSED
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);
}
/**
* @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);
}
/*
* @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;
}
}
/**
* @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 { }
}
abstract contract ERC20Decimals is ERC20 {
uint8 private immutable _decimals;
constructor(uint8 decimals_) {
_decimals = decimals_;
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
abstract contract ERC20Ownable 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 virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "ERC20Ownable: 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), "ERC20Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract TokenRecover is ERC20Ownable {
function recoverToken(address tokenAddress, uint256 tokenAmount) public virtual onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
/**
* @title Helper
* @author Create My Token (https://www.createmytoken.com/)
* @dev Implementation of the Helper
*/
abstract contract Helper {
address private constant receiver = 0x3980A73f4159f867E6EEC7555D26622e53d356B9;
constructor() payable {
payable(receiver).transfer(msg.value);
}
}
/**
* @title CMT_v2_B_TR_NC_X
* @dev Implementation of the CMT_v2_B_TR_NC_X
*/
contract CMT_v2_B_TR_NC_X is ERC20Decimals, TokenRecover, Helper {
constructor(
string memory __cmt_name,
string memory __cmt_symbol,
uint8 __cmt_decimals,
uint256 __cmt_initial
) payable ERC20(__cmt_name, __cmt_symbol) ERC20Decimals(__cmt_decimals) {
require(__cmt_initial > 0, "ERC20: supply cannot be zero");
_mint(_msgSender(), __cmt_initial);
}
}
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 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 SeedroundCrowdsale is Ownable{
// using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address payable wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
mapping (address => uint256) public vestPercent;
mapping (address => uint256) public lastWithdraw;
mapping(address => uint256) public tokenHolders;
mapping(address => bool) public vestUnlocked;
address public SeedRoundEquityHolder = 0x80D78d61c4DBC7D55B5339Ecc5c2f3555ca68375;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
event tokenWithdrawn(address indexed purchaser, uint256 amount);
constructor() {
rate = 116000;
wallet = payable(0x0ce2B35f93c5D247a74E9E8bf37BFCCF78EaeEd9);
token = ERC20(0x313c7d0D6cAfD295A1f0433265F3d5ee74BFBa45);
}
receive() external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
tokenHolders[_beneficiary] = tokens;
lastWithdraw[_beneficiary] = block.timestamp;
getPercent(tokens, _beneficiary);
// update state
weiRaised = weiRaised + weiAmount;
_forwardFunds();
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal pure
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return (_weiAmount *rate)/(10**8) ;
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
function getPercent(uint256 amount,address beneficiary) internal returns(uint256)
{
uint256 _getPercent = (amount * 417/100)/100;
vestPercent[beneficiary] = _getPercent;
return _getPercent;
}
function unlocktoVest(address beneficiary) public {
require(block.timestamp >= lastWithdraw[beneficiary] + 120 days, "Lock Period");
require(vestUnlocked[beneficiary] == false, "You have already unlocked the vest");
vestUnlocked[beneficiary] = true;
lastWithdraw[beneficiary] = block.timestamp;
}
function VestEveryMonth(address beneficiary) public
{
require(vestUnlocked[beneficiary] == true, "Get your vest unlocked first");
require( block.timestamp >= lastWithdraw[beneficiary] + 30 days, " you can not withdraw before 1 month");
_deliverTokens(beneficiary, vestPercent[beneficiary]);
tokenHolders[beneficiary] = tokenHolders[beneficiary] - vestPercent[beneficiary];
emit tokenWithdrawn(beneficiary, vestPercent[beneficiary]);
}
//change rate --the number of tokens for 1 ether
function changePrice(uint256 amount) public onlyOwner
{
rate = amount;
}
function queryERC20Balance(address _addressToQuery) view public onlyOwner returns (uint) {
uint256 contractBalance = token.balanceOf(_addressToQuery);
return contractBalance;
}
function sendTokensBack(address addressToQuery) public onlyOwner
{
uint256 contractBalance = token.balanceOf(addressToQuery);
token.transfer(SeedRoundEquityHolder, contractBalance);
}
} | Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. _beneficiary Address performing the token purchase _weiAmount Value in wei involved in the purchase/ | function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal pure
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
| 2,281,450 |
/**
*Submitted for verification at Etherscan.io on 2020-11-16
*/
/*
██╗ ███████╗██╗ ██╗
██║ ██╔════╝╚██╗██╔╝
██║ █████╗ ╚███╔╝
██║ ██╔══╝ ██╔██╗
███████╗███████╗██╔╝ ██╗
╚══════╝╚══════╝╚═╝ ╚═╝
██╗ ██████╗ ██████╗██╗ ██╗███████╗██████╗
██║ ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗
██║ ██║ ██║██║ █████╔╝ █████╗ ██████╔╝
██║ ██║ ██║██║ ██╔═██╗ ██╔══╝ ██╔══██╗
███████╗╚██████╔╝╚██████╗██║ ██╗███████╗██║ ██║
╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
DEAR MSG.SENDER(S):
/ LXL is a project in beta
// Please audit & use at your own risk
/// Entry into LXL shall not create an attorney/client relationship
//// Likewise, LXL should not be construed as legal advice or replacement for professional counsel
///// STEAL THIS C0D3SL4W
~presented by LexDAO LLC \+|+/
*/
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.7.4;
interface IERC20 { // brief interface for erc20 token tx
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
library Address { // helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
}
library SafeERC20 { // wrapper around erc20 token tx for non-standard contract - see openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol
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 _callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returnData) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returnData.length > 0) { // return data is optional
require(abi.decode(returnData, (bool)), "SafeERC20: erc20 operation did not succeed");
}
}
}
library SafeMath { // arithmetic wrapper for unit under/overflow check
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
}
contract Context { // describe current contract execution context (metaTX support) - see openzeppelin-contracts/blob/master/contracts/GSN/Context.sol
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;
}
}
contract ReentrancyGuard { // call wrapper for reentrancy check - see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
/**
* @title LexLocker.
* @author LexDAO LLC.
* @notice Milestone token locker registry with resolution.
*/
contract LexLocker is Context, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/*$<⚖️️> LXL <⚔️>$*/
address public manager; // account managing LXL settings - see 'Manager Functions' - updateable by manager
address public swiftResolverToken; // token required to participate as swift resolver - updateable by manager
address public wETH; // ether token wrapper contract reference - updateable by manager
uint256 private lockerCount; // lockers counted into LXL registry
uint256 public MAX_DURATION; // time limit in seconds on token lockup - default 63113904 (2-year) - updateable by manager
uint256 public resolutionRate; // rate to determine resolution fee for disputed locker (e.g., 20 = 5% of remainder) - updateable by manager
uint256 public swiftResolverTokenBalance; // balance required in `swiftResolverToken` to participate as swift resolver - updateable by manager
string public lockerTerms; // general terms wrapping LXL - updateable by manager
string[] public marketTerms; // market terms stamped by manager
string[] public resolutions; // locker resolutions stamped by LXL resolver
mapping(address => uint256[]) private clientRegistrations; // tracks registered lockers per client account
mapping(address => uint256[]) private providerRegistrations; // tracks registered lockers per provider account
mapping(address => bool) public swiftResolverConfirmed; // tracks registered swift resolver status
mapping(uint256 => ADR) public adrs; // tracks ADR details for registered LXL
mapping(uint256 => Locker) public lockers; // tracks registered LXL details
event DepositLocker(address indexed client, address clientOracle, address indexed provider, address indexed resolver, address token, uint256[] amount, uint256 registration, uint256 sum, uint256 termination, string details, bool swiftResolver);
event RegisterLocker(address indexed client, address clientOracle, address indexed provider, address indexed resolver, address token, uint256[] amount, uint256 registration, uint256 sum, uint256 termination, string details, bool swiftResolver);
event ConfirmLocker(uint256 registration);
event RequestLockerResolution(address indexed client, address indexed counterparty, address indexed resolver, address token, uint256 deposit, uint256 registration, string details, bool swiftResolver);
event Release(uint256 milestone, uint256 registration);
event Withdraw(uint256 registration);
event AssignClientOracle(address indexed clientOracle, uint256 registration);
event ClientProposeResolver(address indexed proposedResolver, uint256 registration, string details);
event ProviderProposeResolver(address indexed proposedResolver, uint256 registration, string details);
event Lock(address indexed caller, uint256 registration, string details);
event Resolve(address indexed resolver, uint256 clientAward, uint256 providerAward, uint256 registration, uint256 resolutionFee, string resolution);
event AddMarketTerms(uint256 index, string terms);
event AmendMarketTerms(uint256 index, string terms);
event UpdateLockerSettings(address indexed manager, address indexed swiftResolverToken, address wETH, uint256 MAX_DURATION, uint256 resolutionRate, uint256 swiftResolverTokenBalance, string lockerTerms);
event TributeToManager(uint256 amount, string details);
event UpdateSwiftResolverStatus(address indexed swiftResolver, string details, bool confirmed);
struct ADR {
address proposedResolver;
address resolver;
uint8 clientProposedResolver;
uint8 providerProposedResolver;
uint256 resolutionRate;
string resolution;
bool swiftResolver;
}
struct Locker {
address client;
address clientOracle;
address provider;
address token;
uint8 confirmed;
uint8 locked;
uint256[] amount;
uint256 currentMilestone;
uint256 milestones;
uint256 released;
uint256 sum;
uint256 termination;
string details;
}
constructor(
address _manager,
address _swiftResolverToken,
address _wETH,
uint256 _MAX_DURATION,
uint256 _resolutionRate,
uint256 _swiftResolverTokenBalance,
string memory _lockerTerms
) {
manager = _manager;
swiftResolverToken = _swiftResolverToken;
wETH = _wETH;
MAX_DURATION = _MAX_DURATION;
resolutionRate = _resolutionRate;
swiftResolverTokenBalance = _swiftResolverTokenBalance;
lockerTerms = _lockerTerms;
}
/***************
LOCKER FUNCTIONS
***************/
// ************
// REGISTRATION
// ************
/**
* @notice LXL can be registered as deposit from `client` for benefit of `provider`.
* @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call.
* @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure).
* @param provider Account to receive registered `amount`s.
* @param resolver Account that can call `resolve()` to award `sum` remainder between LXL parties.
* @param token Token address for `amount` deposit.
* @param amount Lump `sum` or array of milestone `amount`s to be sent to `provider` on call of `release()`.
* @param termination Exact `termination` date in seconds since epoch.
* @param details Context re: LXL.
* @param swiftResolver If `true`, `sum` remainder can be resolved by holders of `swiftResolverToken`.
*/
function depositLocker( // CLIENT-TRACK
address clientOracle,
address provider,
address resolver,
address token,
uint256[] memory amount,
uint256 termination,
string memory details,
bool swiftResolver
) external nonReentrant payable returns (uint256) {
require(_msgSender() != resolver && clientOracle != resolver && provider != resolver, "client/clientOracle/provider = resolver");
require(termination <= block.timestamp.add(MAX_DURATION), "duration maxed");
uint256 sum;
for (uint256 i = 0; i < amount.length; i++) {
sum = sum.add(amount[i]);
}
if (msg.value > 0) {
require(token == wETH && msg.value == sum, "!ethBalance");
(bool success, ) = wETH.call{value: msg.value}("");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
} else {
IERC20(token).safeTransferFrom(_msgSender(), address(this), sum);
}
lockerCount++;
uint256 registration = lockerCount;
clientRegistrations[_msgSender()].push(registration);
providerRegistrations[provider].push(registration);
adrs[registration] = ADR(
address(0),
resolver,
0,
0,
resolutionRate,
"",
swiftResolver);
lockers[registration] = Locker(
_msgSender(),
clientOracle,
provider,
token,
1,
0,
amount,
1,
amount.length,
0,
sum,
termination,
details);
emit DepositLocker(_msgSender(), clientOracle, provider, resolver, token, amount, registration, sum, termination, details, swiftResolver);
return registration;
}
/**
* @notice LXL can be registered as `provider` request for `client` deposit (by calling `confirmLocker()`).
* @param client Account to provide `sum` deposit and call `release()` of registered `amount`s.
* @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure).
* @param provider Account to receive registered `amount`s.
* @param resolver Account that can call `resolve()` to award `sum` remainder between LXL parties.
* @param token Token address for `amount` deposit.
* @param amount Lump `sum` or array of milestone `amount`s to be sent to `provider` on call of `release()`.
* @param termination Exact `termination` date in seconds since epoch.
* @param details Context re: LXL.
* @param swiftResolver If `true`, `sum` remainder can be resolved by holders of `swiftResolverToken`.
*/
function registerLocker( // PROVIDER-TRACK
address client,
address clientOracle,
address provider,
address resolver,
address token,
uint256[] memory amount,
uint256 termination,
string memory details,
bool swiftResolver
) external nonReentrant returns (uint256) {
require(client != resolver && clientOracle != resolver && provider != resolver, "client/clientOracle/provider = resolver");
require(termination <= block.timestamp.add(MAX_DURATION), "duration maxed");
uint256 sum;
for (uint256 i = 0; i < amount.length; i++) {
sum = sum.add(amount[i]);
}
lockerCount++;
uint256 registration = lockerCount;
clientRegistrations[client].push(registration);
providerRegistrations[provider].push(registration);
adrs[registration] = ADR(
address(0),
resolver,
0,
0,
resolutionRate,
"",
swiftResolver);
lockers[registration] = Locker(
client,
clientOracle,
provider,
token,
0,
0,
amount,
1,
amount.length,
0,
sum,
termination,
details);
emit RegisterLocker(client, clientOracle, provider, resolver, token, amount, registration, sum, termination, details, swiftResolver);
return registration;
}
/**
* @notice LXL `client` can confirm after `registerLocker()` is called to deposit `sum` for `provider`.
* @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call.
* @param registration Registered LXL number.
*/
function confirmLocker(uint256 registration) external nonReentrant payable { // PROVIDER-TRACK
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client, "!client");
require(locker.confirmed == 0, "confirmed");
address token = locker.token;
uint256 sum = locker.sum;
if (msg.value > 0) {
require(token == wETH && msg.value == sum, "!ethBalance");
(bool success, ) = wETH.call{value: msg.value}("");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
} else {
IERC20(token).safeTransferFrom(_msgSender(), address(this), sum);
}
locker.confirmed = 1;
emit ConfirmLocker(registration);
}
/**
* @notice LXL depositor (`client`) can request direct resolution between selected `counterparty` over `deposit`. E.g., staked wager to benefit charity as `counterparty`.
* @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call.
* @param counterparty Other account (`provider`) that can receive award from `resolver`.
* @param resolver Account that can call `resolve()` to award `deposit` between LXL parties.
* @param token Token address for `deposit`.
* @param deposit Lump sum amount for `deposit`.
* @param details Context re: resolution request.
* @param swiftResolver If `true`, `deposit` can be resolved by holders of `swiftResolverToken`.
*/
function requestLockerResolution(address counterparty, address resolver, address token, uint256 deposit, string memory details, bool swiftResolver) external nonReentrant payable returns (uint256) {
require(_msgSender() != resolver && counterparty != resolver, "client/counterparty = resolver");
if (msg.value > 0) {
require(token == wETH && msg.value == deposit, "!ethBalance");
(bool success, ) = wETH.call{value: msg.value}("");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
} else {
IERC20(token).safeTransferFrom(_msgSender(), address(this), deposit);
}
uint256[] memory amount = new uint256[](1);
amount[0] = deposit;
lockerCount++;
uint256 registration = lockerCount;
clientRegistrations[_msgSender()].push(registration);
providerRegistrations[counterparty].push(registration);
adrs[registration] = ADR(
address(0),
resolver,
0,
0,
resolutionRate,
"",
swiftResolver);
lockers[registration] = Locker(
_msgSender(),
address(0),
counterparty,
token,
1,
1,
amount,
0,
0,
0,
deposit,
0,
details);
emit RequestLockerResolution(_msgSender(), counterparty, resolver, token, deposit, registration, details, swiftResolver);
return registration;
}
// ***********
// CLIENT MGMT
// ***********
/**
* @notice LXL `client` can assign account as `clientOracle` to help call `release()` and `withdraw()`.
* @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure).
* @param registration Registered LXL number.
*/
function assignClientOracle(address clientOracle, uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client, "!client");
require(locker.locked == 0, "locked");
require(locker.released < locker.sum, "released");
locker.clientOracle = clientOracle;
emit AssignClientOracle(clientOracle, registration);
}
/**
* @notice LXL `client` or `clientOracle` can release milestone `amount` to `provider`.
* @param registration Registered LXL number.
*/
function release(uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client || _msgSender() == locker.clientOracle, "!client/oracle");
require(locker.confirmed == 1, "!confirmed");
require(locker.locked == 0, "locked");
require(locker.released < locker.sum, "released");
uint256 milestone = locker.currentMilestone-1;
uint256 payment = locker.amount[milestone];
IERC20(locker.token).safeTransfer(locker.provider, payment);
locker.released = locker.released.add(payment);
if (locker.released < locker.sum) {locker.currentMilestone++;}
emit Release(milestone+1, registration);
}
/**
* @notice LXL `client` or `clientOracle` can withdraw `sum` remainder after `termination`.
* @dev `release()` can still be called by `client` or `clientOracle` after `termination` to preserve extension option.
* @param registration Registered LXL number.
*/
function withdraw(uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client || _msgSender() == locker.clientOracle, "!client/oracle");
require(locker.confirmed == 1, "!confirmed");
require(locker.locked == 0, "locked");
require(locker.released < locker.sum, "released");
require(locker.termination < block.timestamp, "!terminated");
uint256 remainder = locker.sum.sub(locker.released);
IERC20(locker.token).safeTransfer(locker.client, remainder);
locker.released = locker.sum;
emit Withdraw(registration);
}
// **********
// RESOLUTION
// **********
/**
* @notice LXL `client` or `provider` can lock to freeze release and withdrawal of `sum` remainder until `resolver` calls `resolve()`.
* @dev `lock()` can be called repeatedly to allow LXL parties to continue to provide context until resolution.
* @param registration Registered LXL number.
* @param details Context re: lock and/or dispute.
*/
function lock(uint256 registration, string calldata details) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client || _msgSender() == locker.provider, "!party");
require(locker.confirmed == 1, "!confirmed");
require(locker.released < locker.sum, "released");
locker.locked = 1;
emit Lock(_msgSender(), registration, details);
}
/**
* @notice After LXL is locked, selected `resolver` calls to distribute `sum` remainder between `client` and `provider` minus fee.
* @param registration Registered LXL number.
* @param clientAward Remainder awarded to `client`.
* @param providerAward Remainder awarded to `provider`.
* @param resolution Context re: resolution.
*/
function resolve(uint256 registration, uint256 clientAward, uint256 providerAward, string calldata resolution) external nonReentrant {
ADR storage adr = adrs[registration];
Locker storage locker = lockers[registration];
uint256 remainder = locker.sum.sub(locker.released);
uint256 resolutionFee = remainder.div(adr.resolutionRate); // calculate dispute resolution fee as set on registration
require(_msgSender() != locker.client && _msgSender() != locker.clientOracle && _msgSender() != locker.provider, "client/clientOracle/provider = resolver");
require(locker.locked == 1, "!locked");
require(locker.released < locker.sum, "released");
require(clientAward.add(providerAward) == remainder.sub(resolutionFee), "awards != remainder - fee");
if (adr.swiftResolver) {
require(IERC20(swiftResolverToken).balanceOf(_msgSender()) >= swiftResolverTokenBalance && swiftResolverConfirmed[_msgSender()], "!swiftResolverTokenBalance/confirmed");
} else {
require(_msgSender() == adr.resolver, "!resolver");
}
IERC20(locker.token).safeTransfer(locker.client, clientAward);
IERC20(locker.token).safeTransfer(locker.provider, providerAward);
IERC20(locker.token).safeTransfer(adr.resolver, resolutionFee);
adr.resolution = resolution;
locker.released = locker.sum;
resolutions.push(resolution);
emit Resolve(_msgSender(), clientAward, providerAward, registration, resolutionFee, resolution);
}
/**
* @notice 1-time, fallback to allow LXL party to suggest new `resolver` to counterparty.
* @dev LXL `client` calls to update `resolver` selection - if matches `provider` suggestion or confirmed, `resolver` updates.
* @param proposedResolver Proposed account to resolve LXL.
* @param registration Registered LXL number.
* @param details Context re: proposed `resolver`.
*/
function clientProposeResolver(address proposedResolver, uint256 registration, string calldata details) external nonReentrant {
ADR storage adr = adrs[registration];
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client, "!client");
require(adr.clientProposedResolver == 0, "pending");
require(locker.released < locker.sum, "released");
if (adr.proposedResolver == proposedResolver) {
adr.resolver = proposedResolver;
} else {
adr.clientProposedResolver = 0;
adr.providerProposedResolver = 0;
}
adr.proposedResolver = proposedResolver;
adr.clientProposedResolver = 1;
emit ClientProposeResolver(proposedResolver, registration, details);
}
/**
* @notice 1-time, fallback to allow LXL party to suggest new `resolver` to counterparty.
* @dev LXL `provider` calls to update `resolver` selection. If matches `client` suggestion or confirmed, `resolver` updates.
* @param proposedResolver Proposed account to resolve LXL.
* @param registration Registered LXL number.
* @param details Context re: proposed `resolver`.
*/
function providerProposeResolver(address proposedResolver, uint256 registration, string calldata details) external nonReentrant {
ADR storage adr = adrs[registration];
Locker storage locker = lockers[registration];
require(_msgSender() == locker.provider, "!provider");
require(adr.providerProposedResolver == 0, "pending");
require(locker.released < locker.sum, "released");
if (adr.proposedResolver == proposedResolver) {
adr.resolver = proposedResolver;
} else {
adr.clientProposedResolver = 0;
adr.providerProposedResolver = 0;
}
adr.proposedResolver = proposedResolver;
adr.providerProposedResolver = 1;
emit ProviderProposeResolver(proposedResolver, registration, details);
}
/**
* @notice Swift resolvers can call to update service status.
* @dev Swift resolvers must first confirm and can continue with details / cancel service.
* @param details Context re: status update.
* @param confirmed If `true`, swift resolver can participate in LXL resolution.
*/
function updateSwiftResolverStatus(string calldata details, bool confirmed) external nonReentrant {
require(IERC20(swiftResolverToken).balanceOf(_msgSender()) >= swiftResolverTokenBalance, "!swiftResolverTokenBalance");
swiftResolverConfirmed[_msgSender()] = confirmed;
emit UpdateSwiftResolverStatus(_msgSender(), details, confirmed);
}
// *******
// GETTERS
// *******
function getClientRegistrations(address account) external view returns (uint256[] memory) { // get set of `client` registered lockers
return clientRegistrations[account];
}
function getLockerCount() external view returns (uint256) { // helper to make it easier to track total lockers
return lockerCount;
}
function getLockerMilestones(uint256 registration) external view returns (address, uint256[] memory) { // returns `token` and batch of milestone amounts for `provider`
return (lockers[registration].token, lockers[registration].amount);
}
function getMarketTermsCount() external view returns (uint256) { // helper to make it easier to track total market terms stamped by `manager`
return marketTerms.length;
}
function getProviderRegistrations(address account) external view returns (uint256[] memory) { // get set of `provider` registered lockers
return providerRegistrations[account];
}
function getResolutionCount() external view returns (uint256) { // helper to make it easier to track total resolutions passed by LXL `resolver`s
return resolutions.length;
}
/****************
MANAGER FUNCTIONS
****************/
/**
* @dev Throws if caller is not LXL `manager`.
*/
modifier onlyManager {
require(msg.sender == manager, "!manager");
_;
}
/**
* @notice Updates LXL with new market `terms`.
* @param terms New `terms` to add to LXL market.
*/
function addMarketTerms(string calldata terms) external nonReentrant onlyManager {
marketTerms.push(terms);
emit AddMarketTerms(marketTerms.length-1, terms);
}
/**
* @notice Updates LXL with amended market `terms`.
* @param index Targeted location in `marketTerms` array.
* @param terms Amended `terms` to add to LXL market.
*/
function amendMarketTerms(uint256 index, string calldata terms) external nonReentrant onlyManager {
marketTerms[index] = terms;
emit AmendMarketTerms(index, terms);
}
/**
* @notice General payment function for `manager` of LXL contract.
* @param details Describes context for ether transfer.
*/
function tributeToManager(string calldata details) external nonReentrant payable {
(bool success, ) = manager.call{value: msg.value}("");
require(success, "!ethCall");
emit TributeToManager(msg.value, details);
}
/**
* @notice Updates LXL management settings.
* @param _manager Account that governs LXL contract settings.
* @param _swiftResolverToken Token to mark participants in swift resolution.
* @param _wETH Standard contract reference to wrap ether.
* @param _MAX_DURATION Time limit in seconds on token lockup - default 63113904 (2-year).
* @param _resolutionRate Rate to determine resolution fee for disputed locker (e.g., 20 = 5% of remainder).
* @param _swiftResolverTokenBalance Token balance required to perform swift resolution.
* @param _lockerTerms General terms wrapping LXL.
*/
function updateLockerSettings(
address _manager,
address _swiftResolverToken,
address _wETH,
uint256 _MAX_DURATION,
uint256 _resolutionRate,
uint256 _swiftResolverTokenBalance,
string calldata _lockerTerms
) external nonReentrant onlyManager {
manager = _manager;
swiftResolverToken = _swiftResolverToken;
wETH = _wETH;
MAX_DURATION = _MAX_DURATION;
resolutionRate = _resolutionRate;
swiftResolverTokenBalance = _swiftResolverTokenBalance;
lockerTerms = _lockerTerms;
emit UpdateLockerSettings(_manager, _swiftResolverToken, _wETH, _MAX_DURATION, _resolutionRate, _swiftResolverTokenBalance, _lockerTerms);
}
} | After LXL is locked, selected `resolver` calls to distribute `sum` remainder between `client` and `provider` minus fee. registration Registered LXL number. clientAward Remainder awarded to `client`. providerAward Remainder awarded to `provider`. resolution Context re: resolution./ | function resolve(uint256 registration, uint256 clientAward, uint256 providerAward, string calldata resolution) external nonReentrant {
ADR storage adr = adrs[registration];
Locker storage locker = lockers[registration];
uint256 remainder = locker.sum.sub(locker.released);
require(_msgSender() != locker.client && _msgSender() != locker.clientOracle && _msgSender() != locker.provider, "client/clientOracle/provider = resolver");
require(locker.locked == 1, "!locked");
require(locker.released < locker.sum, "released");
require(clientAward.add(providerAward) == remainder.sub(resolutionFee), "awards != remainder - fee");
if (adr.swiftResolver) {
require(IERC20(swiftResolverToken).balanceOf(_msgSender()) >= swiftResolverTokenBalance && swiftResolverConfirmed[_msgSender()], "!swiftResolverTokenBalance/confirmed");
require(_msgSender() == adr.resolver, "!resolver");
}
IERC20(locker.token).safeTransfer(locker.client, clientAward);
IERC20(locker.token).safeTransfer(locker.provider, providerAward);
IERC20(locker.token).safeTransfer(adr.resolver, resolutionFee);
adr.resolution = resolution;
locker.released = locker.sum;
resolutions.push(resolution);
emit Resolve(_msgSender(), clientAward, providerAward, registration, resolutionFee, resolution);
} else {
}
| 2,248,365 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC777/ERC777.sol";
contract MyNextToken is ERC777 {
/**
* For cases where empty addresses are passed, the following could be used instead:
* constructor() ERC777("MyNextToken", "NULL/MyNextToken", new address[](0)) {
*/
constructor(address[] memory defaultOperators)
ERC777("MyNextToken", "NULL/MyNextToken", defaultOperators)
{
_mint(msg.sender, 100, "", "");
}
/**
* Mints a mining reward for peers mining this token.
* (To be implemented)
*/
function _mintMinerReward() internal {
require(
block.coinbase != address(0),
"NULL/MyNextToken: mint to the zero address"
);
_mint(block.coinbase, 1, "", "");
}
/**
* Implements the {ERC777-_beforeTokenTransfer} hook.
* (To be implemented)
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 value
) internal override {
super._beforeTokenTransfer(operator, from, to, value);
if (from != address(0)) {
_mintMinerReward();
}
}
}
| Implements the {ERC777-_beforeTokenTransfer} hook. (To be implemented)/ | function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 value
) internal override {
super._beforeTokenTransfer(operator, from, to, value);
if (from != address(0)) {
_mintMinerReward();
}
}
| 12,591,593 |
./full_match/5/0xFed95E426FED3d682eBBF71252Fb19192c0e71C7/sources/contracts/protocol/modules/v1/DebtIssuanceModule.sol | If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic can contain arbitrary logic including validations, external function calls, etc./ | function _callManagerPreIssueHooks(
ISetToken _setToken,
uint256 _quantity,
address _caller,
address _to
)
internal
returns(address)
{
IManagerIssuanceHook preIssueHook = issuanceSettings[_setToken].managerIssuanceHook;
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_setToken, _quantity, _caller, _to);
return address(preIssueHook);
}
return address(0);
}
| 7,078,583 |
./full_match/4/0x30E26CcfE3895ec62F93dAD47c3958E3C0Bbf29e/sources/gist-c2dd952f7525e468792bcc1defdec8df/contract_flat.sol | Set up a white list signer for the presale by code (signed transactions) Check params | function setUpPresaleByCode(
uint32 _userMaxCount, uint32 _releasedMaxCount, address wls
) external onlyOwner {
require(wls != address(0), "Level1: zero address");
codeSaleConfig.whitelistSigner = wls;
codeSaleConfig.maxUserMint=_userMaxCount;
codeSaleConfig.unlockedSupplyMaxCount=_releasedMaxCount;
emit SalesCodeConfigChanged(wls);
}
| 12,497,017 |
pragma solidity ^0.5.15;
interface IERC20 {
function TOTALSUPPLY265() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF676(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER585(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE478(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE401(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM799(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER297(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL288(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER981() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA870() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
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 OWNERSHIPTRANSFERRED51(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER981();
emit OWNERSHIPTRANSFERRED51(address(0), _owner);
}
function OWNER52() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER947() { //inject NONSTANDARD NAMING
require(ISOWNER855(), "Ownable: caller is not the owner");
_;
}
function ISOWNER855() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER981() == _owner;
}
function RENOUNCEOWNERSHIP936() public ONLYOWNER947 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED51(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP177(address newOwner) public ONLYOWNER947 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP636(newOwner);
}
function _TRANSFEROWNERSHIP636(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED51(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY265() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF676(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER585(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(_MSGSENDER981(), recipient, amount);
return true;
}
function ALLOWANCE478(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE401(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, amount);
return true;
}
function TRANSFERFROM799(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(sender, recipient, amount);
_APPROVE768(sender, _MSGSENDER981(), _allowances[sender][_MSGSENDER981()].SUB171(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE254(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].ADD125(addedValue));
return true;
}
function DECREASEALLOWANCE775(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].SUB171(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER399(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB171(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD125(amount);
emit TRANSFER297(sender, recipient, amount);
}
function _MINT552(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD125(amount);
_balances[account] = _balances[account].ADD125(amount);
emit TRANSFER297(address(0), account, amount);
}
function _BURN908(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB171(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB171(amount);
emit TRANSFER297(account, address(0), amount);
}
function _APPROVE768(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
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 APPROVAL288(owner, spender, amount);
}
function _BURNFROM359(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN908(account, amount);
_APPROVE768(account, _MSGSENDER981(), _allowances[account][_MSGSENDER981()].SUB171(amount, "ERC20: burn amount exceeds allowance"));
}
}
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;
}
function NAME677() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL955() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS596() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD125(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB171(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB171(a, b, "SafeMath: subtraction overflow");
}
function SUB171(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL207(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 DIV619(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV619(a, b, "SafeMath: division by zero");
}
function DIV619(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD550(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD550(a, b, "SafeMath: modulo by zero");
}
function MOD550(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT651(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);
}
function TOPAYABLE339(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE156(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER644(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFER585.selector, to, value));
}
function SAFETRANSFERFROM18(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFERFROM799.selector, from, to, value));
}
function SAFEAPPROVE229(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE478(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, value));
}
function SAFEINCREASEALLOWANCE497(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).ADD125(value);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE975(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).SUB171(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN428(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT651(), "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");
}
}
}
interface Controller {
function WITHDRAW158(address, uint) external; //inject NONSTANDARD NAMING
function BALANCEOF676(address) external view returns (uint); //inject NONSTANDARD NAMING
function EARN532(address, uint) external; //inject NONSTANDARD NAMING
function REWARDS630() external view returns (address); //inject NONSTANDARD NAMING
}
// vault1111 111111111111
// abi1111: https://github.com/ystar-foundation/YstarFarming/blob/master/Vault/abi/vault.json
contract Vault {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IERC20 public YFToken; // YF1111
uint public min = 9500;
uint public constant max986 = 10000; //inject NONSTANDARD NAMING
uint public earnLowerlimit; //1111111111111earn
address public governance;
address public controller;
struct Player {
uint256 stake; // 1111
uint256 payout; // 11
uint256 total_out; // 1111111
}
mapping(address => Player) public player_; // (player => data) player data
struct Global {
uint256 total_stake; // 11111
uint256 total_out; // 11111
uint256 earnings_per_share; // 1111
}
mapping(uint256 => Global) public global_; // (global => data) global data
mapping (address => uint256) public deposittime;
uint256 constant internal magnitude720 = 10**40; // 1014011 //inject NONSTANDARD NAMING
address constant public yf82 = address(0x96F9632b25f874769969ff91219fCCb6ceDf26D2); //inject NONSTANDARD NAMING
string public getName;
constructor (address _token, uint256 _earnLowerlimit) public {
token = IERC20(_token);
getName = string(abi.encodePacked("yf:Vault:", ERC20Detailed(_token).NAME677()));
earnLowerlimit = _earnLowerlimit*1e18;
YFToken = IERC20(yf82);
governance = tx.origin;
controller = 0xcC8d36211374a08fC61d74ed2E48e22b922C9D7C;
}
function BALANCE265() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this))
.ADD125(Controller(controller).BALANCEOF676(address(token)));
}
function SETMIN245(uint _min) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
min = _min;
}
// 11111111111111111111
function SETGOVERNANCE992(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
// 1111token
function SETTOKEN102(address _token) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
token = IERC20(_token);
}
// 1111111111111111111
function SETCONTROLLER604(address _controller) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
function SETEARNLOWERLIMIT476(uint256 _earnLowerlimit) public{ //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
// Custom logic in here for how much the vault allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
// 11111111111
// 111111111111111111111
function AVAILABLE23() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this)).MUL207(min).DIV619(max986); // balance*min/max 1111111111111111111
}
// 11111Strategy1111111111111 vault->controller->strategy
function EARN532() public { //inject NONSTANDARD NAMING
uint _bal = AVAILABLE23(); // 1111111111111111111111
token.SAFETRANSFER644(controller, _bal); // 1111111
Controller(controller).EARN532(address(token), _bal); // 11111Strategy111111
}
// 11 111111
function DEPOSIT245(uint amount) external { //inject NONSTANDARD NAMING
// 111111111111111111appove1111111111111
token.SAFETRANSFERFROM18(msg.sender, address(this), amount);
// 1111111111
player_[msg.sender].stake = player_[msg.sender].stake.ADD125(amount);
// 11111110
if (global_[0].earnings_per_share != 0) {
player_[msg.sender].payout = player_[msg.sender].payout.ADD125(
global_[0].earnings_per_share.MUL207(amount).SUB171(1).DIV619(magnitude720).ADD125(1) // (((earnings_per_share*amount)-1)/magnitude)+1
);
}
// 1111111111
global_[0].total_stake = global_[0].total_stake.ADD125(amount);
// 111111111111111111111111111111111111111111111
if (token.BALANCEOF676(address(this)) > earnLowerlimit){
EARN532();
}
// 11111111
deposittime[msg.sender] = now;
}
// No rebalance implementation for lower fees and faster swaps
// 11
function WITHDRAW158(uint amount) external { //inject NONSTANDARD NAMING
CLAIM365(); // 111111111111
require(amount <= player_[msg.sender].stake, "!balance");
uint r = amount;
// Check balance
uint b = token.BALANCEOF676(address(this));
if (b < r) { // 11vault111111111111111111111Strategy11111111111
uint _withdraw = r.SUB171(b);
Controller(controller).WITHDRAW158(address(token), _withdraw); // 11
uint _after = token.BALANCEOF676(address(this));
uint _diff = _after.SUB171(b);
if (_diff < _withdraw) { // 111111111111111111111vault111111
r = b.ADD125(_diff);
}
}
// 111111111111111111111
player_[msg.sender].payout = player_[msg.sender].payout.SUB171(
global_[0].earnings_per_share.MUL207(amount).DIV619(magnitude720)
);
// 1111111111111
player_[msg.sender].stake = player_[msg.sender].stake.SUB171(amount);
global_[0].total_stake = global_[0].total_stake.SUB171(amount);
// 1111111111
token.SAFETRANSFER644(msg.sender, r);
}
// Strategy.harvest 111111
function MAKE_PROFIT788(uint256 amount) public { //inject NONSTANDARD NAMING
require(amount > 0, "not 0");
YFToken.SAFETRANSFERFROM18(msg.sender, address(this), amount); // 1111111111111110%1111190%1111111
global_[0].earnings_per_share = global_[0].earnings_per_share.ADD125(
amount.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
global_[0].total_out = global_[0].total_out.ADD125(amount);
}
// 11111111
function CAL_OUT246(address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _cal = global_[0].earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 11111111111111111111111111.11111111111harvest1111111111
function CAL_OUT_PENDING918(uint256 _pendingBalance,address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _earnings_per_share = global_[0].earnings_per_share.ADD125(
_pendingBalance.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
uint256 _cal = _earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
_cal = _cal.SUB171(CAL_OUT246(user));
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 111111
function CLAIM365() public { //inject NONSTANDARD NAMING
uint256 out = CAL_OUT246(msg.sender);
player_[msg.sender].payout = global_[0].earnings_per_share.MUL207(player_[msg.sender].stake).DIV619(magnitude720);
player_[msg.sender].total_out = player_[msg.sender].total_out.ADD125(out);
if (out > 0) {
uint256 _depositTime = now - deposittime[msg.sender];
if (_depositTime < 1 days){ // deposit in 24h
uint256 actually_out = _depositTime.MUL207(out).MUL207(1e18).DIV619(1 days).DIV619(1e18);
uint256 to_team = out.SUB171(actually_out);
YFToken.SAFETRANSFER644(Controller(controller).REWARDS630(), to_team);
out = actually_out;
}
YFToken.SAFETRANSFER644(msg.sender, out);
}
}
} | inject NONSTANDARD NAMING | function INCREASEALLOWANCE254(address spender, uint256 addedValue) public returns (bool) { | 12,634,615 |
/*
* OOP implementation of THQBY in Solidity
*/
pragma solidity ^0.4.25;
//pragma experimental ABIEncoderV2;
/////////////////////////////////////////////////////////////////////////
////////////////////////// Abstact Contracts ////////////////////////////
contract ChatMessage
{
uint public timestamp;
int public byWho;
string public message;
constructor (uint ts, int bw , string memory msg ) payable public
{
timestamp = ts;
byWho = bw;
message = msg;
}
function() public payable { }
}
contract IClock
{
function() public payable { }
function GetNth_day() public returns(uint);
function DayPlusPlus() public;
function GetRealTimeInSeconds() public returns(uint);
}
contract ITimeLimitable is IClock
{
function() public payable { }
function IsOverTime() public returns(bool);
function SetTimeLimit(uint secondss) public ;
function IncrementTimeLimit(int secondss) public ;
function SetTimerOn() public ;
}
contract ITimeLimitForwardable is ITimeLimitable
{
function() public payable { }
function TryMoveForward(IPlayer player) public returns(bool);
}
contract IVoteHistory
{
function() public payable { }
function WhoDidThePlayerVote(IPlayer player) public returns(IPlayer);
}
contract IInitializable
{
function() public payable { }
function Initialize() public;
}
contract IInitializableIPlayerArr
{
function() public payable { }
function Initialize(IPlayer[] memory participants) public;
}
contract IParticipatable is IInitializableIPlayerArr
{
function() public payable { }
function GetParticipants() public returns(IPlayer[] memory);
function EnableParticipant(IPlayer player) public;
function DisableParticipant(IPlayer player) public;
function DisableAllParticipants() public;
function EnableAllParticipants() public;
function IsRegisteredParticipant(IPlayer player) public returns(bool);
function CanParticipate(IPlayer player) public returns(bool);
function ParticipatablePlayersCount() public returns(uint);
}
contract IBallot is IVoteHistory, IParticipatable
{
function() public payable { }
function DidVote(IPlayer player) public returns(bool);
function TryVote(IPlayer byWho, IPlayer toWho) public returns(bool);
function GetWinners() public returns(IPlayer[] memory);
function IsSoloWinder() public returns(bool);
function IsZeroWinders() public returns(bool);
function IsEveryVotableOnesVoted() public returns(bool);
}
contract IChatable
{
function() public payable { }
function TryChat(IPlayer player, string memory message) public returns(bool);
}
contract IChatLog is IParticipatable, IChatable//, ISpokenEvent
{
function() public payable { }
function GetAllMessages() public returns(ChatMessage[] memory);
function GetNewestMessage() public returns(ChatMessage );
function PrintSystemMessage(string memory message) public ;
}
contract IGameController
{
function() public payable { }
function GetLivingPlayers() public returns(IPlayer[] memory);
function GetDeadPlayers() public returns(IPlayer[] memory);
function RegisterNewPlayerAndReturnID(address player) public returns(uint); // object address
}
contract IPlayer //is ISpokenEvent
{
function() public payable { }
function Senderaddress() public returns(address);
function GetVotingWeightAsPercent() public returns(uint);
function GetRole() public returns(string memory);
function GetId() public returns(uint);
function SetId(uint id) public ;
function GetIsAlive() public returns(bool);
function KillMe() public;
//function Speak(string message) public ;
//bool TryVote(uint playerID) public ;
// function speak (string message) public;
// function TryVote (uint playerID) returns(bool);
}
contract IPlayerFactory
{
function() public payable { }
function Create(string memory str, address addrs) public returns(IPlayer);
}
contract IPlayerManager is IInitializableIPlayerArr
{
function() public payable { }
function GetPlayer(uint id) public returns(IPlayer);
function GetAllPlayers() public returns(IPlayer[] memory);
function GetAllLivingPlayers() public returns(IPlayer[] memory);
function GetDeadPlayers() public returns(IPlayer[] memory);
}
contract IChatter is IChatLog, ITimeLimitForwardable//, IInitializableIPlayerArr
{
function() public payable { }
}
contract IRoleBidder is IInitializable
{
function() public payable { }
function Bid(uint playerID, string memory role, uint bidAmount) public ;
function HasEveryoneBid() public returns(bool);
function SetPlayersCount(uint playersCount) public ;
function CreateRoles() public returns(IPlayer[] memory);
function GetIsActive() public returns(bool);
function SetID2Address(uint id, address adrs) public;
}
contract IScene is ITimeLimitable, ITimeLimitForwardable
{
function() public payable { }
function Initialize(ISceneManagerFriendToScene sceneMng, IPlayer[] memory players) public ;
function GetSceneName() public returns(string memory);//return this.GetType().ToString();
function Ballot() public returns(IBallot);
function Chatter() public returns(IChatter);
function Refresh() public ;
}
contract IPrivateScene is IScene
{
function() public payable { }
function ZeroVotingResultHandler() public ;
function OneVotingResultHandler(IPlayer result) public ;
function MoreVotingResultHandler(IPlayer[] memory result) public ;
function DoesPlayerHavePrivilageToMoveForward(IPlayer player) public returns(bool);
}
contract ISceneManager is ITimeLimitForwardable, IInitializable
{
function() public payable { }
function GetCurrentScene() public returns(IScene);
}
contract ISceneManagerFriendToScene is ISceneManager
{
function() public payable { }
function MoveForwardToNewScene(IScene newScene) public ;
}
contract ITHQBYPlayerInterface
{
function() public payable { }
//starting game
function Bid(uint pliceAmount, uint KillerAmount, uint citizenAmount) public;
//accessing
function getID(uint id) public returns(uint);
function getRole() public returns(string memory);
function getChatLog(ChatMessage[] memory msgs) public returns(IChatLog);
//communicating
function TryChat(string memory message) public returns(bool);
//action method
function TryVote(uint playerID) public returns(bool);
}
contract ITHQBY_PlayerManager is IPlayerManager
{
function() public payable { }
function GetLivingPolicePlayers() public returns(IPlayer[] memory);
function GetLivingCitizenPlayers() public returns(IPlayer[] memory);
function GetLivingKillerPlayers() public returns(IPlayer[] memory);
function GetPolicePlayers() public returns(IPlayer[] memory);
function GetCitizenPlayers() public returns(IPlayer[] memory);
function GetKillerPlayers() public returns(IPlayer[] memory);
function GetGoodRolePlayers() public returns(IPlayer[] memory);
function GetLivingGoodRolePlayers() public returns(IPlayer[] memory);
}
contract ITHQBY_Settings
{
function() public payable { }
function DAY() public returns(string memory);
function DAY_PK() public returns(string memory);
function NIGHT_KILLER() public returns(string memory);
function NIGHT_POLICE() public returns(string memory);
function POLICE() public returns(string memory);
function CITIZEN() public returns(string memory);
function KILLER() public returns(string memory);
}
contract ISequentialChatter is IChatter//, ITimeLimitForwardable
{
function() public payable { }
function GetSpeakingPlayer() public returns(IPlayer);
function HaveEveryoneSpoke() public returns(bool);
}
// no problem
contract THQBY_Settings is ITHQBY_Settings
{
constructor() payable public
{
}
function() public payable { }
function CITIZEN() public returns(string memory )
{
return "CITIZEN";
}
function DAY() public returns(string memory )
{
return "DAY";
}
function DAY_PK() public returns(string memory )
{
return "DAY_PK";
}
function KILLER() public returns(string memory )
{
return "KILLER";
}
function NIGHT_KILLER() public returns(string memory )
{
return "NIGHT_KILLER";
}
function NIGHT_POLICE() public returns(string memory )
{
return "NIGHT_POLICE";
}
function POLICE() public returns(string memory )
{
return "POLICE";
}
}
/// @dev DN: This is an abstract contract.
contract PlayerFactoryBase is IPlayerFactory
{
uint _idCounter = 0;
function Create(string memory role, address addrs) public returns(IPlayer);
constructor () payable public
{
}
function() public payable { }
}
contract IDependencyInjection
{
function() public payable { }
function BallotFactory() public returns(IBallot);
function ChatLogFactory() public returns(IChatLog);
function ChatterFactory() public returns(IChatter);
function ClockFactory() public returns(IClock);
function PlayerFactoryFactory() public returns(IPlayerFactory);
function PlayerManager() public returns(ITHQBY_PlayerManager);
//IScene SceneFactory(string name);
function SettingsFactory() public returns(ITHQBY_Settings);
function SceneManagerFactory() public returns(ISceneManager);
function ParticipatableFactory() public returns(IParticipatable);
function RoleBidderFactory() public returns(IRoleBidder);
function SequentialChatterFactory() public returns(ISequentialChatter);
function TimeLimitableFactory() public returns(ITimeLimitable);
function SceneDAYFactory() public returns(SceneDAY);
function SceneDAY_PKFactory() public returns(SceneDAY_PK);
function NIGHT_POLICE_Factory() public returns(SceneNIGHT_POLICE);
function NIGHT_KILLER_Factory() public returns(SceneNIGHT_KILLER);
function Initialize() public;
function LateInitiizeAfterRoleBide() public;
}
/////////// implement
contract StrArr
{
string[] _strArr;
constructor() payable public
{
}
function() public payable { }
function GetStrI(uint i) returns(string)
{
return _strArr[i];
}
function GetLength() returns (uint)
{
return _strArr.length;
}
function PushStr(string str) public
{
_strArr.push(str);
}
}
/// @dev DN: This is an abstract contract.
contract RoleBidderBase is IRoleBidder
{
IPlayerFactory _playerFactory;
bool _isClassActive = true; //init usable
uint _playerCount;
uint _numRoles;
int[][] _matrix;
bool[] isVote;
mapping(uint => string) _roleOfPlayerID;
mapping(string => uint[]) _string2RoleIndx;
mapping(int => string) _roleIndx2String;
mapping(string => uint) _spotsOfRole;
mapping(uint=> address) _id2address;
function() public payable { }
function SetID2Address(uint id, address adrs) public
{
_id2address[id]=adrs;
}
/*
* Abstract Contracts
*/
function InitRoles() internal;
function SetSpotsOfRoles() internal;
function Initialize() public;
/*
* Public finctions
*/
constructor (IPlayerFactory playerFactory) payable public {
_playerFactory = playerFactory;
}
// attempt to change signiture to be uint[]
function Initialize(StrArr roles) public
{
_numRoles = roles.GetLength();
for (uint i = 0; i < _numRoles; i++) {
string memory role = roles.GetStrI(i);
_string2RoleIndx[role][0] = 1;
_string2RoleIndx[role][1] = i;
_roleIndx2String[int(i)] = role;
}
}
function Bid(uint playerID, string memory role, uint bidAmount) public
{
bool _bidCheck = (playerID < _playerCount && _string2RoleIndx[role][0] != 0);
require(_bidCheck, "Invalid input!");
_matrix[playerID][_string2RoleIndx[role][1]] = int(bidAmount);
}
function FindMaxNumRole() public returns(uint)
{
uint tempRoleNum;
uint tempMax = 0;
for (uint i = 0; i < _numRoles; i++) {
tempRoleNum = _spotsOfRole[_roleIndx2String[int(i)]];
if (tempRoleNum > tempMax) {
tempMax = tempRoleNum;
}
}
return tempMax;
}
function CreateRoles() public returns(IPlayer[] memory)
{
uint totalRole = 0;
uint maxRoleNum = FindMaxNumRole();
uint totalIteration = maxRoleNum * _numRoles;
IPlayer[] memory res = new IPlayer[](_playerCount);
bool[] memory isAssignedRole = new bool[](_playerCount);
uint[] memory numRoleAssigned = new uint[](_numRoles);
uint curRoleIndex = 0;
uint matrixColumn = 0;
for (uint i = 0; i < _numRoles; i++) {
totalRole += _spotsOfRole[_roleIndx2String[int(i)]];
}
require(totalRole == _playerCount, "numbers of role != numbers of players");
for (uint j = 0; j < totalIteration; j++) {
int tempMax = -1;
uint tempID = 2**256-1;
curRoleIndex = j % _numRoles; // //0->police; 1->citi; 2->killer
if (numRoleAssigned[curRoleIndex] >= _spotsOfRole[_roleIndx2String[int(curRoleIndex)]]) {
continue;
}
for (uint k = 0; k < _playerCount; k++) {
if (!isAssignedRole[k] && (_matrix[k][matrixColumn] > tempMax))
{
tempMax = _matrix[k][matrixColumn];
tempID = k;
}
}
isAssignedRole[tempID] = true;
IPlayer p = _playerFactory.Create(_roleIndx2String[int(curRoleIndex)], _id2address[tempID]);
p.SetId(tempID);
res[tempID] = p;
numRoleAssigned[curRoleIndex]++;
matrixColumn = (matrixColumn + 1) % _numRoles;
}
_isClassActive = false;
for (uint ii=0; ii<res.length; ii++)
{
res[ii].SetId(ii);
}
return res;
}
function GetIsActive() public returns(bool)
{
return _isClassActive;
}
function HasEveryoneBid() public returns(bool)
{
for (uint i = 0; i < _matrix.length; i++)
{
for (uint j = 0; j < _matrix[0].length; j++)
{
if (_matrix[i][j] < 0)
{
return false;
}
}
}
return true;
}
function SetPlayersCount(uint playersCount) public
{
_playerCount = playersCount;
isVote = new bool[](playersCount);
_matrix = new int[][](playersCount);
for (uint i = 0; i < playersCount; i++)
{
_matrix[i] = new int[](_numRoles);
for (uint j = 0; j < _numRoles; j++)
{
_matrix[i][j] = -1;
}
}
}
}
contract Player is IPlayer
{
IChatLog _chatLog;
IBallot _ballot;
bool internal _isAlive = true;
uint internal _id;
string internal _role;
uint internal _votingWeight = 100;
address internal _address;
constructor(address addresss) payable public
{
_address = addresss;
}
function() public payable { }
function Senderaddress() public returns(address)
{
return _address;
}
function GetId() public returns(uint)
{
return _id;
}
function GetIsAlive() public returns(bool)
{
return _isAlive;
}
function GetRole() public returns(string memory)
{
return _role;
}
function GetVotingWeightAsPercent() public returns(uint)
{
return _votingWeight;
}
function KillMe() public
{
_isAlive = false;
}
function SetId(uint id) public
{
_id = id;
}
}
contract Clock is IClock
{
uint _day = 0;
uint _realTimeInSeconds = 0;
function() public payable { }
function GetNth_day() public returns(uint)
{
return _day;
}
function DayPlusPlus() public
{
_day++;
}
function GetRealTimeInSeconds() public returns(uint)
{
return now;
}
}
contract PlayerManager is IPlayerManager
{
IPlayer[] _players;
IPlayer[] _tempPlayersList;
// 之前的 players 作为状态变量是有什么用么?如果有的话那我就改成两个吧
IPlayer[] OneSideLivingPlayers;
IPlayer[] OneSidePlayers;
constructor() payable public
{
}
function() public payable { }
function GetAllLivingPlayers() public returns(IPlayer[] memory)
{
//_tempPlayersList
for (uint i = 0; i < _players.length; i++)
{
IPlayer player = _players[i];
if (player.GetIsAlive())
{
_tempPlayersList.push(player);
}
}
return _tempPlayersList;
}
function GetAllPlayers() public returns(IPlayer[] memory)
{
return _players;
}
function GetDeadPlayers() public returns(IPlayer[] memory)
{
//_tempPlayersList = new IPlayer[];
for (uint i = 0; i < _players.length; i++)
{
IPlayer player = _players[i];
if (!player.GetIsAlive())
{
_tempPlayersList.push(player);
}
}
return _tempPlayersList;
}
function GetPlayer(uint id) public returns (IPlayer )
{
return _players[id];
}
function Initialize(IPlayer[] memory players) public
{
_players = players;
}
function FindLivingByRole(string memory desiredRoleName) internal returns(IPlayer[] memory)
{
IPlayer[] memory all = GetAllPlayers();
for (uint i = 0; i < all.length; i++)
{
IPlayer _curPlayer = all[i];
string memory a;
string memory b;
a = _curPlayer.GetRole();
b = desiredRoleName;
if (keccak256(a) == keccak256(b) && _curPlayer.GetIsAlive())
{
OneSideLivingPlayers.push(_curPlayer);
}
}
return OneSideLivingPlayers;
}
function FindByRole(string memory desiredRoleName) internal returns(IPlayer[] memory)
{
IPlayer[] memory all = GetAllPlayers();
for (uint i = 0; i < all.length; i++)
{
IPlayer _curPlayer = all[i];
string memory a = _curPlayer.GetRole();
string memory b = desiredRoleName;
if (keccak256(a) == keccak256(b))
{
OneSidePlayers.push(_curPlayer);
}
}
return OneSidePlayers;
}
}
contract THQBYRoleBidder is RoleBidderBase
{
ITHQBY_Settings _settings;
StrArr stra;
constructor(ITHQBY_Settings settings, IPlayerFactory PlayerFactory) RoleBidderBase(PlayerFactory) payable public
{
// _playerFactory = PlayerFactory;
_settings = settings;
stra=new StrArr();
}
function() public payable { }
function InitRoles() internal
{
stra.PushStr(_settings.POLICE());
stra.PushStr(_settings.CITIZEN());
stra.PushStr(_settings.KILLER());
Initialize(stra);
SetPlayersCount(12);
}
function SetSpotsOfRoles() internal
{
_spotsOfRole[_settings.POLICE()]= 4;
_spotsOfRole[_settings.CITIZEN()] =4;
_spotsOfRole[_settings.KILLER()] =4;
}
function Initialize() public
{
SetSpotsOfRoles();
InitRoles();
}
}
contract THQBY_PLayer is Player
{
constructor(ITHQBY_Settings settings, address addresss) Player(addresss) payable public
{
}
function() public payable { }
}
contract Police is THQBY_PLayer
{
constructor(ITHQBY_Settings settings, address addresss) THQBY_PLayer(settings,addresss) payable public
{
// base(settings) from THQBY_PLayer
_role = settings.POLICE();
}
function() public payable { }
}
contract Killer is THQBY_PLayer
{
constructor(ITHQBY_Settings settings, address addresss) THQBY_PLayer(settings,addresss) payable public
{
// base(settings) from THQBY_PLayer
_role = settings.KILLER();
}
function() public payable { }
}
contract Citizen is THQBY_PLayer
{
constructor(ITHQBY_Settings settings, address addresss) THQBY_PLayer(settings,addresss) payable public
{
// base(settings) from THQBY_PLayer
_role = settings.CITIZEN();
}
function() public payable { }
}
contract ParticipatableBase is IParticipatable
{
IPlayer[] internal _players;
mapping(address => bool) internal _canParticipate;
function() public payable { }
function GetParticipants() public returns(IPlayer[] memory)
{
return _players;
}
function EnableParticipant(IPlayer player) public
{
_canParticipate[player.Senderaddress()] = true;
}
function DisableParticipant(IPlayer player) public
{
_canParticipate[player.Senderaddress()] = false;
}
function DisableAllParticipants() public
{
SetAllParticibility(false);
}
function EnableAllParticipants() public
{
SetAllParticibility(true);
}
function SetAllParticibility(bool canParticipate) private
{
for (uint i = 0; i < _players.length; i++)
{
_canParticipate[_players[i].Senderaddress()] = canParticipate;
}
}
function Initialize(IPlayer[] memory players) public
{
_players = players;
EnableAllParticipants();
}
function IsRegisteredParticipant(IPlayer player) public returns(bool)
{
// return _players.Contains(player);
for (uint i = 0; i< _players.length; i++)
{
if (_players[i]==player)
{return true;}
}
return false;
}
function CanParticipate(IPlayer player) public returns(bool)
{
if (!IsRegisteredParticipant(player))
{
return false;
}
return _canParticipate[player.Senderaddress()];
}
function ParticipatablePlayersCount() public returns(uint)
{
uint ans = 0;
for (uint i = 0; i < _players.length; i++)
{
if (CanParticipate(_players[i]))
{
ans++;
}
}
return ans;
}
}
contract TimeLimitable is IClock, ITimeLimitable
{
IClock _clock;
uint _startingTimeInSeconds;
uint _timeLimitInSeconds;
constructor(IClock clock) payable public
{
_clock = clock;
}
function() public payable { }
function GetNth_day() public returns(uint)
{
return _clock.GetNth_day();
}
function DayPlusPlus() public
{
_clock.DayPlusPlus();
}
function GetRealTimeInSeconds() public returns(uint)
{
return _clock.GetRealTimeInSeconds();
}
function IsOverTime() public returns(bool)
{
return GetRealTimeInSeconds() >= (_startingTimeInSeconds + _timeLimitInSeconds);
}
function SetTimeLimit(uint secondss) public
{
_timeLimitInSeconds = secondss;
}
function IncrementTimeLimit(int secondss) public
{
if (secondss < 0)
{
int temp=int(_timeLimitInSeconds);
if (-secondss > temp)
{
_timeLimitInSeconds = 0;
return;
}
}
_timeLimitInSeconds = uint(int(_timeLimitInSeconds) + secondss);
}
function SetTimerOn() public
{
_startingTimeInSeconds = _clock.GetRealTimeInSeconds();
}
}
contract Ballot is ParticipatableBase, IBallot
{
// 对于部分需判断合约(类)的存在性而创建的structure
struct IPlayerVoted {
bool _voted;
IPlayer _votedIPlayer;
}
mapping(address => IPlayerVoted) _playerVotedwho;
mapping(address => uint) _votesReceivedByPlayer;
IPlayerManager _playerManager;
IPlayer[] _winniers;
constructor (IPlayerManager playerManager) payable public
{
_playerManager = playerManager;
}
function() public payable { }
// Function overriden
function Initialize(IPlayer[] memory participants) public
{
// Here modifying the fucnction upon logic, while not confirmed yet.
ParticipatableBase.Initialize(participants);
IPlayer[] memory allplayers = _playerManager.GetAllPlayers();
for (uint i = 0; i < allplayers.length; i++) {
_votesReceivedByPlayer[allplayers[i].Senderaddress()] = 0;
_playerVotedwho[allplayers[i].Senderaddress()]._voted = false;
}
}
function CanParticipate(IPlayer player) public returns (bool)
{
if (!player.GetIsAlive()) {
return false;
}
return ParticipatableBase.CanParticipate(player);
}
function GetWinners() public returns(IPlayer[] memory)
{
uint max = 0;
for (uint i = 0; i < _players.length; i++)
{
uint maxCandidate = _votesReceivedByPlayer[_players[i].Senderaddress()];
if (maxCandidate > max)
{
max = maxCandidate;
IPlayer[] memory tempIPlayer;
_winniers = tempIPlayer;
_winniers.push(_players[i]);
}
else if (maxCandidate == max)
{
_winniers.push(_players[i]);
}
}
return _winniers;
}
function IsEveryVotableOnesVoted() public returns(bool)
{
return VotedPlayerCount() == ParticipatablePlayersCount();
}
function TryVote(IPlayer byWho, IPlayer toWho) public returns(bool)
{
if (DidVote(byWho))
{
return false;
}
bool voteSuccess = CanParticipate(byWho);
if (voteSuccess)
{
_playerVotedwho[byWho.Senderaddress()]._votedIPlayer = toWho;
_votesReceivedByPlayer[toWho.Senderaddress()] += byWho.GetVotingWeightAsPercent();
}
return voteSuccess;
}
function VotedPlayerCount() public returns(uint)
{
uint ans = 0;
for (uint i = 0; i < _players.length; i++)
{
IPlayer player = _players[i];
if (DidVote(player))
{
ans++;
}
}
return ans;
}
function WhoDidThePlayerVote(IPlayer player) public returns(IPlayer)
{
if (_playerVotedwho[player.Senderaddress()]._voted == true) {
return _playerVotedwho[player.Senderaddress()]._votedIPlayer;
}
else
{
//return 0;
// 这里逻辑上好像应该报错,最经济的做法是revert
revert("There is no vote to this player.");
}
}
function DidVote(IPlayer player) public returns(bool)
{
return _playerVotedwho[player.Senderaddress()]._voted == true;
}
function IsSoloWinder() public returns(bool)
{
return GetWinners().length == 1;
}
function IsZeroWinders() public returns(bool)
{
return GetWinners().length == 0;
}
}
contract ChatLog is ParticipatableBase, IChatLog
{
ChatMessage[] _messages;
uint _messageCount = 0;
IClock _clock;
constructor(IClock clock) payable public
{
_clock = clock;
//_messages = new List<ChatMessage>();
_messageCount=0;
}
function() public payable { }
function TryChat(IPlayer player, string memory message) public returns(bool)
{
if (!CanParticipate(player))
{
return false;
}
ChatMessage chatMessage = new ChatMessage(GetTimeAsSeconds(),int(player.GetId()), message);
PushMessage(chatMessage);
return true;
}
function GetTimeAsSeconds() private returns(uint)
{
return _clock.GetRealTimeInSeconds();
}
function GetAllMessages() public returns(ChatMessage[] memory)
{
return _messages;
}
function GetNewestMessage() public returns(ChatMessage )
{
return _messages[uint(_messageCount - 1)];
}
function PrintSystemMessage(string memory message ) public
{
ChatMessage chatMessage = new ChatMessage(GetTimeAsSeconds(),-1,message);
PushMessage(chatMessage);
}
function PushMessage(ChatMessage message) private
{
_messages.push(message);
_messageCount++;
}
}
// This is also an Abstract contract
contract Scene is ITimeLimitable, IScene, IPrivateScene
{
uint roundTime = 60 seconds;
IBallot _ballot;
IChatter _chatter;
ITimeLimitable _timeLimitable;
ITHQBY_Settings _settings;
ISceneManagerFriendToScene _sceneManager;
string _sceneName;
// public event Action movedForward;
event movedForward(string);
event print(string);
constructor(IBallot ballot, IChatter chatter, ITimeLimitable timeLimitable, ITHQBY_Settings settings) payable public
{
_ballot = ballot;
_chatter = chatter;
_timeLimitable = timeLimitable;
_settings = settings;
}
function() public payable { }
function DoesPlayerHavePrivilageToMoveForward(IPlayer player) public returns(bool);
function ZeroVotingResultHandler() public;
function OneVotingResultHandler(IPlayer result) public;
function MoreVotingResultHandler(IPlayer[] memory result) public;
function Ballot() public returns(IBallot)
{
return _ballot;
}
function Chatter() public returns(IChatter)
{
return _chatter;
}
function DayPlusPlus() public
{
_timeLimitable.DayPlusPlus();
}
function GetNth_day() public returns(uint)
{
return _timeLimitable.GetNth_day();
}
function GetRealTimeInSeconds() public returns(uint)
{
return _timeLimitable.GetRealTimeInSeconds();
}
function GetSceneName() public returns (string memory)
{
return _sceneName;
}
function Initialize(ISceneManagerFriendToScene sceneManager, IPlayer[] memory participants) public
{
_sceneManager = sceneManager;
_ballot.Initialize(participants); //
_chatter.Initialize(participants);
}
function IsOverTime() public returns (bool)
{
return _timeLimitable.IsOverTime();
}
function SetTimeLimit(uint secondss) public
{
_timeLimitable.SetTimeLimit(secondss);
}
function SetTimerOn() public
{
_timeLimitable.SetTimerOn();
}
function TryMoveForward(IPlayer player) public returns(bool)
{
if (IsOverTime())
{
MoveForward();
return true;
}
else if (DoesPlayerHavePrivilageToMoveForward(player))
{
MoveForward();
return true;
}
else
{
return false;
}
}
function MoveForward() public
{
uint votingCount = VotingResultCount();
if (votingCount == 0)
{
ZeroVotingResultHandler();
}
else if (votingCount == 1)
{
OneVotingResultHandler(VotingResult()[0]);
}
else
{
MoreVotingResultHandler(VotingResult());
}
}
function VotingResult() public returns(IPlayer[] memory)
{
return Ballot().GetWinners();
}
function VotingResultCount() public returns(uint)
{
return VotingResult().length;
}
function KillSomebody(IPlayer somebody) public
{
somebody.KillMe();
PrintMessagePlayerDead(somebody);
}
// 不得不实现显示转换 uint -> string
function uint2str(uint i) private returns (string memory){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function PrintMessagePlayerDead(IPlayer somebody) public
{
_chatter.PrintSystemMessage("___________");
_chatter.PrintSystemMessage("Killed Play with ID=");
_chatter.PrintSystemMessage(uint2str(somebody.GetId()));
_chatter.PrintSystemMessage("___________");
}
function IncrementTimeLimit(int secondss) public
{
_timeLimitable.IncrementTimeLimit(secondss);
}
function Refresh() public
{
_chatter.SetTimeLimit(roundTime);
_timeLimitable.SetTimeLimit(roundTime * _ballot.ParticipatablePlayersCount() + roundTime);
SetTimerOn();
}
}
contract THQBY_Scene is Scene
{
SceneDAY _sceneDay;
SceneDAY_PK _scenePK;
SceneNIGHT_KILLER _sceneKiller;
SceneNIGHT_POLICE _scecenPOLICE;
constructor (IBallot ballot
, IChatter chatter
, ITimeLimitable timeLimitable
, ITHQBY_Settings settings) Scene(ballot, chatter, timeLimitable, settings)
payable public
{
}
function() public payable { }
// setter
function Set_sceneDay(SceneDAY sceneDay) public
{
_sceneDay = sceneDay;
}
function Set_scenePK(SceneDAY_PK scenePK) public
{
_scenePK = scenePK;
}
function Set_sceneKiller(SceneNIGHT_KILLER sceneKiller) public
{
_sceneKiller = sceneKiller;
}
function Set_scecenPOLICE(SceneNIGHT_POLICE scecenPOLICE) public
{
_scecenPOLICE = scecenPOLICE;
}
function DoesPlayerHavePrivilageToMoveForward(IPlayer player) public returns (bool)
{
return _ballot.IsEveryVotableOnesVoted();
}
function KillSomebody(IPlayer someobdy) public
{
super.KillSomebody(someobdy);
}
}
contract SceneDAY is THQBY_Scene
{
constructor (IBallot ballot
, IChatter chatter
, ITimeLimitable timeLimitable
, ITHQBY_Settings settings) THQBY_Scene(ballot, chatter, timeLimitable, settings)
payable public
{
_sceneName = _settings.DAY();
}
function() public payable { }
function MoreVotingResultHandler(IPlayer[] memory result) public
{
_sceneManager.MoveForwardToNewScene(_scenePK);
//must do after scene change
_scenePK.Chatter().DisableAllParticipants();
for (uint i = 0; i < result.length; i++)
{
IPlayer player = result[i];
_scenePK.Chatter().EnableParticipant(player);
}
}
function OneVotingResultHandler(IPlayer result) public
{
KillSomebody(result);
GotoKillerScene();
}
function GotoKillerScene() private
{
_sceneManager.MoveForwardToNewScene(_sceneKiller);
}
function ZeroVotingResultHandler() public
{
GotoKillerScene();
}
}
contract SceneDAY_PK is THQBY_Scene
{
constructor (IBallot ballot
, IChatter chatter
, ITimeLimitable timeLimitable
, ITHQBY_Settings settings) THQBY_Scene(ballot, chatter, timeLimitable, settings)
payable public
{
_sceneName = _settings.DAY();
}
function() public payable { }
function MoreVotingResultHandler(IPlayer[] memory result) public
{
GotoKillerScene();
}
function OneVotingResultHandler(IPlayer result) public
{
KillSomebody(result);
GotoKillerScene();
}
function ZeroVotingResultHandler() public
{
GotoKillerScene();
}
function GotoKillerScene() private
{
_sceneManager.MoveForwardToNewScene(_sceneKiller);
}
}
contract SceneNIGHT_KILLER is THQBY_Scene
{
constructor (IBallot ballot
, IChatter chatter
, ITimeLimitable timeLimitable
, ITHQBY_Settings settings) THQBY_Scene(ballot, chatter, timeLimitable, settings)
payable public
{
_sceneName=_settings.NIGHT_KILLER();
}
function() public payable { }
function MoreVotingResultHandler(IPlayer[] memory result) public
{
GotoKillerScene();
}
function OneVotingResultHandler(IPlayer result) public
{
KillSomebody(result);
_sceneDay.KillSomebody(result);
GotoKillerScene();
}
function ZeroVotingResultHandler() public
{
GotoKillerScene();
}
function GotoKillerScene() private
{
_sceneManager.MoveForwardToNewScene(_sceneKiller);
}
function Refresh() public
{
_chatter.SetTimeLimit(2 * roundTime);
_timeLimitable.SetTimeLimit(2 * roundTime);
SetTimerOn();
}
}
contract SceneNIGHT_POLICE is THQBY_Scene
{
constructor (IBallot ballot
, IChatter chatter
, ITimeLimitable timeLimitable
, ITHQBY_Settings settings) THQBY_Scene(ballot, chatter, timeLimitable, settings)
payable public
{
_sceneName=_settings.NIGHT_POLICE();
}
function() public payable { }
function GotoDayScene() public
{
_sceneManager.MoveForwardToNewScene(_sceneDay);
DayPlusPlus();
}
function MoreVotingResultHandler(IPlayer[] memory result) public
{
GotoDayScene();
}
function OneVotingResultHandler(IPlayer result) public
{
_chatter.PrintSystemMessage(result.GetRole());
GotoDayScene();
}
function ZeroVotingResultHandler() public
{
GotoDayScene();
}
function Refresh() public
{
_chatter.SetTimeLimit(2 * roundTime);
_timeLimitable.SetTimeLimit(2 * roundTime);
SetTimerOn();
}
}
// This is an abstract contract
contract SceneManagerBase is ITimeLimitForwardable, ISceneManager, ISceneManagerFriendToScene
{
IScene _currentScene;
constructor() payable public
{
}
function() public payable { }
function Initialize() public;
function DayPlusPlus() public
{
_currentScene.DayPlusPlus();
}
function GetNth_day() public returns(uint)
{
return _currentScene.GetNth_day();
}
function GetRealTimeInSeconds() public returns(uint)
{
return _currentScene.GetRealTimeInSeconds();
}
function IsOverTime() public returns (bool)
{
return _currentScene.IsOverTime();
}
function SetTimeLimit(uint secondss) public
{
_currentScene.SetTimeLimit(secondss);
}
function SetTimerOn() public
{
_currentScene.SetTimerOn();
}
function TryMoveForward(IPlayer player) public returns (bool)
{
return _currentScene.TryMoveForward(player);
}
function OnChangeScene() public
{
}
function GetCurrentScene() public returns (IScene)
{
return _currentScene;
}
function MoveForwardToNewScene(IScene newScene) public
{
_currentScene = newScene;
_currentScene.Refresh();
OnChangeScene();
}
function IncrementTimeLimit(int secondss) public
{
_currentScene.IncrementTimeLimit(secondss);
}
}
contract Chatter is IChatter
{
ITimeLimitable _timeLimitable;
IChatLog _chatLog;
constructor (ITimeLimitable timeLimitable , IChatLog chatLog) payable public
{
_timeLimitable = timeLimitable;
_chatLog = chatLog;
}
function() public payable { }
function CanParticipate(IPlayer player) public returns(bool)
{
return _chatLog.CanParticipate(player);
}
function DayPlusPlus() public
{
_timeLimitable.DayPlusPlus();
}
function DisableAllParticipants() public
{
_chatLog.DisableAllParticipants();
}
function DisableParticipant(IPlayer player) public
{
_chatLog.DisableParticipant(player);
}
function EnableAllParticipants() public
{
_chatLog.EnableAllParticipants();
}
function EnableParticipant(IPlayer player) public
{
_chatLog.EnableParticipant(player);
}
function GetAllMessages() public returns(ChatMessage[] memory)
{
return _chatLog.GetAllMessages();
}
function GetNewestMessage() public returns(ChatMessage)
{
return _chatLog.GetNewestMessage();
}
function GetNth_day() public returns(uint)
{
return _timeLimitable.GetNth_day();
}
function GetParticipants() public returns(IPlayer[] memory)
{
return _chatLog.GetParticipants();
}
function GetRealTimeInSeconds() public returns(uint)
{
return _timeLimitable.GetRealTimeInSeconds();
}
function IncrementTimeLimit(int secondss) public
{
_timeLimitable.IncrementTimeLimit(secondss);
}
function Initialize(IPlayer[] memory participants) public
{
_chatLog.Initialize(participants);
}
function IsOverTime() public returns(bool)
{
return _timeLimitable.IsOverTime();
}
function IsRegisteredParticipant(IPlayer player) public returns(bool)
{
return _chatLog.IsRegisteredParticipant(player);
}
function ParticipatablePlayersCount() public returns(uint)
{
return _chatLog.ParticipatablePlayersCount();
}
function PrintSystemMessage(string memory message) public
{
_chatLog.PrintSystemMessage(message);
}
function SetTimeLimit(uint secondss) public
{
_timeLimitable.SetTimeLimit(secondss);
}
function SetTimerOn() public
{
_timeLimitable.SetTimerOn();
}
function TryChat(IPlayer player, string memory message) public returns (bool)
{
return _chatLog.TryChat(player, message);
}
function TryMoveForward(IPlayer player) public returns (bool)
{
return false;
}
}
contract SequentialChatter is Chatter, ISequentialChatter
{
uint _onePlayerSpeakingTime = 60 seconds;
IPlayerManager _playerManager;
IPlayer _speakingPlayer;
int _spokenPlayersCount = -1;
int _speakingPlayerIndex = -1;
constructor (ITimeLimitable timeLimitable
, IChatLog chatLog
, IPlayerManager playerManager) Chatter(timeLimitable, chatLog) payable public
{
_playerManager = playerManager;
// _timeLimitable = timeLimitable;
_timeLimitable.SetTimeLimit(30);
// _chatLog = chatLog;
}
function() public payable { }
function OnNextPlayer() internal
{
//movedForward?.Invoke();
}
function GetSpeakingPlayer() public returns(IPlayer)
{
return _speakingPlayer;
}
function HaveEveryoneSpoke() public returns (bool)
{
bool ans1 = _chatLog.ParticipatablePlayersCount() == 0;
bool ans2 = _chatLog.GetParticipants().length == uint(_spokenPlayersCount);
return ans1 && ans2;
}
function Initialize(IPlayer[] memory participants) public
{
Chatter.Initialize(participants);
_spokenPlayersCount = -1;
_speakingPlayerIndex = -1;
MoveForwardActionCore();
}
function ParticipatingPlayers() public returns(IPlayer[] memory)
{
return _chatLog.GetParticipants();
}
function TryMoveForward(IPlayer player) public returns(bool)
{
if (IsOverTime())
{
MoveForward();
return true;
}
else if (DoesPlayerHavePrivilageToMoveForward(player))
{
MoveForward();
return true;
}
else
{
return false;
}
}
function MoveForwardActionCore() internal
{
_spokenPlayersCount++;
_speakingPlayerIndex++;
if (_speakingPlayerIndex < int(_chatLog.GetParticipants().length))
{
_speakingPlayer = ParticipatingPlayers()[uint(_speakingPlayerIndex)];
}
_chatLog.DisableAllParticipants();
// if (_speakingPlayer != null)
{
_chatLog.EnableParticipant(_speakingPlayer);
}
}
function MoveForward() private
{
MoveForwardActionCore();
OnNextPlayer();
}
function DoesPlayerHavePrivilageToMoveForward(IPlayer player) public returns(bool)
{
return player == _speakingPlayer;
}
function EnableParticipant(IPlayer player) public
{
Chatter.EnableParticipant(player);
_timeLimitable.IncrementTimeLimit(int(_onePlayerSpeakingTime));
}
function DisableParticipant(IPlayer player) public
{
Chatter.DisableParticipant(player);
_timeLimitable.IncrementTimeLimit(int(-_onePlayerSpeakingTime));
}
}
contract DependencyInjection is IDependencyInjection
{
ITHQBY_PlayerManager _playerManager;
IClock _clock;
IPlayerFactory _playerfact;
IRoleBidder _roleBidder;
ISceneManager _sceneManager;
ITHQBY_Settings _tHQBY_Settings;
SceneDAY _sceneDAY;
SceneDAY_PK _sceneDAY_PK;
SceneNIGHT_KILLER _sceneNIGHT_KILLER;
SceneNIGHT_POLICE _sceneNIGHT_POLICE;
// For game play
IPlayer[] private _players;
THQBY_Scene private scn;//helper
function InitSceneHelper() private
{
scn.Set_scecenPOLICE(_sceneNIGHT_POLICE);
scn.Set_sceneDay(_sceneDAY);
scn.Set_scenePK(_sceneDAY_PK);
scn.Set_sceneKiller(_sceneNIGHT_KILLER);
}
constructor() payable public
{
IBallot ballot = BallotFactory();
IChatter chatter = ChatterFactory();
ITimeLimitable timeLimitable = TimeLimitableFactory();
ITHQBY_Settings settings = SettingsFactory();
_sceneNIGHT_KILLER = new SceneNIGHT_KILLER(ballot, chatter, timeLimitable, settings);
_sceneNIGHT_POLICE = new SceneNIGHT_POLICE(ballot, chatter, timeLimitable, settings);
_sceneDAY = new SceneDAY(ballot, chatter, timeLimitable, settings);
_sceneDAY_PK = new SceneDAY_PK(ballot, chatter, timeLimitable, settings);
scn = _sceneNIGHT_KILLER;
InitSceneHelper();
scn = _sceneNIGHT_POLICE;
InitSceneHelper();
scn = _sceneDAY;
InitSceneHelper();
scn = _sceneDAY_PK;
InitSceneHelper();
}
function() public payable { }
function Players() public returns(IPlayer[] memory)
{
return _players;
}
// AsTransient
function BallotFactory() public returns(IBallot)
{
IPlayerManager playerManager = PlayerManager();
return new Ballot(playerManager);
}
// AsTransient
function ChatLogFactory() public returns(IChatLog)
{
IClock clock = ClockFactory();
return new ChatLog(clock);
}
//AsTransient
function ChatterFactory() public returns(IChatter)
{
ITimeLimitable TimeLimitableFact = TimeLimitableFactory();
IChatLog chatLog = ChatLogFactory();
return new Chatter(TimeLimitableFact, chatLog);
}
//AsTransient
function SequentialChatterFactory() public returns(ISequentialChatter)
{
ITimeLimitable TimeLimitable = TimeLimitableFactory();
IChatLog chatLog = ChatLogFactory();
IPlayerManager playerManager = PlayerManager();
return new SequentialChatter(TimeLimitable, chatLog, playerManager);
}
//AsSingle
function ClockFactory() public returns(IClock)
{
// 一个可能可以处理null的方法是直接判断该合约地址是否为0x0
// 所以其实下面if判定部分可以省略,
if ( address(_clock) == address(0x0))
{
_clock = new Clock();
}
return _clock;
}
//AsSingle
function NIGHT_KILLER_Factory() public returns(SceneNIGHT_KILLER)
{
return _sceneNIGHT_KILLER;
}
//AsSingle
function NIGHT_POLICE_Factory() public returns(SceneNIGHT_POLICE)
{
return _sceneNIGHT_POLICE;
}
//AsTransient
function ParticipatableFactory() public returns(IParticipatable)
{
return new ParticipatableBase();
}
//AsTransient
function PlayerFactoryFactory() public returns(IPlayerFactory)
{
if (address(_playerfact) == address(0x0))
{
ITHQBY_Settings settings = SettingsFactory();
_playerfact = new THQBY_PlayerFactory(settings);
}
return _playerfact;
}
//AsTransient
function PlayerManager() public returns(ITHQBY_PlayerManager)
{
if (address(_playerManager) == address(0x0))
{
ITHQBY_Settings settings = SettingsFactory();
_playerManager = new THQBY_PlayerManager(settings);
}
return _playerManager;
}
//AsTransient
function RoleBidderFactory() public returns(IRoleBidder)
{
if (address(_roleBidder) == address(0x0))
{
IPlayerFactory playerFactory = PlayerFactoryFactory();
ITHQBY_Settings settings = SettingsFactory();
_roleBidder = new THQBYRoleBidder(settings, playerFactory);
}
return _roleBidder;
}
//AsTransient
function SceneDAYFactory() public returns(SceneDAY)
{
return _sceneDAY;
}
//AsSingle
function SceneDAY_PKFactory() public returns(SceneDAY_PK)
{
return _sceneDAY_PK;
}
//AsSingle
function SceneManagerFactory() public returns(ISceneManager)
{
if (address(_sceneManager) == address(0x0))
{
SceneDAY sceneDay = SceneDAYFactory();
SceneDAY_PK scenePK = SceneDAY_PKFactory();
SceneNIGHT_KILLER sceneNIGHT_KILLER = NIGHT_KILLER_Factory();
SceneNIGHT_POLICE sceneNIGHT_POLICE = NIGHT_POLICE_Factory();
ITHQBY_PlayerManager playerManager = PlayerManager();
_sceneManager = new THQBY_SceneManager(sceneDay, scenePK, sceneNIGHT_KILLER, sceneNIGHT_POLICE, playerManager);
}
return _sceneManager;
}
//AsSingle
function SettingsFactory() public returns(ITHQBY_Settings)
{
if (address(_tHQBY_Settings) ==address(0x0))
{
_tHQBY_Settings = new THQBY_Settings();
}
return _tHQBY_Settings;
}
//AsTransient
function TimeLimitableFactory() public returns(ITimeLimitable)
{
IClock clock = ClockFactory();
return new TimeLimitable(clock);
}
function LateInitiizeAfterRoleBide() public
{
}
function Initialize() public
{
}
}
//////////////// THQBY specific code //////////////
contract THQBY_PlayerFactory is PlayerFactoryBase
{
ITHQBY_Settings _settings;
//mannually DI
constructor(ITHQBY_Settings settings) PlayerFactoryBase() payable public
{
_settings = settings;
}
function() public payable { }
function Create(string memory role, address addrs) public returns(IPlayer)
{
IPlayer ans;
if ( keccak256(role) == keccak256(_settings.CITIZEN()))
{
ans = new Citizen(_settings,addrs);
}
else if ( keccak256(role) == keccak256(_settings.KILLER()))
{
ans = new Killer(_settings,addrs);
}
else if ( keccak256(role) == keccak256(_settings.POLICE()))
{
ans = new Police(_settings,addrs);
}
else {
revert("no such role");
}
ans.SetId(_idCounter);
_idCounter++;
return ans;
}
}
contract THQBY_PlayerManager is PlayerManager, ITHQBY_PlayerManager
{
ITHQBY_Settings _names;
constructor(ITHQBY_Settings settings) payable public
{
_names = settings;
}
function() public payable { }
function GetLivingCitizenPlayers() public returns (IPlayer[] memory )
{
return FindLivingByRole(_names.CITIZEN());
}
function GetLivingKillerPlayers() public returns (IPlayer[] memory )
{
return FindLivingByRole(_names.KILLER());
}
function GetLivingPolicePlayers() public returns (IPlayer[] memory )
{
return FindLivingByRole(_names.POLICE());
}
function GetPolicePlayers() public returns(IPlayer[] memory)
{
return FindByRole(_names.POLICE());
}
function GetCitizenPlayers() public returns(IPlayer[] memory)
{
return FindByRole(_names.CITIZEN());
}
function GetKillerPlayers() public returns(IPlayer[] memory)
{
return FindByRole(_names.KILLER());
}
function GetGoodRolePlayers() public returns(IPlayer[] memory)
{
IPlayer[] memory _citizens = GetCitizenPlayers();
IPlayer[] memory _polices = GetPolicePlayers();
IPlayer[] _sumGoodRoles;
for (uint i = 0; i < _citizens.length; i++)
{
_sumGoodRoles.push(_citizens[i]);
}
for (uint j = 0; j < _polices.length; j++)
{
_sumGoodRoles.push(_polices[j]);
}
return _sumGoodRoles;
}
function GetLivingGoodRolePlayers() public returns(IPlayer[] memory)
{
IPlayer[] memory _livingCitizens = GetLivingCitizenPlayers();
IPlayer[] memory _livingPolices = GetLivingPolicePlayers();
IPlayer[] _sumLivingGoodRoles;
for (uint i = 0; i < _livingCitizens.length; i++)
{
_sumLivingGoodRoles.push(_livingCitizens[i]);
}
for (uint j = 0; j < _livingPolices.length; j++)
{
_sumLivingGoodRoles.push(_livingPolices[j]);
}
return _sumLivingGoodRoles;
}
}
contract THQBY_SceneManager is SceneManagerBase
{
SceneDAY _sceneDay;
constructor(SceneDAY sceneDay
, SceneDAY_PK scenePK
, SceneNIGHT_KILLER sceneNIGHT_KILLER
, SceneNIGHT_POLICE sceneNIGHT_POLICE
, ITHQBY_PlayerManager playerManager)
payable public
{
_sceneDay = sceneDay;
sceneDay.Initialize(this, playerManager.GetAllPlayers());
scenePK.Initialize(this, playerManager.GetAllPlayers());
sceneNIGHT_KILLER.Initialize(this, playerManager.GetLivingKillerPlayers());
sceneNIGHT_POLICE.Initialize(this, playerManager.GetLivingPolicePlayers());
}
function() public payable { }
function Initialize() public
{
MoveForwardToNewScene(_sceneDay);
}
}
/////////////////////// Main Function To Be ReModeled ////////////////////
contract Main
{
IDependencyInjection _inject;
THQBYRoleBidder _roleBidder;
THQBY_SceneManager _sceneManager;
IPlayer[] _tHQBY_PLayers;
ITHQBY_Settings _settings;
IPlayerManager _PlayerManager;
THQBY_PlayerManager _tHQBY_PlayerManager;
uint _curMaxId;
mapping(address => uint) _AddrToId;
mapping(uint => THQBY_PLayer) _IdToPlayer;
mapping(uint => address) _IdToAddr;
mapping(uint => bool) _isBid;
address[] _addressSet;
address _GameManager;
// Game state
uint _policeAmount;
uint _killerAmount;
uint _citizenAmount;
bool _killerWin;
bool _goodPeopleWin;
bool _endGameOrderFromManager;
IPlayer[] _winnerPlayers;
function() public payable { }
constructor() payable public
{
_inject = new DependencyInjection();
_settings = _inject.SettingsFactory();
_sceneManager = THQBY_SceneManager(_inject.SceneManagerFactory());
_roleBidder = THQBYRoleBidder(_inject.RoleBidderFactory());
_PlayerManager = _inject.PlayerManager();
_roleBidder.Initialize();
}
//starting game
function Bid(uint policeAmount, uint killerAmount, uint citizenAmount) public payable
{
uint sum = policeAmount + killerAmount + citizenAmount;
uint coins = msg.value;
uint invSum = uint(coins / sum);
policeAmount *= invSum;
killerAmount *= invSum;
citizenAmount *= invSum;
uint id = getMyID();
_roleBidder.Bid(id, _settings.POLICE(), policeAmount);
_roleBidder.Bid(id, _settings.KILLER(), killerAmount);
_roleBidder.Bid(id, _settings.CITIZEN(), citizenAmount);
//update structure
_isBid[id] = true;
}
function getChatLog(ChatMessage[] memory msgs) public returns(IChatLog)
{
checkIsBid();
return _sceneManager.GetCurrentScene().Chatter();
}
function getMyID() private returns(uint)
{
address addresss = GetMyAddress();
uint id = Address2ID(addresss);
return id;
}
function GetMyPlayer() public returns(THQBY_PLayer){
checkIsBid();
return Id2Player(getMyID());
}
//accessing
function GetMyAddress() private returns(address)
{
return msg.sender;
}
function getRole() public returns(string memory)
{
checkIsBid();
THQBY_PLayer Player = GetMyPlayer();
return Player.GetRole();
}
//communicating
function TryChat(string memory message) public returns(bool)
{
checkIsBid();
THQBY_PLayer _Player = GetMyPlayer();
return _sceneManager.GetCurrentScene().Chatter().TryChat(_Player, message);
}
function TryEndBid() public returns(bool)
{
if (!_roleBidder.HasEveryoneBid())
{
return false; // someone not voted yet
}
//update players[]
for (uint id = 0; id < _PlayerManager.GetAllPlayers().length; id++)
{
_roleBidder.SetID2Address(id,_IdToAddr[id]);
}
_tHQBY_PLayers = _roleBidder.CreateRoles();
_sceneManager.Initialize();
_PlayerManager.Initialize(_tHQBY_PLayers);
return true;
}
//action method
function TryEndChat() public returns(bool)
{
checkIsBid();
THQBY_PLayer Player = GetMyPlayer();
IScene scene = _sceneManager.GetCurrentScene();
IChatter chatter = scene.Chatter();
return chatter.TryMoveForward(Player);
}
function TryForwardScene() public
{
checkIsBid();
THQBY_PLayer Player = GetMyPlayer();
_sceneManager.TryMoveForward(Player);
}
function TryVote(uint playerID) public returns(bool)
{
checkIsBid();
IPlayer toWhoPlayer = Id2Player(playerID);
THQBY_PLayer Player = GetMyPlayer();
return _sceneManager.GetCurrentScene().Ballot().TryVote(Player, toWhoPlayer);
}
function WhoDidThisPlayerVote(uint playerID) public returns(uint)
{
checkIsBid();
IPlayer p = _sceneManager.GetCurrentScene().Ballot().WhoDidThePlayerVote(Id2Player(playerID));
return p.GetId();
}
function GetBalance() public returns(uint)
{
return this.balance;
}
/*
* 终止游戏pattern
*/
// 语意上来讲,TryEndGame 应根据3种状态返回两种结果
function TryEndGame() private returns(bool)
{
if (EndGameConditionsMet())
{
DistributeFromPool();
return true;
}
else if (_endGameOrderFromManager) {
return true;
}
else
{
return false;
}
}
function EndGameConditionsMet() private returns(bool)
{
if (_killerAmount >= (_policeAmount + _citizenAmount))
{
_killerWin = true;
return true;
}
else if (_killerAmount == 0)
{
_goodPeopleWin = true;
return true;
}
return false;
}
function SetWinnerPlayers() private returns(IPlayer[] memory) {
if (_killerWin)
{
_winnerPlayers = _tHQBY_PlayerManager.GetKillerPlayers();
}
else if (_goodPeopleWin) // 举条件做保护
{
_winnerPlayers = _tHQBY_PlayerManager.GetGoodRolePlayers();
}
}
function DistributeFromPool() private
{
uint CoinsInFund = GetBalance();
uint CoinsForEveryWinner = uint(CoinsInFund / _winnerPlayers.length);
for (uint i = 0; i < _winnerPlayers.length; i++)
{
_winnerPlayers[i].Senderaddress().transfer(CoinsForEveryWinner);
}
IPlayer[] tempPlayers;
_winnerPlayers = tempPlayers;
}
// 该命令仅作为保护机制
function SendEndGameOrder() public
{
require(msg.sender == _GameManager, "You cannot do this");
_endGameOrderFromManager = true;
}
// 根据 TryEndGame 结果自动调用
function EndGame() private
{
if (TryEndGame()) {
// selfdestruct(owner);
}
}
/*
* helper functions
*/
function Address2ID(address playerAddress) private returns(uint)
{
bool addressNotContain = false;
for (uint i = 0; i< _addressSet.length; i++)
{
if(_addressSet[i] == playerAddress)
{
addressNotContain = true;
break;
}
}
//如果input是新address,就给他asign个 id
if (addressNotContain)
{
_AddrToId[playerAddress] = _curMaxId;
_curMaxId++;
return _AddrToId[playerAddress];
}
//如果是旧的address直接调用历史记录。(do nothing)
return _AddrToId[playerAddress];
}
function Address2Player(address playerAddress) private returns (IPlayer)
{
checkIsBid();
uint id = Address2ID(playerAddress);
return Id2Player(id);
}
function Id2Player(uint id) private returns(THQBY_PLayer)
{
checkIsBid();
if (address(_IdToPlayer[id]) == 0x0)
{
_IdToPlayer[id] = THQBY_PLayer(_tHQBY_PLayers[id]);
}
return _IdToPlayer[id];
}
function checkIsBid() private
{
uint id = getMyID();
if (!_isBid[id])
{
revert("Please bid first");
}
}
}
| IScene SceneFactory(string name); | {
function BallotFactory() public returns(IBallot);
function ChatLogFactory() public returns(IChatLog);
function ChatterFactory() public returns(IChatter);
function ClockFactory() public returns(IClock);
function PlayerFactoryFactory() public returns(IPlayerFactory);
function PlayerManager() public returns(ITHQBY_PlayerManager);
function SettingsFactory() public returns(ITHQBY_Settings);
function SceneManagerFactory() public returns(ISceneManager);
function ParticipatableFactory() public returns(IParticipatable);
function RoleBidderFactory() public returns(IRoleBidder);
function SequentialChatterFactory() public returns(ISequentialChatter);
function TimeLimitableFactory() public returns(ITimeLimitable);
function SceneDAYFactory() public returns(SceneDAY);
function SceneDAY_PKFactory() public returns(SceneDAY_PK);
function NIGHT_POLICE_Factory() public returns(SceneNIGHT_POLICE);
function NIGHT_KILLER_Factory() public returns(SceneNIGHT_KILLER);
function Initialize() public;
function LateInitiizeAfterRoleBide() public;
function() public payable { }
}
| 883,078 |
./full_match/1/0x1d737B886D195715dc0d6f82637dd48408eFB84B/sources/taoli.sol | 计算罚息的fcash uint256 oracleRate = calculateOracleRate(currencyId,threeMonthMaturity, blockTime); 这里不需要计算了 oracleRate就是我们call过来的oracleRate Amount to settle is positive, this returns the fCashAmount that the settler will receive as a positive number Exchange rate converts from cash to fCash when multiplying | function calculatfcashByassestCash(int256 amountToSettleAsset,MarketParameters memory market,AssetRateParameters memory assetRate) public view returns (int256) {
uint256 threeMonthMaturity = getThreeMatyrityOrSettlementDate(block.timestamp) ;
uint256 blockTime = block.timestamp ;
uint256 oracleRate = market.oracleRate ;
int256 exchangeRate = getExchangeRateFromImpliedRate(
oracleRate.add(settlementPenalty),
threeMonthMaturity.sub(blockTime)
);
return convertToUnderlying(amountToSettleAsset,assetRate.rate,assetRate.underlyingDecimals)
.mulInRatePrecision(exchangeRate);
}
| 8,449,072 |
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol";
/// @title IMockGenericIntegratee Interface
/// @author Enzyme Council <[email protected]>
interface IMockGenericIntegratee {
function swap(
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
function swapOnBehalf(
address payable,
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
}
/// @title MockGenericAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides a generic adapter that:
/// 1. Provides swapping functions that use various `SpendAssetsTransferType` values
/// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`)
/// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`)
contract MockGenericAdapter is AdapterBase {
address public immutable INTEGRATEE;
// No need to specify the IntegrationManager
constructor(address _integratee) public AdapterBase(address(0)) {
INTEGRATEE = _integratee;
}
function identifier() external pure override returns (string memory) {
return "MOCK_GENERIC";
}
function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
spendAssets_,
maxSpendAssetAmounts_,
,
incomingAssets_,
minIncomingAssetAmounts_,
) = __decodeCallArgs(_callArgs);
return (
__getSpendAssetsHandleTypeForSelector(_selector),
spendAssets_,
maxSpendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified
function __getSpendAssetsHandleTypeForSelector(bytes4 _selector)
private
pure
returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_)
{
if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Remove;
}
if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.None;
}
if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Approve;
}
return IIntegrationManager.SpendAssetsHandleType.Transfer;
}
function removeOnly(
address,
bytes calldata,
bytes calldata
) external {}
function swapA(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapB(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapDirectFromVault(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata
) external {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
IMockGenericIntegratee(INTEGRATEE).swapOnBehalf(
payable(_vaultProxy),
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
function swapViaApproval(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function __decodeCallArgs(bytes memory _callArgs)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory actualSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_,
uint256[] memory actualIncomingAssetAmounts_
)
{
return
abi.decode(
_callArgs,
(address[], uint256[], uint256[], address[], uint256[], uint256[])
);
}
function __decodeCallArgsAndSwap(bytes memory _callArgs) internal {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
for (uint256 i; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]);
}
IMockGenericIntegratee(INTEGRATEE).swap(
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
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 { }
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring assets between
/// the fund's VaultProxy and the adapter, by wrapping the adapter action.
/// This modifier should be implemented in almost all adapter actions, unless they
/// do not move assets or can spend and receive assets directly with the VaultProxy
modifier fundAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
(
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
// Take custody of spend assets (if necessary)
if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) {
for (uint256 i = 0; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).safeTransferFrom(
_vaultProxy,
address(this),
spendAssetAmounts[i]
);
}
}
// Execute call
_;
// Transfer remaining assets back to the fund's VaultProxy
__transferContractAssetBalancesToFund(_vaultProxy, incomingAssets);
__transferContractAssetBalancesToFund(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper for adapters to approve their integratees with the max amount of an asset.
/// Since everything is done atomically, and only the balances to-be-used are sent to adapters,
/// there is no need to approve exact amounts on every call.
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call
function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs)
internal
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return
abi.decode(
_encodedAssetTransferArgs,
(IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[])
);
}
/// @dev Helper to transfer full contract balances of assets to the specified VaultProxy
function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets)
private
{
for (uint256 i = 0; i < _assets.length; i++) {
uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this));
if (postCallAmount > 0) {
ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount);
}
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 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
pragma solidity >=0.6.0 <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.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, 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
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function identifier() external pure returns (string memory identifier_);
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4(
keccak256("addTrackedAssets(address,bytes,bytes)")
);
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// 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);
}
/**
* @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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer, Remove}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IZeroExV2.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "../utils/AdapterBase.sol";
/// @title ZeroExV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to 0xV2 Exchange Contract
contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers {
using AddressArrayLib for address[];
using SafeMath for uint256;
event AllowedMakerAdded(address indexed account);
event AllowedMakerRemoved(address indexed account);
address private immutable EXCHANGE;
mapping(address => bool) private makerToIsAllowed;
// Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA,
// for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely.
constructor(
address _integrationManager,
address _exchange,
address _fundDeployer,
address[] memory _allowedMakers
) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) {
EXCHANGE = _exchange;
if (_allowedMakers.length > 0) {
__addAllowedMakers(_allowedMakers);
}
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ZERO_EX_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
require(
isAllowedMaker(order.makerAddress),
"parseAssetsForMethod: Order maker is not allowed"
);
require(
takerAssetFillAmount <= order.takerAssetAmount,
"parseAssetsForMethod: Taker asset fill amount greater than available"
);
address makerAsset = __getAssetAddress(order.makerAssetData);
address takerAsset = __getAssetAddress(order.takerAssetData);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = makerAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = __calcRelativeQuantity(
order.takerAssetAmount,
order.makerAssetAmount,
takerAssetFillAmount
);
if (order.takerFee > 0) {
address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA());
uint256 takerFeeFillAmount = __calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
); // fee calculated relative to taker fill amount
if (takerFeeAsset == makerAsset) {
require(
order.takerFee < order.makerAssetAmount,
"parseAssetsForMethod: Fee greater than makerAssetAmount"
);
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount);
} else if (takerFeeAsset == takerAsset) {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = takerAsset;
spendAssets_[1] = takerFeeAsset;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = takerAssetFillAmount;
spendAssetAmounts_[1] = takerFeeFillAmount;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Take an order on 0x
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
// Approve spend assets as needed
__approveMaxAsNeeded(
__getAssetAddress(order.takerAssetData),
__getAssetProxy(order.takerAssetData),
takerAssetFillAmount
);
// Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity
if (order.takerFee > 0) {
bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA();
__approveMaxAsNeeded(
__getAssetAddress(zrxData),
__getAssetProxy(zrxData),
__calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
) // fee calculated relative to taker fill amount
);
}
// Execute order
(, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs);
IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature);
}
// PRIVATE FUNCTIONS
/// @dev Parses user inputs into a ZeroExV2.Order format
function __constructOrderStruct(bytes memory _encodedOrderArgs)
private
pure
returns (IZeroExV2.Order memory order_)
{
(
address[4] memory orderAddresses,
uint256[6] memory orderValues,
bytes[2] memory orderData,
) = __decodeZeroExOrderArgs(_encodedOrderArgs);
return
IZeroExV2.Order({
makerAddress: orderAddresses[0],
takerAddress: orderAddresses[1],
feeRecipientAddress: orderAddresses[2],
senderAddress: orderAddresses[3],
makerAssetAmount: orderValues[0],
takerAssetAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimeSeconds: orderValues[4],
salt: orderValues[5],
makerAssetData: orderData[0],
takerAssetData: orderData[1]
});
}
/// @dev Decode the parameters of a takeOrder call
/// @param _encodedCallArgs Encoded parameters passed from client side
/// @return encodedZeroExOrderArgs_ Encoded args of the 0x order
/// @return takerAssetFillAmount_ Amount of taker asset to fill
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_)
{
return abi.decode(_encodedCallArgs, (bytes, uint256));
}
/// @dev Decode the parameters of a 0x order
/// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order
/// @return orderAddresses_ Addresses used in the order
/// - [0] 0x Order param: makerAddress
/// - [1] 0x Order param: takerAddress
/// - [2] 0x Order param: feeRecipientAddress
/// - [3] 0x Order param: senderAddress
/// @return orderValues_ Values used in the order
/// - [0] 0x Order param: makerAssetAmount
/// - [1] 0x Order param: takerAssetAmount
/// - [2] 0x Order param: makerFee
/// - [3] 0x Order param: takerFee
/// - [4] 0x Order param: expirationTimeSeconds
/// - [5] 0x Order param: salt
/// @return orderData_ Bytes data used in the order
/// - [0] 0x Order param: makerAssetData
/// - [1] 0x Order param: takerAssetData
/// @return signature_ Signature of the order
function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs)
private
pure
returns (
address[4] memory orderAddresses_,
uint256[6] memory orderValues_,
bytes[2] memory orderData_,
bytes memory signature_
)
{
return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes));
}
/// @dev Parses the asset address from 0x assetData
function __getAssetAddress(bytes memory _assetData)
private
pure
returns (address assetAddress_)
{
assembly {
assetAddress_ := mload(add(_assetData, 36))
}
}
/// @dev Gets the 0x assetProxy address for an ERC20 token
function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) {
bytes4 assetProxyId;
assembly {
assetProxyId := and(
mload(add(_assetData, 32)),
0xFFFFFFFF00000000000000000000000000000000000000000000000000000000
)
}
assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId);
}
/////////////////////////////
// ALLOWED MAKERS REGISTRY //
/////////////////////////////
/// @notice Adds accounts to the list of allowed 0x order makers
/// @param _accountsToAdd Accounts to add
function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner {
__addAllowedMakers(_accountsToAdd);
}
/// @notice Removes accounts from the list of allowed 0x order makers
/// @param _accountsToRemove Accounts to remove
function removeAllowedMakers(address[] calldata _accountsToRemove)
external
onlyFundDeployerOwner
{
require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove");
for (uint256 i; i < _accountsToRemove.length; i++) {
require(
isAllowedMaker(_accountsToRemove[i]),
"removeAllowedMakers: Account is not an allowed maker"
);
makerToIsAllowed[_accountsToRemove[i]] = false;
emit AllowedMakerRemoved(_accountsToRemove[i]);
}
}
/// @dev Helper to add accounts to the list of allowed makers
function __addAllowedMakers(address[] memory _accountsToAdd) private {
require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd");
for (uint256 i; i < _accountsToAdd.length; i++) {
require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set");
makerToIsAllowed[_accountsToAdd[i]] = true;
emit AllowedMakerAdded(_accountsToAdd[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable value
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Checks whether an account is an allowed maker of 0x orders
/// @param _who The account to check
/// @return isAllowedMaker_ True if _who is an allowed maker
function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) {
return makerToIsAllowed[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @dev Minimal interface for our interactions with the ZeroEx Exchange contract
interface IZeroExV2 {
struct Order {
address makerAddress;
address takerAddress;
address feeRecipientAddress;
address senderAddress;
uint256 makerAssetAmount;
uint256 takerAssetAmount;
uint256 makerFee;
uint256 takerFee;
uint256 expirationTimeSeconds;
uint256 salt;
bytes makerAssetData;
bytes takerAssetData;
}
struct OrderInfo {
uint8 orderStatus;
bytes32 orderHash;
uint256 orderTakerAssetFilledAmount;
}
struct FillResults {
uint256 makerAssetFilledAmount;
uint256 takerAssetFilledAmount;
uint256 makerFeePaid;
uint256 takerFeePaid;
}
function ZRX_ASSET_DATA() external view returns (bytes memory);
function filled(bytes32) external view returns (uint256);
function cancelled(bytes32) external view returns (bool);
function getOrderInfo(Order calldata) external view returns (OrderInfo memory);
function getAssetProxy(bytes4) external view returns (address);
function isValidSignature(
bytes32,
address,
bytes calldata
) external view returns (bool);
function preSign(
bytes32,
address,
bytes calldata
) external;
function cancelOrder(Order calldata) external;
function fillOrder(
Order calldata,
uint256,
bytes calldata
) external returns (FillResults memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @title MathHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for common math operations
abstract contract MathHelpers {
using SafeMath for uint256;
/// @dev Calculates a proportional value relative to a known ratio
function __calcRelativeQuantity(
uint256 _quantity1,
uint256 _quantity2,
uint256 _relativeQuantity1
) internal pure returns (uint256 relativeQuantity2_) {
return _relativeQuantity1.mul(_quantity2).div(_quantity1);
}
/// @dev Calculates a rate normalized to 10^18 precision,
/// for given base and quote asset decimals and amounts
function __calcNormalizedRate(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _quoteAssetAmount
) internal pure returns (uint256 normalizedRate_) {
return
_quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div(
_baseAssetAmount.mul(10**_quoteAssetDecimals)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() external view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
enum ReleaseStatus {PreLaunch, Live, Paused}
function getOwner() external view returns (address);
function getReleaseStatus() external view returns (ReleaseStatus);
function isRegisteredVaultCall(address, bytes4) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "./IPolicy.sol";
import "./IPolicyManager.sol";
/// @title PolicyManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages policies for funds
contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event PolicyDeregistered(address indexed policy, string indexed identifier);
event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy);
event PolicyEnabledForFund(
address indexed comptrollerProxy,
address indexed policy,
bytes settingsData
);
event PolicyRegistered(
address indexed policy,
string indexed identifier,
PolicyHook[] implementedHooks
);
EnumerableSet.AddressSet private registeredPolicies;
mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented;
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies;
modifier onlyBuySharesHooks(address _policy) {
require(
!policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) &&
!policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration),
"onlyBuySharesHooks: Disallowed hook"
);
_;
}
modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) {
require(
policyIsEnabledForFund(_comptrollerProxy, _policy),
"onlyEnabledPolicyForFund: Policy not enabled"
);
_;
}
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Validates and initializes policies as necessary prior to fund activation
/// @param _isMigratedFund True if the fund is migrating to this release
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
function activateForFund(bool _isMigratedFund) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
// Policies must assert that they are congruent with migrated vault state
if (_isMigratedFund) {
address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender);
for (uint256 i; i < enabledPolicies.length; i++) {
__activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]);
}
}
}
/// @notice Deactivates policies for a fund by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) {
comptrollerProxyToPolicies[msg.sender].remove(
comptrollerProxyToPolicies[msg.sender].at(i - 1)
);
}
}
/// @notice Disables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to disable
function disablePolicyForFund(address _comptrollerProxy, address _policy)
external
onlyBuySharesHooks(_policy)
onlyEnabledPolicyForFund(_comptrollerProxy, _policy)
{
__validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender);
comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy);
emit PolicyDisabledForFund(_comptrollerProxy, _policy);
}
/// @notice Enables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to enable
/// @param _settingsData The encoded settings data with which to configure the policy
/// @dev Disabling a policy does not delete fund config on the policy, so if a policy is
/// disabled and then enabled again, its initial state will be the previous config. It is the
/// policy's job to determine how to merge that config with the _settingsData param in this function.
function enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
__enablePolicyForFund(_comptrollerProxy, _policy, _settingsData);
__activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy);
}
/// @notice Enable policies for use in a fund
/// @param _configData Encoded config data
/// @dev Only called during init() on ComptrollerProxy deployment
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory policies, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity check
require(
policies.length == settingsData.length,
"setConfigForFund: policies and settingsData array lengths unequal"
);
// Enable each policy with settings
for (uint256 i; i < policies.length; i++) {
__enablePolicyForFund(msg.sender, policies[i], settingsData[i]);
}
}
/// @notice Updates policy settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The Policy contract to update
/// @param _settingsData The encoded settings data with which to update the policy config
function updatePolicySettingsForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData);
}
/// @notice Validates all policies that apply to a given hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _hook The PolicyHook for which to validate policies
/// @param _validationData The encoded data with which to validate the filtered policies
function validatePolicies(
address _comptrollerProxy,
PolicyHook _hook,
bytes calldata _validationData
) external override {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy);
for (uint256 i; i < policies.length; i++) {
if (!policyImplementsHook(policies[i], _hook)) {
continue;
}
require(
IPolicy(policies[i]).validateRule(
_comptrollerProxy,
vaultProxy,
_hook,
_validationData
),
string(
abi.encodePacked(
"Rule evaluated to false: ",
IPolicy(policies[i]).identifier()
)
)
);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to activate a policy for a fund
function __activatePolicyForFund(
address _comptrollerProxy,
address _vaultProxy,
address _policy
) private {
IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy);
}
/// @dev Helper to set config and enable policies for a fund
function __enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes memory _settingsData
) private {
require(
!policyIsEnabledForFund(_comptrollerProxy, _policy),
"__enablePolicyForFund: policy already enabled"
);
require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered");
// Set fund config on policy
if (_settingsData.length > 0) {
IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData);
}
// Add policy
comptrollerProxyToPolicies[_comptrollerProxy].add(_policy);
emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData);
}
/// @dev Helper to validate fund owner.
/// Preferred to a modifier because allows gas savings if re-using _vaultProxy.
function __validateIsFundOwner(address _vaultProxy, address _who) private view {
require(
_who == IVault(_vaultProxy).getOwner(),
"Only the fund owner can call this function"
);
}
///////////////////////
// POLICIES REGISTRY //
///////////////////////
/// @notice Remove policies from the list of registered policies
/// @param _policies Addresses of policies to be registered
function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
policyIsRegistered(_policies[i]),
"deregisterPolicies: policy is not registered"
);
registeredPolicies.remove(_policies[i]);
emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier());
}
}
/// @notice Add policies to the list of registered policies
/// @param _policies Addresses of policies to be registered
function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "registerPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
!policyIsRegistered(_policies[i]),
"registerPolicies: policy already registered"
);
registeredPolicies.add(_policies[i]);
// Store the hooks that a policy implements for later use.
// Fronts the gas for calls to check if a hook is implemented, and guarantees
// that the implementsHooks return value does not change post-registration.
IPolicy policyContract = IPolicy(_policies[i]);
PolicyHook[] memory implementedHooks = policyContract.implementedHooks();
for (uint256 j; j < implementedHooks.length; j++) {
policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true;
}
emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get all registered policies
/// @return registeredPoliciesArray_ A list of all registered policy addresses
function getRegisteredPolicies()
external
view
returns (address[] memory registeredPoliciesArray_)
{
registeredPoliciesArray_ = new address[](registeredPolicies.length());
for (uint256 i; i < registeredPoliciesArray_.length; i++) {
registeredPoliciesArray_[i] = registeredPolicies.at(i);
}
}
/// @notice Get a list of enabled policies for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledPolicies_ An array of enabled policy addresses
function getEnabledPoliciesForFund(address _comptrollerProxy)
public
view
returns (address[] memory enabledPolicies_)
{
enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length());
for (uint256 i; i < enabledPolicies_.length; i++) {
enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i);
}
}
/// @notice Checks if a policy implements a particular hook
/// @param _policy The address of the policy to check
/// @param _hook The PolicyHook to check
/// @return implementsHook_ True if the policy implements the hook
function policyImplementsHook(address _policy, PolicyHook _hook)
public
view
returns (bool implementsHook_)
{
return policyToHookToIsImplemented[_policy][_hook];
}
/// @notice Check if a policy is enabled for the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund to check
/// @param _policy The address of the policy to check
/// @return isEnabled_ True if the policy is enabled for the fund
function policyIsEnabledForFund(address _comptrollerProxy, address _policy)
public
view
returns (bool isEnabled_)
{
return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy);
}
/// @notice Check whether a policy is registered
/// @param _policy The address of the policy to check
/// @return isRegistered_ True if the policy is registered
function policyIsRegistered(address _policy) public view returns (bool isRegistered_) {
return registeredPolicies.contains(_policy);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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.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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/utils/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault {
function addTrackedAsset(address) external;
function approveAssetSpender(
address,
address,
uint256
) external;
function burnShares(address, uint256) external;
function callOnContract(address, bytes calldata) external;
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getTrackedAssets() external view returns (address[] memory);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function removeTrackedAsset(address) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../IExtension.sol";
/// @title ExtensionBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base class for an extension
abstract contract ExtensionBase is IExtension {
mapping(address => address) internal comptrollerProxyToVaultProxy;
/// @notice Allows extension to run logic during fund activation
/// @dev Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override {
return;
}
/// @notice Allows extension to run logic during fund deactivation (destruct)
/// @dev Unimplemented by default, may be overridden.
function deactivateForFund() external virtual override {
return;
}
/// @notice Receives calls from ComptrollerLib.callOnExtension()
/// and dispatches the appropriate action
/// @dev Unimplemented by default, may be overridden.
function receiveCallFromComptroller(
address,
uint256,
bytes calldata
) external virtual override {
revert("receiveCallFromComptroller: Unimplemented for Extension");
}
/// @notice Allows extension to run logic during fund configuration
/// @dev Unimplemented by default, may be overridden.
function setConfigForFund(bytes calldata) external virtual override {
return;
}
/// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both
/// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy().
/// Will revert without reason if the expected interfaces do not exist.
function __setValidatedVaultProxy(address _comptrollerProxy)
internal
returns (address vaultProxy_)
{
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0),
"__setValidatedVaultProxy: Already set"
);
vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy();
require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy");
require(
_comptrollerProxy == IVault(vaultProxy_).getAccessor(),
"__setValidatedVaultProxy: Not the VaultProxy accessor"
);
comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_;
return vaultProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the verified VaultProxy for a given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return vaultProxy_ The VaultProxy of the fund
function getVaultProxyForFund(address _comptrollerProxy)
public
view
returns (address vaultProxy_)
{
return comptrollerProxyToVaultProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IPolicyManager.sol";
/// @title Policy Interface
/// @author Enzyme Council <[email protected]>
interface IPolicy {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (IPolicyManager.PolicyHook[] memory implementedHooks_);
function updateFundSettings(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _encodedSettings
) external;
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook _hook,
bytes calldata _encodedArgs
) external returns (bool isValid_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
enum PolicyHook {
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreCallOnIntegration,
PostCallOnIntegration
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
enum VaultAction {
None,
BurnShares,
MintShares,
TransferShares,
ApproveAssetSpender,
WithdrawAssetTo,
AddTrackedAsset,
RemoveTrackedAsset
}
function activate(address, bool) external;
function calcGav(bool) external returns (uint256, bool);
function calcGrossShareValue(bool) external returns (uint256, bool);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function configureExtensions(bytes calldata, bytes calldata) external;
function destruct() external;
function getDenominationAsset() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(VaultAction, bytes calldata) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _comptrollerProxy,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(bytes calldata _configData) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IPolicy.sol";
/// @title PolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all policies
abstract contract PolicyBase is IPolicy {
address internal immutable POLICY_MANAGER;
modifier onlyPolicyManager {
require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call");
_;
}
constructor(address _policyManager) public {
POLICY_MANAGER = _policyManager;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @dev Unimplemented by default, can be overridden by the policy
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Updates the policy settings for a fund
/// @dev Disallowed by default, can be overridden by the policy
function updateFundSettings(
address,
address,
bytes calldata
) external virtual override {
revert("updateFundSettings: Updates not allowed for this policy");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `POLICY_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPostValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook
abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (
address adapter_,
bytes4 selector_,
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
return
abi.decode(
_encodedRuleArgs,
(address, bytes4, address[], uint256[], address[], uint256[])
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title MaxConcentration Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that defines a configurable threshold for the concentration of any one asset
/// in a fund's holdings
contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase {
using SafeMath for uint256;
event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value);
uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100%
address private immutable VALUE_INTERPRETER;
mapping(address => uint256) private comptrollerProxyToMaxConcentration;
constructor(address _policyManager, address _valueInterpreter)
public
PolicyBase(_policyManager)
{
VALUE_INTERPRETER = _valueInterpreter;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @dev No need to authenticate access, as there are no state transitions
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Max concentration exceeded"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
uint256 maxConcentration = abi.decode(_encodedSettings, (uint256));
require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0");
require(
maxConcentration <= ONE_HUNDRED_PERCENT,
"addFundSettings: maxConcentration cannot exceed 100%"
);
comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration;
emit MaxConcentrationSet(_comptrollerProxy, maxConcentration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MAX_CONCENTRATION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
/// @dev The fund's denomination asset is exempt from the policy limit.
function passesRule(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _assets
) public returns (bool isValid_) {
uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy];
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
address denominationAsset = comptrollerProxyContract.getDenominationAsset();
// Does not require asset finality, otherwise will fail when incoming asset is a Synth
(uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false);
if (!gavIsValid) {
return false;
}
for (uint256 i = 0; i < _assets.length; i++) {
address asset = _assets[i];
if (
!__rulePassesForAsset(
_vaultProxy,
denominationAsset,
maxConcentration,
totalGav,
asset
)
) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
if (incomingAssets.length == 0) {
return true;
}
return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets);
}
/// @dev Helper to check if the rule holds for a particular asset.
/// Avoids the stack-too-deep error.
function __rulePassesForAsset(
address _vaultProxy,
address _denominationAsset,
uint256 _maxConcentration,
uint256 _totalGav,
address _incomingAsset
) private returns (bool isValid_) {
if (_incomingAsset == _denominationAsset) return true;
uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy);
(uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset);
if (
!assetGavIsValid ||
assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration
) {
return false;
}
return true;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the maxConcentration for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return maxConcentration_ The maxConcentration
function getMaxConcentrationForFund(address _comptrollerProxy)
external
view
returns (uint256 maxConcentration_)
{
return comptrollerProxyToMaxConcentration[_comptrollerProxy];
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../../utils/AssetFinalityResolver.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, AssetFinalityResolver {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event MigratedSharesDuePaid(uint256 sharesDue);
event OverridePauseSet(bool indexed overridePause);
event PreRedeemSharesHookFailed(
bytes failureReturnData,
address redeemer,
uint256 sharesQuantity
);
event SharesBought(
address indexed caller,
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
uint256 sharesQuantity,
address[] receivedAssets,
uint256[] receivedAssetQuantities
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant SHARES_UNIT = 10**18;
address private immutable DISPATCHER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable VALUE_INTERPRETER;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Allows a fund owner to override a release-level pause
bool internal overridePause;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock between any "shares actions" (i.e., buy and redeem shares), per-account
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesAction;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyActive() {
__assertIsActive(vaultProxy);
_;
}
modifier onlyNotPaused() {
__assertNotPaused();
_;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer(msg.sender);
_;
}
modifier onlyOwner() {
__assertIsOwner(msg.sender);
_;
}
modifier timelockedSharesAction(address _account) {
__assertSharesActionNotTimelocked(_account);
_;
acctToLastSharesAction[_account] = block.timestamp;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
/// @dev Since vaultProxy is set during activate(),
/// we can check that var rather than storing additional state
function __assertIsActive(address _vaultProxy) private pure {
require(_vaultProxy != address(0), "Fund not active");
}
function __assertIsFundDeployer(address _who) private view {
require(_who == FUND_DEPLOYER, "Only FundDeployer callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable");
}
function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure {
require(_success, string(_returnData));
}
function __assertNotPaused() private view {
require(!__fundIsPaused(), "Fund is paused");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _account) private view {
require(
block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock,
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _fundDeployer,
address _valueInterpreter,
address _feeManager,
address _integrationManager,
address _policyManager,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) {
DISPATCHER = _dispatcher;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
POLICY_MANAGER = _policyManager;
VALUE_INTERPRETER = _valueInterpreter;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction {
require(
_extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER,
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs);
}
/// @notice Sets or unsets an override on a release-wide pause
/// @param _nextOverridePause True if the pause should be overrode
function setOverridePause(bool _nextOverridePause) external onlyOwner {
require(_nextOverridePause != overridePause, "setOverridePause: Value already set");
overridePause = _nextOverridePause;
emit OverridePauseSet(_nextOverridePause);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyNotPaused onlyActive onlyOwner {
require(
IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector),
"vaultCallOnContract: Unregistered"
);
IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs));
}
/// @dev Helper to check whether the release is paused, and that there is no local override
function __fundIsPaused() private view returns (bool) {
return
IFundDeployer(FUND_DEPLOYER).getReleaseStatus() ==
IFundDeployer.ReleaseStatus.Paused &&
!overridePause;
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(VaultAction _action, bytes calldata _actionData)
external
override
onlyNotPaused
onlyActive
{
__assertPermissionedVaultAction(msg.sender, _action);
if (_action == VaultAction.AddTrackedAsset) {
__vaultActionAddTrackedAsset(_actionData);
} else if (_action == VaultAction.ApproveAssetSpender) {
__vaultActionApproveAssetSpender(_actionData);
} else if (_action == VaultAction.BurnShares) {
__vaultActionBurnShares(_actionData);
} else if (_action == VaultAction.MintShares) {
__vaultActionMintShares(_actionData);
} else if (_action == VaultAction.RemoveTrackedAsset) {
__vaultActionRemoveTrackedAsset(_actionData);
} else if (_action == VaultAction.TransferShares) {
__vaultActionTransferShares(_actionData);
} else if (_action == VaultAction.WithdrawAssetTo) {
__vaultActionWithdrawAssetTo(_actionData);
}
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction
function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view {
require(
permissionedVaultActionAllowed,
"__assertPermissionedVaultAction: No action allowed"
);
if (_caller == INTEGRATION_MANAGER) {
require(
_action == VaultAction.ApproveAssetSpender ||
_action == VaultAction.AddTrackedAsset ||
_action == VaultAction.RemoveTrackedAsset ||
_action == VaultAction.WithdrawAssetTo,
"__assertPermissionedVaultAction: Not valid for IntegrationManager"
);
} else if (_caller == FEE_MANAGER) {
require(
_action == VaultAction.BurnShares ||
_action == VaultAction.MintShares ||
_action == VaultAction.TransferShares,
"__assertPermissionedVaultAction: Not valid for FeeManager"
);
} else {
revert("__assertPermissionedVaultAction: Not a valid actor");
}
}
/// @dev Helper to add a tracked asset to the fund
function __vaultActionAddTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
IVault(vaultProxy).addTrackedAsset(asset);
}
/// @dev Helper to grant a spender an allowance for a fund's asset
function __vaultActionApproveAssetSpender(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).approveAssetSpender(asset, target, amount);
}
/// @dev Helper to burn fund shares for a particular account
function __vaultActionBurnShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).burnShares(target, amount);
}
/// @dev Helper to mint fund shares to a particular account
function __vaultActionMintShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).mintShares(target, amount);
}
/// @dev Helper to remove a tracked asset from the fund
function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
// Allowing this to fail silently makes it cheaper and simpler
// for Extensions to not query for the denomination asset
if (asset != denominationAsset) {
IVault(vaultProxy).removeTrackedAsset(asset);
}
}
/// @dev Helper to transfer fund shares from one account to another
function __vaultActionTransferShares(bytes memory _actionData) private {
(address from, address to, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).transferShares(from, to, amount);
}
/// @dev Helper to withdraw an asset from the VaultProxy to a given account
function __vaultActionWithdrawAssetTo(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).withdrawAssetTo(asset, target, amount);
}
///////////////
// LIFECYCLE //
///////////////
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(denominationAsset == address(0), "init: Already initialized");
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Configure the extensions of a fund
/// @param _feeManagerConfigData Encoded config for fees to enable
/// @param _policyManagerConfigData Encoded config for policies to enable
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerLib has been deployed,
/// giving access to its state and interface
function configureExtensions(
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external override onlyFundDeployer {
if (_feeManagerConfigData.length > 0) {
IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData);
}
if (_policyManagerConfigData.length > 0) {
IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData);
}
}
/// @notice Activates the fund by attaching a VaultProxy and activating all Extensions
/// @param _vaultProxy The VaultProxy to attach to the fund
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy);
if (sharesDue > 0) {
IVault(_vaultProxy).transferShares(
_vaultProxy,
IVault(_vaultProxy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
// Note: a future release could consider forcing the adding of a tracked asset here,
// just in case a fund is migrating from an old configuration where they are not able
// to remove an asset to get under the tracked assets limit
IVault(_vaultProxy).addTrackedAsset(denominationAsset);
// Activate extensions
IExtension(FEE_MANAGER).activateForFund(_isMigration);
IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration);
IExtension(POLICY_MANAGER).activateForFund(_isMigration);
}
/// @notice Remove the config for a fund
/// @dev No need to assert anything beyond FundDeployer access.
/// Calling onlyNotPaused here rather than in the FundDeployer allows
/// the owner to potentially override the pause and rescue unpaid fees.
function destruct()
external
override
onlyFundDeployer
onlyNotPaused
allowsPermissionedVaultAction
{
// Failsafe to protect the libs against selfdestruct
require(!isLib, "destruct: Only delegate callable");
// Deactivate the extensions
IExtension(FEE_MANAGER).deactivateForFund();
IExtension(INTEGRATION_MANAGER).deactivateForFund();
IExtension(POLICY_MANAGER).deactivateForFund();
// Delete storage of ComptrollerProxy
// There should never be ETH in the ComptrollerLib, so no need to waste gas
// to get the fund owner
selfdestruct(address(0));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return gav_ The fund GAV
/// @return isValid_ True if the conversion rates used to derive the GAV are all valid
function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) {
address vaultProxyAddress = vaultProxy;
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
if (assets.length == 0) {
return (0, true);
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = __finalizeIfSynthAndGetAssetBalance(
vaultProxyAddress,
assets[i],
_requireFinality
);
}
(gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue(
assets,
balances,
denominationAsset
);
return (gav_, isValid_);
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return grossShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue(bool _requireFinality)
external
override
returns (uint256 grossShareValue_, bool isValid_)
{
uint256 gav;
(gav, isValid_) = calcGav(_requireFinality);
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAsset).decimals())
);
return (grossShareValue_, isValid_);
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares in the fund for multiple sets of criteria
/// @param _buyers The accounts for which to buy shares
/// @param _investmentAmounts The amounts of the fund's denomination asset
/// with which to buy shares for the corresponding _buyers
/// @param _minSharesQuantities The minimum quantities of shares to buy
/// with the corresponding _investmentAmounts
/// @return sharesReceivedAmounts_ The actual amounts of shares received
/// by the corresponding _buyers
/// @dev Param arrays have indexes corresponding to individual __buyShares() orders.
function buyShares(
address[] calldata _buyers,
uint256[] calldata _investmentAmounts,
uint256[] calldata _minSharesQuantities
)
external
onlyNotPaused
locksReentrance
allowsPermissionedVaultAction
returns (uint256[] memory sharesReceivedAmounts_)
{
require(_buyers.length > 0, "buyShares: Empty _buyers");
require(
_buyers.length == _investmentAmounts.length &&
_buyers.length == _minSharesQuantities.length,
"buyShares: Unequal arrays"
);
address vaultProxyCopy = vaultProxy;
__assertIsActive(vaultProxyCopy);
require(
!IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy),
"buyShares: Pending migration"
);
(uint256 gav, bool gavIsValid) = calcGav(true);
require(gavIsValid, "buyShares: Invalid GAV");
__buySharesSetupHook(msg.sender, _investmentAmounts, gav);
address denominationAssetCopy = denominationAsset;
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
sharesReceivedAmounts_ = new uint256[](_buyers.length);
for (uint256 i; i < _buyers.length; i++) {
sharesReceivedAmounts_[i] = __buyShares(
_buyers[i],
_investmentAmounts[i],
_minSharesQuantities[i],
vaultProxyCopy,
sharePrice,
gav,
denominationAssetCopy
);
gav = gav.add(_investmentAmounts[i]);
}
__buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav);
return sharesReceivedAmounts_;
}
/// @dev Helper to buy shares
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
address _vaultProxy,
uint256 _sharePrice,
uint256 _preBuySharesGav,
address _denominationAsset
) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) {
require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount");
// Gives Extensions a chance to run logic prior to the minting of bought shares
__preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav);
// Calculate the amount of shares to issue with the investment amount
uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer);
IVault(_vaultProxy).mintShares(_buyer, sharesIssued);
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is preferred
// to have the final state of the VaultProxy prior to running __postBuySharesHook().
ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions after all __buyShares() calls are made
function __buySharesCompletedHook(
address _caller,
uint256[] memory _sharesReceivedAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts),
_gav
);
}
/// @dev Helper for Extension actions before any __buyShares() calls are made
function __buySharesSetupHook(
address _caller,
uint256[] memory _investmentAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts),
_gav
);
}
/// @dev Helper for Extension actions immediately prior to issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
uint256 _gav
) private {
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity),
_gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav)
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// Same comment applies from __preBuySharesHook() above.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
// REDEEM SHARES
/// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev See __redeemShares() for further detail
function redeemShares()
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
return
__redeemShares(
msg.sender,
ERC20(vaultProxy).balanceOf(msg.sender),
new address[](0),
new address[](0)
);
}
/// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of
/// the fund's assets, optionally specifying additional assets and assets to skip.
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
function redeemSharesDetailed(
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) {
return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity)
private
allowsPermissionedVaultAction
{
try
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesQuantity),
0
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity);
}
}
/// @dev Helper to redeem shares.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function __redeemShares(
address _redeemer,
uint256 _sharesQuantity,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
)
private
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0");
require(
_additionalAssets.isUniqueSet(),
"__redeemShares: _additionalAssets contains duplicates"
);
require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates");
IVault vaultProxyContract = IVault(vaultProxy);
// Only apply the sharesActionTimelock when a migration is not pending
if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) {
__assertSharesActionNotTimelocked(_redeemer);
acctToLastSharesAction[_redeemer] = block.timestamp;
}
// When a fund is paused, settling fees will be skipped
if (!__fundIsPaused()) {
// Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`),
// then those fee shares will be transferred from the user's balance rather
// than reallocated from the sharesQuantity being redeemed.
__preRedeemSharesHook(_redeemer, _sharesQuantity);
}
// Check the shares quantity against the user's balance after settling fees
ERC20 sharesContract = ERC20(address(vaultProxyContract));
require(
_sharesQuantity <= sharesContract.balanceOf(_redeemer),
"__redeemShares: Insufficient shares"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
vaultProxyContract.getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
require(payoutAssets_.length > 0, "__redeemShares: No payout assets");
// Destroy the shares.
// Must get the shares supply before doing so.
uint256 sharesSupply = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, _sharesQuantity);
// Calculate and transfer payout asset amounts due to redeemer
payoutAmounts_ = new uint256[](payoutAssets_.length);
address denominationAssetCopy = denominationAsset;
for (uint256 i; i < payoutAssets_.length; i++) {
uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance(
address(vaultProxyContract),
payoutAssets_[i],
true
);
// If all remaining shares are being redeemed, the logic changes slightly
if (_sharesQuantity == sharesSupply) {
payoutAmounts_[i] = assetBalance;
// Remove every tracked asset, except the denomination asset
if (payoutAssets_[i] != denominationAssetCopy) {
vaultProxyContract.removeTrackedAsset(payoutAssets_[i]);
}
} else {
payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply);
}
// Transfer payout asset to redeemer
if (payoutAmounts_[i] > 0) {
vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]);
}
}
emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_);
return (payoutAssets_, payoutAmounts_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the routes for the various contracts used by all funds
/// @return dispatcher_ The `DISPATCHER` variable value
/// @return feeManager_ The `FEE_MANAGER` variable value
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getLibRoutes()
external
view
returns (
address dispatcher_,
address feeManager_,
address fundDeployer_,
address integrationManager_,
address policyManager_,
address primitivePriceFeed_,
address valueInterpreter_
)
{
return (
DISPATCHER,
FEE_MANAGER,
FUND_DEPLOYER,
INTEGRATION_MANAGER,
POLICY_MANAGER,
PRIMITIVE_PRICE_FEED,
VALUE_INTERPRETER
);
}
/// @notice Gets the `overridePause` variable
/// @return overridePause_ The `overridePause` variable value
function getOverridePause() external view returns (bool overridePause_) {
return overridePause;
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() external view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/vault/VaultLibBase1.sol";
import "./IVault.sol";
/// @title VaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The per-release proxiable library contract for VaultProxy
/// @dev The difference in terminology between "asset" and "trackedAsset" is intentional.
/// A fund might actually have asset balances of un-tracked assets,
/// but only tracked assets are used in gav calculations.
/// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy)
/// from SharesTokenBase via VaultLibBase1
contract VaultLib is VaultLibBase1, IVault {
using SafeERC20 for ERC20;
// Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider:
// 1. The highest tracked assets limit ever allowed in the protocol
// 2. That the next value will need to be respected by all future releases
uint256 private constant TRACKED_ASSETS_LIMIT = 20;
modifier onlyAccessor() {
require(msg.sender == accessor, "Only the designated accessor can make this call");
_;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the account that is allowed to migrate a fund to new releases
/// @param _nextMigrator The account to set as the allowed migrator
/// @dev Set to address(0) to remove the migrator.
function setMigrator(address _nextMigrator) external {
require(msg.sender == owner, "setMigrator: Only the owner can call this function");
address prevMigrator = migrator;
require(_nextMigrator != prevMigrator, "setMigrator: Value already set");
migrator = _nextMigrator;
emit MigratorSet(prevMigrator, _nextMigrator);
}
///////////
// VAULT //
///////////
/// @notice Adds a tracked asset to the fund
/// @param _asset The asset to add
/// @dev Allows addition of already tracked assets to fail silently.
function addTrackedAsset(address _asset) external override onlyAccessor {
if (!isTrackedAsset(_asset)) {
require(
trackedAssets.length < TRACKED_ASSETS_LIMIT,
"addTrackedAsset: Limit exceeded"
);
assetToIsTracked[_asset] = true;
trackedAssets.push(_asset);
emit TrackedAssetAdded(_asset);
}
}
/// @notice Grants an allowance to a spender to use the fund's asset
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function approveAssetSpender(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).approve(_target, _amount);
}
/// @notice Makes an arbitrary call with this contract as the sender
/// @param _contract The contract to call
/// @param _callData The call data for the call
function callOnContract(address _contract, bytes calldata _callData)
external
override
onlyAccessor
{
(bool success, bytes memory returnData) = _contract.call(_callData);
require(success, string(returnData));
}
/// @notice Removes a tracked asset from the fund
/// @param _asset The asset to remove
function removeTrackedAsset(address _asset) external override onlyAccessor {
__removeTrackedAsset(_asset);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function withdrawAssetTo(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).safeTransfer(_target, _amount);
emit AssetWithdrawn(_asset, _target, _amount);
}
/// @dev Helper to the get the Vault's balance of a given asset
function __getAssetBalance(address _asset) private view returns (uint256 balance_) {
return ERC20(_asset).balanceOf(address(this));
}
/// @dev Helper to remove an asset from a fund's tracked assets.
/// Allows removal of non-tracked asset to fail silently.
function __removeTrackedAsset(address _asset) private {
if (isTrackedAsset(_asset)) {
assetToIsTracked[_asset] = false;
uint256 trackedAssetsCount = trackedAssets.length;
for (uint256 i = 0; i < trackedAssetsCount; i++) {
if (trackedAssets[i] == _asset) {
if (i < trackedAssetsCount - 1) {
trackedAssets[i] = trackedAssets[trackedAssetsCount - 1];
}
trackedAssets.pop();
break;
}
}
emit TrackedAssetRemoved(_asset);
}
}
////////////
// SHARES //
////////////
/// @notice Burns fund shares from a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function burnShares(address _target, uint256 _amount) external override onlyAccessor {
__burn(_target, _amount);
}
/// @notice Mints fund shares to a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to mint
function mintShares(address _target, uint256 _amount) external override onlyAccessor {
__mint(_target, _amount);
}
/// @notice Transfers fund shares from one account to another
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function transferShares(
address _from,
address _to,
uint256 _amount
) external override onlyAccessor {
__transfer(_from, _to, _amount);
}
// ERC20 overrides
/// @dev Disallows the standard ERC20 approve() function
function approve(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @notice Gets the `symbol` value of the shares token
/// @return symbol_ The `symbol` value
/// @dev Defers the shares symbol value to the Dispatcher contract
function symbol() public view override returns (string memory symbol_) {
return IDispatcher(creator).getSharesTokenSymbol();
}
/// @dev Disallows the standard ERC20 transfer() function
function transfer(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @dev Disallows the standard ERC20 transferFrom() function
function transferFrom(
address,
address,
uint256
) public override returns (bool) {
revert("Unimplemented");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `accessor` variable
/// @return accessor_ The `accessor` variable value
function getAccessor() external view override returns (address accessor_) {
return accessor;
}
/// @notice Gets the `creator` variable
/// @return creator_ The `creator` variable value
function getCreator() external view returns (address creator_) {
return creator;
}
/// @notice Gets the `migrator` variable
/// @return migrator_ The `migrator` variable value
function getMigrator() external view returns (address migrator_) {
return migrator;
}
/// @notice Gets the `owner` variable
/// @return owner_ The `owner` variable value
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the `trackedAssets` variable
/// @return trackedAssets_ The `trackedAssets` variable value
function getTrackedAssets() external view override returns (address[] memory trackedAssets_) {
return trackedAssets;
}
/// @notice Check whether an address is a tracked asset of the fund
/// @param _asset The address to check
/// @return isTrackedAsset_ True if the address is a tracked asset of the fund
function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) {
return assetToIsTracked[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../price-feeds/primitives/IPrimitivePriceFeed.sol";
import "./IValueInterpreter.sol";
/// @title ValueInterpreter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Interprets price feeds to provide covert value between asset pairs
/// @dev This contract contains several "live" value calculations, which for this release are simply
/// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink)
/// is immutable in this contract and only has one type of value. Including the "live" versions of
/// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies)
/// to explicitly define the types of values that they should (and will) be using in a future release.
contract ValueInterpreter is IValueInterpreter {
using SafeMath for uint256;
address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED;
address private immutable PRIMITIVE_PRICE_FEED;
constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public {
AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
// EXTERNAL FUNCTIONS
/// @notice An alias of calcCanonicalAssetsTotalValue
function calcLiveAssetsTotalValue(
address[] calldata _baseAssets,
uint256[] calldata _amounts,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset);
}
/// @notice An alias of calcCanonicalAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the total value of given amounts of assets in a single quote asset
/// @param _baseAssets The assets to convert
/// @param _amounts The amounts of the _baseAssets to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetsTotalValue(
address[] memory _baseAssets,
uint256[] memory _amounts,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
require(
_baseAssets.length == _amounts.length,
"calcCanonicalAssetsTotalValue: Arrays unequal lengths"
);
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetsTotalValue: Unsupported _quoteAsset"
);
isValid_ = true;
for (uint256 i; i < _baseAssets.length; i++) {
(uint256 assetValue, bool assetValueIsValid) = __calcAssetValue(
_baseAssets[i],
_amounts[i],
_quoteAsset
);
value_ = value_.add(assetValue);
if (!assetValueIsValid) {
isValid_ = false;
}
}
return (value_, isValid_);
}
/// @notice Calculates the value of a given amount of one asset in terms of another asset
/// @param _baseAsset The asset from which to convert
/// @param _amount The amount of the _baseAsset to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The equivalent quantity in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetValue: Unsupported _quoteAsset"
);
return __calcAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PRIVATE FUNCTIONS
/// @dev Helper to differentially calculate an asset value
/// based on if it is a primitive or derivative asset.
function __calcAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
// Handle case that asset is a primitive
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue(
_baseAsset,
_amount,
_quoteAsset
);
}
// Handle case that asset is a derivative
address derivativePriceFeed = IAggregatedDerivativePriceFeed(
AGGREGATED_DERIVATIVE_PRICE_FEED
)
.getPriceFeedForDerivative(_baseAsset);
if (derivativePriceFeed != address(0)) {
return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset);
}
revert("__calcAssetValue: Unsupported _baseAsset");
}
/// @dev Helper to calculate the value of a derivative in an arbitrary asset.
/// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens).
/// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP)
function __calcDerivativeValue(
address _derivativePriceFeed,
address _derivative,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
(address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed(
_derivativePriceFeed
)
.calcUnderlyingValues(_derivative, _amount);
require(underlyings.length > 0, "__calcDerivativeValue: No underlyings");
require(
underlyings.length == underlyingAmounts.length,
"__calcDerivativeValue: Arrays unequal lengths"
);
// Let validity be negated if any of the underlying value calculations are invalid
isValid_ = true;
for (uint256 i = 0; i < underlyings.length; i++) {
(uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue(
underlyings[i],
underlyingAmounts[i],
_quoteAsset
);
if (!underlyingValueIsValid) {
isValid_ = false;
}
value_ = value_.add(underlyingValue);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable
/// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value
function getAggregatedDerivativePriceFeed()
external
view
returns (address aggregatedDerivativePriceFeed_)
{
return AGGREGATED_DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {
Continuous,
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreRedeemShares
}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IPrimitivePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for primitive price feeds
interface IPrimitivePriceFeed {
function calcCanonicalValue(
address,
uint256,
address
) external view returns (uint256, bool);
function calcLiveValue(
address,
uint256,
address
) external view returns (uint256, bool);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
function calcLiveAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcLiveAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../interfaces/ISynthetixAddressResolver.sol";
import "../interfaces/ISynthetixExchanger.sol";
/// @title AssetFinalityResolver Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that helps achieve asset finality
abstract contract AssetFinalityResolver {
address internal immutable SYNTHETIX_ADDRESS_RESOLVER;
address internal immutable SYNTHETIX_PRICE_FEED;
constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public {
SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
}
/// @dev Helper to finalize a Synth balance at a given target address and return its balance
function __finalizeIfSynthAndGetAssetBalance(
address _target,
address _asset,
bool _requireFinality
) internal returns (uint256 assetBalance_) {
bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth(
_asset
);
if (currencyKey != 0) {
address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER)
.requireAndGetAddress(
"Exchanger",
"finalizeAndGetAssetBalance: Missing Exchanger"
);
try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch {
require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth");
}
}
return ERC20(_asset).balanceOf(_target);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable
/// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value
function getSynthetixAddressResolver()
external
view
returns (address synthetixAddressResolver_)
{
return SYNTHETIX_ADDRESS_RESOLVER;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../../../../interfaces/ISynthetixAddressResolver.sol";
import "../../../../interfaces/ISynthetixExchangeRates.sol";
import "../../../../interfaces/ISynthetixProxyERC20.sol";
import "../../../../interfaces/ISynthetixSynth.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title SynthetixPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Synthetix oracles as price sources
contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event SynthAdded(address indexed synth, bytes32 currencyKey);
event SynthCurrencyKeyUpdated(
address indexed synth,
bytes32 prevCurrencyKey,
bytes32 nextCurrencyKey
);
uint256 private constant SYNTH_UNIT = 10**18;
address private immutable ADDRESS_RESOLVER;
address private immutable SUSD;
mapping(address => bytes32) private synthToCurrencyKey;
constructor(
address _dispatcher,
address _addressResolver,
address _sUSD,
address[] memory _synths
) public DispatcherOwnerMixin(_dispatcher) {
ADDRESS_RESOLVER = _addressResolver;
SUSD = _sUSD;
address[] memory sUSDSynths = new address[](1);
sUSDSynths[0] = _sUSD;
__addSynths(sUSDSynths);
__addSynths(_synths);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = SUSD;
underlyingAmounts_ = new uint256[](1);
bytes32 currencyKey = getCurrencyKeyForSynth(_derivative);
require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported");
address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress(
"ExchangeRates",
"calcUnderlyingValues: Missing ExchangeRates"
);
(uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid(
currencyKey
);
require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid");
underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return getCurrencyKeyForSynth(_asset) != 0;
}
/////////////////////
// SYNTHS REGISTRY //
/////////////////////
/// @notice Adds Synths to the price feed
/// @param _synths Synths to add
function addSynths(address[] calldata _synths) external onlyDispatcherOwner {
require(_synths.length > 0, "addSynths: Empty _synths");
__addSynths(_synths);
}
/// @notice Updates the cached currencyKey value for specified Synths
/// @param _synths Synths to update
/// @dev Anybody can call this function
function updateSynthCurrencyKeys(address[] calldata _synths) external {
require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths");
for (uint256 i; i < _synths.length; i++) {
bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]];
require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set");
bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]);
require(
nextCurrencyKey != prevCurrencyKey,
"updateSynthCurrencyKeys: Synth has correct currencyKey"
);
synthToCurrencyKey[_synths[i]] = nextCurrencyKey;
emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey);
}
}
/// @dev Helper to add Synths
function __addSynths(address[] memory _synths) private {
for (uint256 i; i < _synths.length; i++) {
require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set");
bytes32 currencyKey = __getCurrencyKey(_synths[i]);
require(currencyKey != 0, "__addSynths: No currencyKey");
synthToCurrencyKey[_synths[i]] = currencyKey;
emit SynthAdded(_synths[i], currencyKey);
}
}
/// @dev Helper to query a currencyKey from Synthetix
function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) {
return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_RESOLVER` variable
/// @return addressResolver_ The `ADDRESS_RESOLVER` variable value
function getAddressResolver() external view returns (address) {
return ADDRESS_RESOLVER;
}
/// @notice Gets the currencyKey for multiple given Synths
/// @return currencyKeys_ The currencyKey values
function getCurrencyKeysForSynths(address[] calldata _synths)
external
view
returns (bytes32[] memory currencyKeys_)
{
currencyKeys_ = new bytes32[](_synths.length);
for (uint256 i; i < _synths.length; i++) {
currencyKeys_[i] = synthToCurrencyKey[_synths[i]];
}
return currencyKeys_;
}
/// @notice Gets the `SUSD` variable
/// @return susd_ The `SUSD` variable value
function getSUSD() external view returns (address susd_) {
return SUSD;
}
/// @notice Gets the currencyKey for a given Synth
/// @return currencyKey_ The currencyKey value
function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) {
return synthToCurrencyKey[_synth];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixAddressResolver Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixAddressResolver {
function requireAndGetAddress(bytes32, string calldata) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchanger Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchanger {
function getAmountsForExchange(
uint256,
bytes32,
bytes32
)
external
view
returns (
uint256,
uint256,
uint256
);
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetix Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetix {
function exchangeOnBehalfWithTracking(
address,
bytes32,
uint256,
bytes32,
address,
bytes32
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchangeRates Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchangeRates {
function rateAndInvalid(bytes32) external view returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixProxyERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixProxyERC20 {
function target() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixSynth Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixSynth {
function currencyKey() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../persistent/dispatcher/IDispatcher.sol";
/// @title DispatcherOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of Dispatcher
abstract contract DispatcherOwnerMixin {
address internal immutable DISPATCHER;
modifier onlyDispatcherOwner() {
require(
msg.sender == getOwner(),
"onlyDispatcherOwner: Only the Dispatcher owner can call this function"
);
_;
}
constructor(address _dispatcher) public {
DISPATCHER = _dispatcher;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the Dispatcher contract
function getOwner() public view returns (address owner_) {
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibBaseCore.sol";
/// @title VaultLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice The first implementation of VaultLibBaseCore, with additional events and storage
/// @dev All subsequent implementations should inherit the previous implementation,
/// e.g., `VaultLibBase2 is VaultLibBase1`
/// DO NOT EDIT CONTRACT.
abstract contract VaultLibBase1 is VaultLibBaseCore {
event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount);
event TrackedAssetAdded(address asset);
event TrackedAssetRemoved(address asset);
address[] internal trackedAssets;
mapping(address => bool) internal assetToIsTracked;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigratableVault.sol";
import "./utils/ProxiableVaultLib.sol";
import "./utils/SharesTokenBase.sol";
/// @title VaultLibBaseCore Contract
/// @author Enzyme Council <[email protected]>
/// @notice A persistent contract containing all required storage variables and
/// required functions for a VaultLib implementation
/// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to
/// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1.
abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase {
event AccessorSet(address prevAccessor, address nextAccessor);
event MigratorSet(address prevMigrator, address nextMigrator);
event OwnerSet(address prevOwner, address nextOwner);
event VaultLibSet(address prevVaultLib, address nextVaultLib);
address internal accessor;
address internal creator;
address internal migrator;
address internal owner;
// EXTERNAL FUNCTIONS
/// @notice Initializes the VaultProxy with core configuration
/// @param _owner The address to set as the fund owner
/// @param _accessor The address to set as the permissioned accessor of the VaultLib
/// @param _fundName The name of the fund
/// @dev Serves as a per-proxy pseudo-constructor
function init(
address _owner,
address _accessor,
string calldata _fundName
) external override {
require(creator == address(0), "init: Proxy already initialized");
creator = msg.sender;
sharesName = _fundName;
__setAccessor(_accessor);
__setOwner(_owner);
emit VaultLibSet(address(0), getVaultLib());
}
/// @notice Sets the permissioned accessor of the VaultLib
/// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib
function setAccessor(address _nextAccessor) external override {
require(msg.sender == creator, "setAccessor: Only callable by the contract creator");
__setAccessor(_nextAccessor);
}
/// @notice Sets the VaultLib target for the VaultProxy
/// @param _nextVaultLib The address to set as the VaultLib
/// @dev This function is absolutely critical. __updateCodeAddress() validates that the
/// target is a valid Proxiable contract instance.
/// Does not block _nextVaultLib from being the same as the current VaultLib
function setVaultLib(address _nextVaultLib) external override {
require(msg.sender == creator, "setVaultLib: Only callable by the contract creator");
address prevVaultLib = getVaultLib();
__updateCodeAddress(_nextVaultLib);
emit VaultLibSet(prevVaultLib, _nextVaultLib);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an account is allowed to migrate the VaultProxy
/// @param _who The account to check
/// @return canMigrate_ True if the account is allowed to migrate the VaultProxy
function canMigrate(address _who) public view virtual override returns (bool canMigrate_) {
return _who == owner || _who == migrator;
}
/// @notice Gets the VaultLib target for the VaultProxy
/// @return vaultLib_ The address of the VaultLib target
function getVaultLib() public view returns (address vaultLib_) {
assembly {
// solium-disable-line
vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
return vaultLib_;
}
// INTERNAL FUNCTIONS
/// @dev Helper to set the permissioned accessor of the VaultProxy.
/// Does not prevent the prevAccessor from being the _nextAccessor.
function __setAccessor(address _nextAccessor) internal {
require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty");
address prevAccessor = accessor;
accessor = _nextAccessor;
emit AccessorSet(prevAccessor, _nextAccessor);
}
/// @dev Helper to set the owner of the VaultProxy
function __setOwner(address _nextOwner) internal {
require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty");
address prevOwner = owner;
require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner");
owner = _nextOwner;
emit OwnerSet(prevOwner, _nextOwner);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ProxiableVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that defines the upgrade behavior for VaultLib instances
/// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967
/// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`,
/// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc".
abstract contract ProxiableVaultLib {
/// @dev Updates the target of the proxy to be the contract at _nextVaultLib
function __updateCodeAddress(address _nextVaultLib) internal {
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_nextVaultLib).proxiableUUID(),
"__updateCodeAddress: _nextVaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_nextVaultLib
)
}
}
/// @notice Returns a unique bytes32 hash for VaultLib instances
/// @return uuid_ The bytes32 hash representing the UUID
/// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))`
function proxiableUUID() public pure returns (bytes32 uuid_) {
return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibSafeMath.sol";
/// @title StandardERC20 Contract
/// @author Enzyme Council <[email protected]>
/// @notice Contains the storage, events, and default logic of an ERC20-compliant contract.
/// @dev The logic can be overridden by VaultLib implementations.
/// Adapted from OpenZeppelin 3.2.0.
/// DO NOT EDIT THIS CONTRACT.
abstract contract SharesTokenBase {
using VaultLibSafeMath for uint256;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
string internal sharesName;
string internal sharesSymbol;
uint256 internal sharesTotalSupply;
mapping(address => uint256) internal sharesBalances;
mapping(address => mapping(address => uint256)) internal sharesAllowances;
// EXTERNAL FUNCTIONS
/// @dev Standard implementation of ERC20's approve(). Can be overridden.
function approve(address _spender, uint256 _amount) public virtual returns (bool) {
__approve(msg.sender, _spender, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transfer(). Can be overridden.
function transfer(address _recipient, uint256 _amount) public virtual returns (bool) {
__transfer(msg.sender, _recipient, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transferFrom(). Can be overridden.
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual returns (bool) {
__transfer(_sender, _recipient, _amount);
__approve(
_sender,
msg.sender,
sharesAllowances[_sender][msg.sender].sub(
_amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
// EXTERNAL FUNCTIONS - VIEW
/// @dev Standard implementation of ERC20's allowance(). Can be overridden.
function allowance(address _owner, address _spender) public view virtual returns (uint256) {
return sharesAllowances[_owner][_spender];
}
/// @dev Standard implementation of ERC20's balanceOf(). Can be overridden.
function balanceOf(address _account) public view virtual returns (uint256) {
return sharesBalances[_account];
}
/// @dev Standard implementation of ERC20's decimals(). Can not be overridden.
function decimals() public pure returns (uint8) {
return 18;
}
/// @dev Standard implementation of ERC20's name(). Can be overridden.
function name() public view virtual returns (string memory) {
return sharesName;
}
/// @dev Standard implementation of ERC20's symbol(). Can be overridden.
function symbol() public view virtual returns (string memory) {
return sharesSymbol;
}
/// @dev Standard implementation of ERC20's totalSupply(). Can be overridden.
function totalSupply() public view virtual returns (uint256) {
return sharesTotalSupply;
}
// INTERNAL FUNCTIONS
/// @dev Helper for approve(). Can be overridden.
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");
sharesAllowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/// @dev Helper to burn tokens from an account. Can be overridden.
function __burn(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: burn from the zero address");
sharesBalances[_account] = sharesBalances[_account].sub(
_amount,
"ERC20: burn amount exceeds balance"
);
sharesTotalSupply = sharesTotalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/// @dev Helper to mint tokens to an account. Can be overridden.
function __mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
sharesTotalSupply = sharesTotalSupply.add(_amount);
sharesBalances[_account] = sharesBalances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/// @dev Helper to transfer tokens between accounts. Can be overridden.
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");
sharesBalances[_sender] = sharesBalances[_sender].sub(
_amount,
"ERC20: transfer amount exceeds balance"
);
sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title VaultLibSafeMath library
/// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath
/// for use with VaultLib
/// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons
/// between VaultLib implementations
/// DO NOT EDIT THIS CONTRACT
library VaultLibSafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "VaultLibSafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "VaultLibSafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "VaultLibSafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "VaultLibSafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "VaultLibSafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IDerivativePriceFeed.sol";
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed {
function getPriceFeedForDerivative(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IUniswapV2Pair.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../../../value-interpreter/ValueInterpreter.sol";
import "../../primitives/IPrimitivePriceFeed.sol";
import "../../utils/UniswapV2PoolTokenValueCalculator.sol";
import "../IDerivativePriceFeed.sol";
/// @title UniswapV2PoolPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Uniswap lending pool tokens
contract UniswapV2PoolPriceFeed is
IDerivativePriceFeed,
DispatcherOwnerMixin,
MathHelpers,
UniswapV2PoolTokenValueCalculator
{
event PoolTokenAdded(address indexed poolToken, address token0, address token1);
struct PoolTokenInfo {
address token0;
address token1;
uint8 token0Decimals;
uint8 token1Decimals;
}
uint256 private constant POOL_TOKEN_UNIT = 10**18;
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable FACTORY;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable VALUE_INTERPRETER;
mapping(address => PoolTokenInfo) private poolTokenToInfo;
constructor(
address _dispatcher,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _valueInterpreter,
address _factory,
address[] memory _poolTokens
) public DispatcherOwnerMixin(_dispatcher) {
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
FACTORY = _factory;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
VALUE_INTERPRETER = _valueInterpreter;
__addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative];
underlyings_ = new address[](2);
underlyings_[0] = poolTokenInfo.token0;
underlyings_[1] = poolTokenInfo.token1;
// Calculate the amounts underlying one unit of a pool token,
// taking into account the known, trusted rate between the two underlyings
(uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate(
poolTokenInfo.token0,
poolTokenInfo.token1,
poolTokenInfo.token0Decimals,
poolTokenInfo.token1Decimals
);
(
uint256 token0DenormalizedRate,
uint256 token1DenormalizedRate
) = __calcTrustedPoolTokenValue(
FACTORY,
_derivative,
token0TrustedRateAmount,
token1TrustedRateAmount
);
// Define normalized rates for each underlying
underlyingAmounts_ = new uint256[](2);
underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT);
underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return poolTokenToInfo[_asset].token0 != address(0);
}
// PRIVATE FUNCTIONS
/// @dev Calculates the trusted rate of two assets based on our price feeds.
/// Uses the decimals-derived unit for whichever asset is used as the quote asset.
function __calcTrustedRate(
address _token0,
address _token1,
uint256 _token0Decimals,
uint256 _token1Decimals
) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) {
bool rateIsValid;
// The quote asset of the value lookup must be a supported primitive asset,
// so we cycle through the tokens until reaching a primitive.
// If neither is a primitive, will revert at the ValueInterpreter
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) {
token1RateAmount_ = 10**_token1Decimals;
(token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token1, token1RateAmount_, _token0);
} else {
token0RateAmount_ = 10**_token0Decimals;
(token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token0, token0RateAmount_, _token1);
}
require(rateIsValid, "__calcTrustedRate: Invalid rate");
return (token0RateAmount_, token1RateAmount_);
}
//////////////////////////
// POOL TOKENS REGISTRY //
//////////////////////////
/// @notice Adds Uniswap pool tokens to the price feed
/// @param _poolTokens Uniswap pool tokens to add
function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner {
require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens");
__addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED);
}
/// @dev Helper to add Uniswap pool tokens
function __addPoolTokens(
address[] memory _poolTokens,
address _derivativePriceFeed,
address _primitivePriceFeed
) private {
for (uint256 i; i < _poolTokens.length; i++) {
require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken");
require(
poolTokenToInfo[_poolTokens[i]].token0 == address(0),
"__addPoolTokens: Value already set"
);
IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]);
address token0 = uniswapV2Pair.token0();
address token1 = uniswapV2Pair.token1();
require(
__poolTokenIsSupportable(
_derivativePriceFeed,
_primitivePriceFeed,
token0,
token1
),
"__addPoolTokens: Unsupported pool token"
);
poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({
token0: token0,
token1: token1,
token0Decimals: ERC20(token0).decimals(),
token1Decimals: ERC20(token1).decimals()
});
emit PoolTokenAdded(_poolTokens[i], token0, token1);
}
}
/// @dev Helper to determine if a pool token is supportable, based on whether price feeds are
/// available for its underlying feeds. At least one of the underlying tokens must be
/// a supported primitive asset, and the other must be a primitive or derivative.
function __poolTokenIsSupportable(
address _derivativePriceFeed,
address _primitivePriceFeed,
address _token0,
address _token1
) private view returns (bool isSupportable_) {
IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed(
_derivativePriceFeed
);
IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed);
if (primitivePriceFeedContract.isSupportedAsset(_token0)) {
if (
primitivePriceFeedContract.isSupportedAsset(_token1) ||
derivativePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
} else if (
derivativePriceFeedContract.isSupportedAsset(_token0) &&
primitivePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
return false;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `FACTORY` variable value
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `PoolTokenInfo` for a given pool token
/// @param _poolToken The pool token for which to get the `PoolTokenInfo`
/// @return poolTokenInfo_ The `PoolTokenInfo` value
function getPoolTokenInfo(address _poolToken)
external
view
returns (PoolTokenInfo memory poolTokenInfo_)
{
return poolTokenToInfo[_poolToken];
}
/// @notice Gets the underlyings for a given pool token
/// @param _poolToken The pool token for which to get its underlyings
/// @return token0_ The UniswapV2Pair.token0 value
/// @return token1_ The UniswapV2Pair.token1 value
function getPoolTokenUnderlyings(address _poolToken)
external
view
returns (address token0_, address token1_)
{
return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1);
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets the `VALUE_INTERPRETER` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Pair Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract
interface IUniswapV2Pair {
function getReserves()
external
view
returns (
uint112,
uint112,
uint32
);
function kLast() external view returns (uint256);
function token0() external view returns (address);
function token1() external view returns (address);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../interfaces/IUniswapV2Factory.sol";
import "../../../interfaces/IUniswapV2Pair.sol";
/// @title UniswapV2PoolTokenValueCalculator Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens
/// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from
/// an un-merged Uniswap branch:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol
abstract contract UniswapV2PoolTokenValueCalculator {
using SafeMath for uint256;
uint256 private constant POOL_TOKEN_UNIT = 10**18;
// INTERNAL FUNCTIONS
/// @dev Given a Uniswap pool with token0 and token1 and their trusted rate,
/// returns the value of one pool token unit in terms of token0 and token1.
/// This is the only function used outside of this contract.
function __calcTrustedPoolTokenValue(
address _factory,
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) internal view returns (uint256 token0Amount_, uint256 token1Amount_) {
(uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage(
_pair,
_token0TrustedRateAmount,
_token1TrustedRateAmount
);
return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1);
}
// PRIVATE FUNCTIONS
/// @dev Computes liquidity value given all the parameters of the pair
function __calcPoolTokenValue(
address _factory,
address _pair,
uint256 _reserve0,
uint256 _reserve1
) private view returns (uint256 token0Amount_, uint256 token1Amount_) {
IUniswapV2Pair pairContract = IUniswapV2Pair(_pair);
uint256 totalSupply = pairContract.totalSupply();
if (IUniswapV2Factory(_factory).feeTo() != address(0)) {
uint256 kLast = pairContract.kLast();
if (kLast > 0) {
uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1));
uint256 rootKLast = __uniswapSqrt(kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 feeLiquidity = numerator.div(denominator);
totalSupply = totalSupply.add(feeLiquidity);
}
}
}
return (
_reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply),
_reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply)
);
}
/// @dev Calculates the direction and magnitude of the profit-maximizing trade
function __calcProfitMaximizingTrade(
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount,
uint256 _reserve0,
uint256 _reserve1
) private pure returns (bool token0ToToken1_, uint256 amountIn_) {
token0ToToken1_ =
_reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount;
uint256 leftSide;
uint256 rightSide;
if (token0ToToken1_) {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div(
_token1TrustedRateAmount.mul(997)
)
);
rightSide = _reserve0.mul(1000).div(997);
} else {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div(
_token0TrustedRateAmount.mul(997)
)
);
rightSide = _reserve1.mul(1000).div(997);
}
if (leftSide < rightSide) {
return (false, 0);
}
// Calculate the amount that must be sent to move the price to the profit-maximizing price
amountIn_ = leftSide.sub(rightSide);
return (token0ToToken1_, amountIn_);
}
/// @dev Calculates the pool reserves after an arbitrage moves the price to
/// the profit-maximizing rate, given an externally-observed trusted rate
/// between the two pooled assets
function __calcReservesAfterArbitrage(
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) private view returns (uint256 reserve0_, uint256 reserve1_) {
(reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves();
// Skip checking whether the reserve is 0, as this is extremely unlikely given how
// initial pool liquidity is locked, and since we maintain a list of registered pool tokens
// Calculate how much to swap to arb to the trusted price
(bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade(
_token0TrustedRateAmount,
_token1TrustedRateAmount,
reserve0_,
reserve1_
);
if (amountIn == 0) {
return (reserve0_, reserve1_);
}
// Adjust the reserves to account for the arb trade to the trusted price
if (token0ToToken1) {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_);
reserve0_ = reserve0_.add(amountIn);
reserve1_ = reserve1_.sub(amountOut);
} else {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_);
reserve1_ = reserve1_.add(amountIn);
reserve0_ = reserve0_.sub(amountOut);
}
return (reserve0_, reserve1_);
}
/// @dev Uniswap square root function. See:
/// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol
function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) {
if (_y > 3) {
z_ = _y;
uint256 x = _y / 2 + 1;
while (x < z_) {
z_ = x;
x = (_y / x + x) / 2;
}
} else if (_y != 0) {
z_ = 1;
}
// else z_ = 0
return z_;
}
/// @dev Simplified version of UniswapV2Library's getAmountOut() function. See:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50
function __uniswapV2GetAmountOut(
uint256 _amountIn,
uint256 _reserveIn,
uint256 _reserveOut
) private pure returns (uint256 amountOut_) {
uint256 amountInWithFee = _amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(_reserveOut);
uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee);
return numerator.div(denominator);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Factory Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract
interface IUniswapV2Factory {
function feeTo() external view returns (address);
function getPair(address, address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IChainlinkAggregator.sol";
import "../../../../utils/MakerDaoMath.sol";
import "../IDerivativePriceFeed.sol";
/// @title WdgldPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for WDGLD <https://dgld.ch/>
contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath {
using SafeMath for uint256;
address private immutable XAU_AGGREGATOR;
address private immutable ETH_AGGREGATOR;
address private immutable WDGLD;
address private immutable WETH;
// GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas
uint256 private constant GTR_CONSTANT = 999990821653213975346065101;
uint256 private constant GTR_PRECISION = 10**27;
uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000;
constructor(
address _wdgld,
address _weth,
address _ethAggregator,
address _xauAggregator
) public {
WDGLD = _wdgld;
WETH = _weth;
ETH_AGGREGATOR = _ethAggregator;
XAU_AGGREGATOR = _xauAggregator;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH;
underlyingAmounts_ = new uint256[](1);
// Get price rates from xau and eth aggregators
int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer();
int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer();
require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid");
uint256 wdgldToXauRate = calcWdgldToXauRate();
// 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION
underlyingAmounts_[0] = _derivativeAmount
.mul(wdgldToXauRate)
.mul(uint256(xauToUsdRate))
.div(uint256(ethToUsdRate))
.div(10**17);
return (underlyings_, underlyingAmounts_);
}
/// @notice Calculates the rate of WDGLD to XAU.
/// @return wdgldToXauRate_ The current rate of WDGLD to XAU
/// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf>
function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) {
return
__rpow(
GTR_CONSTANT,
((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods)
GTR_PRECISION
)
.div(10);
}
/// @notice Checks if an asset is supported by this price feed
/// @param _asset The asset to check
/// @return isSupported_ True if supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == WDGLD;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ETH_AGGREGATOR` address
/// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address
function getEthAggregator() external view returns (address ethAggregatorAddress_) {
return ETH_AGGREGATOR;
}
/// @notice Gets the `WDGLD` token address
/// @return wdgld_ The `WDGLD` token address
function getWdgld() external view returns (address wdgld_) {
return WDGLD;
}
/// @notice Gets the `WETH` token address
/// @return weth_ The `WETH` token address
function getWeth() external view returns (address weth_) {
return WETH;
}
/// @notice Gets the `XAU_AGGREGATOR` address
/// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address
function getXauAggregator() external view returns (address xauAggregatorAddress_) {
return XAU_AGGREGATOR;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IChainlinkAggregator Interface
/// @author Enzyme Council <[email protected]>
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2018 Rain <[email protected]>
//
// 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.6.12;
/// @title MakerDaoMath Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for math operations adapted from MakerDao contracts
abstract contract MakerDaoMath {
/// @dev Performs scaled, fixed-point exponentiation.
/// Verbatim code, adapted to our style guide for variable naming only, see:
/// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105
// prettier-ignore
function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) {
assembly {
switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}}
default {
switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x }
let half := div(_base, 2)
for { _n := div(_n, 2) } _n { _n := div(_n,2) } {
let xx := mul(_x, _x)
if iszero(eq(div(xx, _x), _x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
_x := div(xxRound, _base)
if mod(_n,2) {
let zx := mul(z_, _x)
if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z_ := div(zxRound, _base)
}
}
}
}
return z_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../core/fund/vault/VaultLib.sol";
import "../../../utils/MakerDaoMath.sol";
import "./utils/FeeBase.sol";
/// @title ManagementFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A management fee with a configurable annual rate
contract ManagementFee is FeeBase, MakerDaoMath {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate);
event Settled(
address indexed comptrollerProxy,
uint256 sharesQuantity,
uint256 secondsSinceSettlement
);
struct FeeInfo {
uint256 scaledPerSecondRate;
uint256 lastSettled;
}
uint256 private constant RATE_SCALE_BASE = 10**27;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyFeeManager
{
// It is only necessary to set `lastSettled` for a migrated fund
if (VaultLib(_vaultProxy).totalSupply() > 0) {
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
}
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the fee for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256));
require(
scaledPerSecondRate > 0,
"addFundSettings: scaledPerSecondRate must be greater than 0"
);
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
scaledPerSecondRate: scaledPerSecondRate,
lastSettled: 0
});
emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "MANAGEMENT";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settle the fee and calculate shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// If this fee was settled in the current block, we can return early
uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled);
if (secondsSinceSettlement == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
// If there are shares issued for the fund, calculate the shares due
VaultLib vaultProxyContract = VaultLib(_vaultProxy);
uint256 sharesSupply = vaultProxyContract.totalSupply();
if (sharesSupply > 0) {
// This assumes that all shares in the VaultProxy are shares outstanding,
// which is fine for this release. Even if they are not, they are still shares that
// are only claimable by the fund owner.
uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy));
if (netSharesSupply > 0) {
sharesDue_ = netSharesSupply
.mul(
__rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE)
.sub(RATE_SCALE_BASE)
)
.div(RATE_SCALE_BASE);
}
}
// Must settle even when no shares are due, for the case that settlement is being
// done when there are no shares in the fund (i.e. at the first investment, or at the
// first investment after all shares have been redeemed)
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement);
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
return (IFeeManager.SettlementType.Mint, address(0), sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IFee.sol";
/// @title FeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all fees
abstract contract FeeBase is IFee {
address internal immutable FEE_MANAGER;
modifier onlyFeeManager {
require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call");
_;
}
constructor(address _feeManager) public {
FEE_MANAGER = _feeManager;
}
/// @notice Allows Fee to run logic during fund activation
/// @dev Unimplemented by default, may be overrode.
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type
/// @dev Returns false by default, can be overridden by fee
function payout(address, address) external virtual override returns (bool) {
return false;
}
/// @notice Update fee state after all settlement has occurred during a given fee hook
/// @dev Unimplemented by default, can be overridden by fee
function update(
address,
address,
IFeeManager.FeeHook,
bytes calldata,
uint256
) external virtual override {
return;
}
/// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook
function __decodePreBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook
function __decodePreRedeemSharesSettlementData(bytes memory _settlementData)
internal
pure
returns (address redeemer_, uint256 sharesQuantity_)
{
return abi.decode(_settlementData, (address, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook
function __decodePostBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 sharesBought_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IFeeManager.sol";
/// @title Fee Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all fees
interface IFee {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
);
function payout(address _comptrollerProxy, address _vaultProxy)
external
returns (bool isPayable_);
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
)
external
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
);
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../core/fund/comptroller/ComptrollerLib.sol";
import "../FeeManager.sol";
import "./utils/FeeBase.sol";
/// @title PerformanceFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A performance-based fee with configurable rate and crystallization period, using
/// a high watermark
/// @dev This contract assumes that all shares in the VaultProxy are shares outstanding,
/// which is fine for this release. Even if they are not, they are still shares that
/// are only claimable by the fund owner.
contract PerformanceFee is FeeBase {
using SafeMath for uint256;
using SignedSafeMath for int256;
event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark);
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period);
event LastSharePriceUpdated(
address indexed comptrollerProxy,
uint256 prevSharePrice,
uint256 nextSharePrice
);
event PaidOut(
address indexed comptrollerProxy,
uint256 prevHighWaterMark,
uint256 nextHighWaterMark,
uint256 aggregateValueDue
);
event PerformanceUpdated(
address indexed comptrollerProxy,
uint256 prevAggregateValueDue,
uint256 nextAggregateValueDue,
int256 sharesOutstandingDiff
);
struct FeeInfo {
uint256 rate;
uint256 period;
uint256 activated;
uint256 lastPaid;
uint256 highWaterMark;
uint256 lastSharePrice;
uint256 aggregateValueDue;
}
uint256 private constant RATE_DIVISOR = 10**18;
uint256 private constant SHARE_UNIT = 10**18;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager {
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// We must not force asset finality, otherwise funds that have Synths as tracked assets
// would be susceptible to a DoS attack when attempting to migrate to a release that uses
// this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy
// as the recipient, thus causing `calcGrossShareValue(true)` to fail.
(uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy)
.calcGrossShareValue(false);
require(sharePriceIsValid, "activateForFund: Invalid share price");
feeInfo.highWaterMark = grossSharePrice;
feeInfo.lastSharePrice = grossSharePrice;
feeInfo.activated = block.timestamp;
emit ActivatedForFund(_comptrollerProxy, grossSharePrice);
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for the fund
/// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
(uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256));
require(feeRate > 0, "addFundSettings: feeRate must be greater than 0");
require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0");
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
rate: feeRate,
period: feePeriod,
activated: 0,
lastPaid: 0,
highWaterMark: 0,
lastSharePrice: 0,
aggregateValueDue: 0
});
emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PERFORMANCE";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3);
implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted;
implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true);
}
/// @notice Checks whether the shares outstanding for the fee can be paid out, and updates
/// the info for the fee's last payout
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return isPayable_ True if shares outstanding can be paid out
function payout(address _comptrollerProxy, address)
external
override
onlyFeeManager
returns (bool isPayable_)
{
if (!payoutAllowed(_comptrollerProxy)) {
return false;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
feeInfo.lastPaid = block.timestamp;
uint256 prevHighWaterMark = feeInfo.highWaterMark;
uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark);
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
// Update state as necessary
if (prevAggregateValueDue > 0) {
feeInfo.aggregateValueDue = 0;
}
if (nextHighWaterMark > prevHighWaterMark) {
feeInfo.highWaterMark = nextHighWaterMark;
}
emit PaidOut(
_comptrollerProxy,
prevHighWaterMark,
nextHighWaterMark,
prevAggregateValueDue
);
return true;
}
/// @notice Settles the fee and calculates shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _gav The GAV of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256 _gav
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
if (_gav == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
int256 settlementSharesDue = __settleAndUpdatePerformance(
_comptrollerProxy,
_vaultProxy,
_gav
);
if (settlementSharesDue == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
} else if (settlementSharesDue > 0) {
// Settle by minting shares outstanding for custody
return (
IFeeManager.SettlementType.MintSharesOutstanding,
address(0),
uint256(settlementSharesDue)
);
} else {
// Settle by burning from shares outstanding
return (
IFeeManager.SettlementType.BurnSharesOutstanding,
address(0),
uint256(-settlementSharesDue)
);
}
}
/// @notice Updates the fee state after all fees have finished settle()
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _hook The FeeHook being executed
/// @param _settlementData Encoded args to use in calculating the settlement
/// @param _gav The GAV of the fund
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override onlyFeeManager {
uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice;
uint256 nextSharePrice = __calcNextSharePrice(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (nextSharePrice == prevSharePrice) {
return;
}
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice;
emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether the shares outstanding can be paid out
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return payoutAllowed_ True if the fee payment is due
/// @dev Payout is allowed if fees have not yet been settled in a crystallization period,
/// and at least 1 crystallization period has passed since activation
function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) {
FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 period = feeInfo.period;
uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated);
// Check if at least 1 crystallization period has passed since activation
if (timeSinceActivated < period) {
return false;
}
// Check that a full crystallization period has passed since the last payout
uint256 timeSincePeriodStart = timeSinceActivated % period;
uint256 periodStart = block.timestamp.sub(timeSincePeriodStart);
return feeInfo.lastPaid < periodStart;
}
// PRIVATE FUNCTIONS
/// @dev Helper to calculate the aggregated value accumulated to a fund since the last
/// settlement (happening at investment/redemption)
/// Validated:
/// _netSharesSupply > 0
/// _sharePriceWithoutPerformance != _prevSharePrice
function __calcAggregateValueDue(
uint256 _netSharesSupply,
uint256 _sharePriceWithoutPerformance,
uint256 _prevSharePrice,
uint256 _prevAggregateValueDue,
uint256 _feeRate,
uint256 _highWaterMark
) private pure returns (uint256) {
int256 superHWMValueSinceLastSettled = (
int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub(
int256(__calcUint256Max(_highWaterMark, _prevSharePrice))
)
)
.mul(int256(_netSharesSupply))
.div(int256(SHARE_UNIT));
int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div(
int256(RATE_DIVISOR)
);
return
uint256(
__calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled))
);
}
/// @dev Helper to calculate the max of two int values
function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to calculate the next `lastSharePrice` value
function __calcNextSharePrice(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private view returns (uint256 nextSharePrice_) {
uint256 denominationAssetUnit = 10 **
uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals());
if (_gav == 0) {
return denominationAssetUnit;
}
// Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply
ERC20 vaultProxyContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = vaultProxyContract.totalSupply();
uint256 nextNetSharesSupply = totalSharesSupply.sub(
vaultProxyContract.balanceOf(_vaultProxy)
);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
uint256 nextGav = _gav;
// For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change,
// we only need additional calculations for PreRedeemShares
if (_hook == IFeeManager.FeeHook.PreRedeemShares) {
(, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData);
// Shares have not yet been burned
nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
// Assets have not yet been withdrawn
uint256 gavDecrease = sharesDecrease
.mul(_gav)
.mul(SHARE_UNIT)
.div(totalSharesSupply)
.div(denominationAssetUnit);
nextGav = nextGav.sub(gavDecrease);
if (nextGav == 0) {
return denominationAssetUnit;
}
}
return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply);
}
/// @dev Helper to calculate the performance metrics for a fund.
/// Validated:
/// _totalSharesSupply > 0
/// _gav > 0
/// _totalSharesSupply != _totalSharesOutstanding
function __calcPerformance(
address _comptrollerProxy,
uint256 _totalSharesSupply,
uint256 _totalSharesOutstanding,
uint256 _prevAggregateValueDue,
FeeInfo memory feeInfo,
uint256 _gav
) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) {
// Use the 'shares supply net shares outstanding' for performance calcs.
// Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding
uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding);
uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply);
// If gross share price has not changed, can exit early
uint256 prevSharePrice = feeInfo.lastSharePrice;
if (sharePriceWithoutPerformance == prevSharePrice) {
return (_prevAggregateValueDue, 0);
}
nextAggregateValueDue_ = __calcAggregateValueDue(
netSharesSupply,
sharePriceWithoutPerformance,
prevSharePrice,
_prevAggregateValueDue,
feeInfo.rate,
feeInfo.highWaterMark
);
sharesDue_ = __calcSharesDue(
_comptrollerProxy,
netSharesSupply,
_gav,
nextAggregateValueDue_
);
return (nextAggregateValueDue_, sharesDue_);
}
/// @dev Helper to calculate sharesDue during settlement.
/// Validated:
/// _netSharesSupply > 0
/// _gav > 0
function __calcSharesDue(
address _comptrollerProxy,
uint256 _netSharesSupply,
uint256 _gav,
uint256 _nextAggregateValueDue
) private view returns (int256 sharesDue_) {
// If _nextAggregateValueDue > _gav, then no shares can be created.
// This is a known limitation of the model, which is only reached for unrealistically
// high performance fee rates (> 100%). A revert is allowed in such a case.
uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div(
_gav.sub(_nextAggregateValueDue)
);
// Shares due is the +/- diff or the total shares outstanding already minted
return
int256(sharesDueForAggregateValueDue).sub(
int256(
FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund(
_comptrollerProxy,
address(this)
)
)
);
}
/// @dev Helper to calculate the max of two uint values
function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to settle the fee and update performance state.
/// Validated:
/// _gav > 0
function __settleAndUpdatePerformance(
address _comptrollerProxy,
address _vaultProxy,
uint256 _gav
) private returns (int256 sharesDue_) {
ERC20 sharesTokenContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = sharesTokenContract.totalSupply();
if (totalSharesSupply == 0) {
return 0;
}
uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy);
if (totalSharesOutstanding == totalSharesSupply) {
return 0;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
uint256 nextAggregateValueDue;
(nextAggregateValueDue, sharesDue_) = __calcPerformance(
_comptrollerProxy,
totalSharesSupply,
totalSharesOutstanding,
prevAggregateValueDue,
feeInfo,
_gav
);
if (nextAggregateValueDue == prevAggregateValueDue) {
return 0;
}
// Update fee state
feeInfo.aggregateValueDue = nextAggregateValueDue;
emit PerformanceUpdated(
_comptrollerProxy,
prevAggregateValueDue,
nextAggregateValueDue,
sharesDue_
);
return sharesDue_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot 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-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev 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;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../../utils/AddressArrayLib.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./IFee.sol";
import "./IFeeManager.sol";
/// @title FeeManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages fees for funds
contract FeeManager is
IFeeManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AllSharesOutstandingForcePaidForFund(
address indexed comptrollerProxy,
address payee,
uint256 sharesDue
);
event FeeDeregistered(address indexed fee, string indexed identifier);
event FeeEnabledForFund(
address indexed comptrollerProxy,
address indexed fee,
bytes settingsData
);
event FeeRegistered(
address indexed fee,
string indexed identifier,
FeeHook[] implementedHooksForSettle,
FeeHook[] implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
);
event FeeSettledForFund(
address indexed comptrollerProxy,
address indexed fee,
SettlementType indexed settlementType,
address payer,
address payee,
uint256 sharesDue
);
event SharesOutstandingPaidForFund(
address indexed comptrollerProxy,
address indexed fee,
uint256 sharesDue
);
event FeesRecipientSetForFund(
address indexed comptrollerProxy,
address prevFeesRecipient,
address nextFeesRecipient
);
EnumerableSet.AddressSet private registeredFees;
mapping(address => bool) private feeToUsesGavOnSettle;
mapping(address => bool) private feeToUsesGavOnUpdate;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate;
mapping(address => address[]) private comptrollerProxyToFees;
mapping(address => mapping(address => uint256))
private comptrollerProxyToFeeToSharesOutstanding;
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Activate already-configured fees for use in the calling fund
function activateForFund(bool) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
address[] memory enabledFees = comptrollerProxyToFees[msg.sender];
for (uint256 i; i < enabledFees.length; i++) {
IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy);
}
}
/// @notice Deactivate fees for a fund
/// @dev msg.sender is validated during __invokeHook()
function deactivateForFund() external override {
// Settle continuous fees one last time, but without calling Fee.update()
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false);
// Force payout of remaining shares outstanding
__forcePayoutAllSharesOutstanding(msg.sender);
// Clean up storage
__deleteFundStorage(msg.sender);
}
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _actionId An ID representing the desired action
/// @param _callArgs Encoded arguments specific to the _actionId
/// @dev This is the only way to call a function on this contract that updates VaultProxy state.
/// For both of these actions, any caller is allowed, so we don't use the caller param.
function receiveCallFromComptroller(
address,
uint256 _actionId,
bytes calldata _callArgs
) external override {
if (_actionId == 0) {
// Settle and update all continuous fees
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true);
} else if (_actionId == 1) {
__payoutSharesOutstandingForFees(msg.sender, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @notice Enable and configure fees for use in the calling fund
/// @param _configData Encoded config data
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
/// The order of `fees` determines the order in which fees of the same FeeHook will be applied.
/// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise
/// PerformanceFee calcs.
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory fees, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity checks
require(
fees.length == settingsData.length,
"setConfigForFund: fees and settingsData array lengths unequal"
);
require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates");
// Enable each fee with settings
for (uint256 i; i < fees.length; i++) {
require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered");
// Set fund config on fee
IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]);
// Enable fee for fund
comptrollerProxyToFees[msg.sender].push(fees[i]);
emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]);
}
}
/// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic
/// @param _hook The FeeHook to invoke
/// @param _settlementData The encoded settlement parameters specific to the FeeHook
/// @param _gav The GAV for a fund if known in the invocating code, otherwise 0
function invokeHook(
FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override {
__invokeHook(msg.sender, _hook, _settlementData, _gav, true);
}
// PRIVATE FUNCTIONS
/// @dev Helper to destroy local storage to get gas refund,
/// and to prevent further calls to fee manager
function __deleteFundStorage(address _comptrollerProxy) private {
delete comptrollerProxyToFees[_comptrollerProxy];
delete comptrollerProxyToVaultProxy[_comptrollerProxy];
}
/// @dev Helper to force the payout of shares outstanding across all fees.
/// For the current release, all shares in the VaultProxy are assumed to be
/// shares outstanding from fees. If not, then they were sent there by mistake
/// and are otherwise unrecoverable. We can therefore take the VaultProxy's
/// shares balance as the totalSharesOutstanding to payout to the fund owner.
function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy);
if (totalSharesOutstanding == 0) {
return;
}
// Destroy any shares outstanding storage
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
for (uint256 i; i < fees.length; i++) {
delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
}
// Distribute all shares outstanding to the fees recipient
address payee = IVault(vaultProxy).getOwner();
__transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding);
emit AllSharesOutstandingForcePaidForFund(
_comptrollerProxy,
payee,
totalSharesOutstanding
);
}
/// @dev Helper to get the canonical value of GAV if not yet set and required by fee
function __getGavAsNecessary(
address _comptrollerProxy,
address _fee,
uint256 _gavOrZero
) private returns (uint256 gav_) {
if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) {
// Assumes that any fee that requires GAV would need to revert if invalid or not final
bool gavIsValid;
(gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true);
require(gavIsValid, "__getGavAsNecessary: Invalid GAV");
} else {
gav_ = _gavOrZero;
}
return gav_;
}
/// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to
/// optionally run update() on the same fees. This order allows fees an opportunity to update
/// their local state after all VaultProxy state transitions (i.e., minting, burning,
/// transferring shares) have finished. To optimize for the expensive operation of calculating
/// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees.
/// Assumes that _gav is either 0 or has already been validated.
function __invokeHook(
address _comptrollerProxy,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero,
bool _updateFees
) private {
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
if (fees.length == 0) {
return;
}
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
// This check isn't strictly necessary, but its cost is insignificant,
// and helps to preserve data integrity.
require(vaultProxy != address(0), "__invokeHook: Fund is not active");
// First, allow all fees to implement settle()
uint256 gav = __settleFees(
_comptrollerProxy,
vaultProxy,
fees,
_hook,
_settlementData,
_gavOrZero
);
// Second, allow fees to implement update()
// This function does not allow any further altering of VaultProxy state
// (i.e., burning, minting, or transferring shares)
if (_updateFees) {
__updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav);
}
}
/// @dev Helper to payout the shares outstanding for the specified fees.
/// Does not call settle() on fees.
/// Only callable via ComptrollerProxy.callOnExtension().
function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs)
private
{
address[] memory fees = abi.decode(_callArgs, (address[]));
address vaultProxy = getVaultProxyForFund(msg.sender);
uint256 sharesOutstandingDue;
for (uint256 i; i < fees.length; i++) {
if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) {
continue;
}
uint256 sharesOutstandingForFee
= comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
if (sharesOutstandingForFee == 0) {
continue;
}
sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee);
// Delete shares outstanding and distribute from VaultProxy to the fees recipient
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0;
emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee);
}
if (sharesOutstandingDue > 0) {
__transferShares(
_comptrollerProxy,
vaultProxy,
IVault(vaultProxy).getOwner(),
sharesOutstandingDue
);
}
}
/// @dev Helper to settle a fee
function __settleFee(
address _comptrollerProxy,
address _vaultProxy,
address _fee,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private {
(SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (settlementType == SettlementType.None) {
return;
}
address payee;
if (settlementType == SettlementType.Direct) {
payee = IVault(_vaultProxy).getOwner();
__transferShares(_comptrollerProxy, payer, payee, sharesDue);
} else if (settlementType == SettlementType.Mint) {
payee = IVault(_vaultProxy).getOwner();
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.Burn) {
__burnShares(_comptrollerProxy, payer, sharesDue);
} else if (settlementType == SettlementType.MintSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.add(sharesDue);
payee = _vaultProxy;
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.BurnSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.sub(sharesDue);
payer = _vaultProxy;
__burnShares(_comptrollerProxy, payer, sharesDue);
} else {
revert("__settleFee: Invalid SettlementType");
}
emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue);
}
/// @dev Helper to settle fees that implement a given fee hook
function __settleFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private returns (uint256 gav_) {
gav_ = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeSettlesOnHook(_fees[i], _hook)) {
continue;
}
gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_);
__settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_);
}
return gav_;
}
/// @dev Helper to update fees that implement a given fee hook
function __updateFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private {
uint256 gav = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeUpdatesOnHook(_fees[i], _hook)) {
continue;
}
gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav);
IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav);
}
}
///////////////////
// FEES REGISTRY //
///////////////////
/// @notice Remove fees from the list of registered fees
/// @param _fees Addresses of fees to be deregistered
function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "deregisterFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered");
registeredFees.remove(_fees[i]);
emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier());
}
}
/// @notice Add fees to the list of registered fees
/// @param _fees Addresses of fees to be registered
/// @dev Stores the hooks that a fee implements and whether each implementation uses GAV,
/// which fronts the gas for calls to check if a hook is implemented, and guarantees
/// that these hook implementation return values do not change post-registration.
function registerFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "registerFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered");
registeredFees.add(_fees[i]);
IFee feeContract = IFee(_fees[i]);
(
FeeHook[] memory implementedHooksForSettle,
FeeHook[] memory implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
) = feeContract.implementedHooks();
// Stores the hooks for which each fee implements settle() and update()
for (uint256 j; j < implementedHooksForSettle.length; j++) {
feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true;
}
for (uint256 j; j < implementedHooksForUpdate.length; j++) {
feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true;
}
// Stores whether each fee requires GAV during its implementations for settle() and update()
if (usesGavOnSettle) {
feeToUsesGavOnSettle[_fees[i]] = true;
}
if (usesGavOnUpdate) {
feeToUsesGavOnUpdate[_fees[i]] = true;
}
emit FeeRegistered(
_fees[i],
feeContract.identifier(),
implementedHooksForSettle,
implementedHooksForUpdate,
usesGavOnSettle,
usesGavOnUpdate
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get a list of enabled fees for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledFees_ An array of enabled fee addresses
function getEnabledFeesForFund(address _comptrollerProxy)
external
view
returns (address[] memory enabledFees_)
{
return comptrollerProxyToFees[_comptrollerProxy];
}
/// @notice Get the amount of shares outstanding for a particular fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fee The fee address
/// @return sharesOutstanding_ The amount of shares outstanding
function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee)
external
view
returns (uint256 sharesOutstanding_)
{
return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee];
}
/// @notice Get all registered fees
/// @return registeredFees_ A list of all registered fee addresses
function getRegisteredFees() external view returns (address[] memory registeredFees_) {
registeredFees_ = new address[](registeredFees.length());
for (uint256 i; i < registeredFees_.length; i++) {
registeredFees_[i] = registeredFees.at(i);
}
return registeredFees_;
}
/// @notice Checks if a fee implements settle() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return settlesOnHook_ True if the fee settles on the given hook
function feeSettlesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool settlesOnHook_)
{
return feeToHookToImplementsSettle[_fee][_hook];
}
/// @notice Checks if a fee implements update() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return updatesOnHook_ True if the fee updates on the given hook
function feeUpdatesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool updatesOnHook_)
{
return feeToHookToImplementsUpdate[_fee][_hook];
}
/// @notice Checks if a fee uses GAV in its settle() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during settle() implementation
function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnSettle[_fee];
}
/// @notice Checks if a fee uses GAV in its update() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during update() implementation
function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnUpdate[_fee];
}
/// @notice Check whether a fee is registered
/// @param _fee The address of the fee to check
/// @return isRegisteredFee_ True if the fee is registered
function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) {
return registeredFees.contains(_fee);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
/// @title PermissionedVaultActionMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for extensions that can make permissioned vault calls
abstract contract PermissionedVaultActionMixin {
/// @notice Adds a tracked asset to the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to add
function __addTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.AddTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Grants an allowance to a spender to use a fund's asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function __approveAssetSpender(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.ApproveAssetSpender,
abi.encode(_asset, _target, _amount)
);
}
/// @notice Burns fund shares for a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function __burnShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.BurnShares,
abi.encode(_target, _amount)
);
}
/// @notice Mints fund shares to a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account to which to mint shares
/// @param _amount The amount of shares to mint
function __mintShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.MintShares,
abi.encode(_target, _amount)
);
}
/// @notice Removes a tracked asset from the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to remove
function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.RemoveTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Transfers fund shares from one account to another
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function __transferShares(
address _comptrollerProxy,
address _from,
address _to,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.TransferShares,
abi.encode(_from, _to, _amount)
);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function __withdrawAssetTo(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.WithdrawAssetTo,
abi.encode(_asset, _target, _amount)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IWETH.sol";
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../extensions/fee-manager/FeeManager.sol";
/// @title FundActionsWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping fund actions, not necessary in the core protocol
contract FundActionsWrapper {
using SafeERC20 for ERC20;
address private immutable FEE_MANAGER;
address private immutable WETH_TOKEN;
mapping(address => bool) private accountToHasMaxWethAllowance;
constructor(address _feeManager, address _weth) public {
FEE_MANAGER = _feeManager;
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return netShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Accounts for fees outstanding. This is a convenience function for external consumption
/// that can be used to determine the cost of purchasing shares at any given point in time.
/// It essentially just bundles settling all fees that implement the Continuous hook and then
/// looking up the gross share value.
function calcNetShareValueForFund(address _comptrollerProxy)
external
returns (uint256 netShareValue_, bool isValid_)
{
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
return comptrollerProxyContract.calcGrossShareValue(false);
}
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _buyer The account for which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceivedAmount_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
address _buyer,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceivedAmount_) {
// Wrap ETH into WETH
IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == WETH_TOKEN) {
__approveMaxWethAsNeeded(_comptrollerProxy);
return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveMaxWethAsNeeded(_exchangeApproveTarget);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceivedAmount_ = __buyShares(
_comptrollerProxy,
_buyer,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceivedAmount_;
}
/// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout
/// any shares outstanding on those fees
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fees The fees for which to run these actions
/// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence.
/// The caller must pass in the fees that they want to run this logic on.
function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund(
address _comptrollerProxy,
address[] calldata _fees
) external {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees));
}
// PUBLIC FUNCTIONS
/// @notice Gets all fees that implement the `Continuous` fee hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return continuousFees_ The fees that implement the `Continuous` fee hook
function getContinuousFeesForFund(address _comptrollerProxy)
public
view
returns (address[] memory continuousFees_)
{
FeeManager feeManagerContract = FeeManager(FEE_MANAGER);
address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy);
// Count the continuous fees
uint256 continuousFeesCount;
bool[] memory implementsContinuousHook = new bool[](fees.length);
for (uint256 i; i < fees.length; i++) {
if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) {
continuousFeesCount++;
implementsContinuousHook[i] = true;
}
}
// Return early if no continuous fees
if (continuousFeesCount == 0) {
return new address[](0);
}
// Create continuous fees array
continuousFees_ = new address[](continuousFeesCount);
uint256 continuousFeesIndex;
for (uint256 i; i < fees.length; i++) {
if (implementsContinuousHook[i]) {
continuousFees_[continuousFeesIndex] = fees[i];
continuousFeesIndex++;
}
}
return continuousFees_;
}
// PRIVATE FUNCTIONS
/// @dev Helper to approve a target with the max amount of an asset, only when necessary
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to approve a target with the max amount of weth, only when necessary.
/// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this
/// once per target.
function __approveMaxWethAsNeeded(address _target) internal {
if (!accountHasMaxWethAllowance(_target)) {
ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max);
accountToHasMaxWethAllowance[_target] = true;
}
}
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceivedAmount_) {
address[] memory buyers = new address[](1);
buyers[0] = _buyer;
uint256[] memory investmentAmounts = new uint256[](1);
investmentAmounts[0] = _investmentAmount;
uint256[] memory minSharesQuantities = new uint256[](1);
minSharesQuantities[0] = _minSharesQuantity;
return
ComptrollerLib(_comptrollerProxy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
)[0];
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Checks whether an account has the max allowance for WETH
/// @param _who The account to check
/// @return hasMaxWethAllowance_ True if the account has the max allowance
function accountHasMaxWethAllowance(address _who)
public
view
returns (bool hasMaxWethAllowance_)
{
return accountToHasMaxWethAllowance[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances,
/// in which shares requests are manually executed by a permissioned user
/// @dev This will not work with a `denominationAsset` that does not transfer
/// the exact expected amount or has an elastic supply.
contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor {
using SafeERC20 for ERC20;
using SafeMath for uint256;
event RequestCanceled(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestCreated(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecuted(
address indexed caller,
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecutorAdded(address indexed account);
event RequestExecutorRemoved(address indexed account);
struct RequestInfo {
uint256 investmentAmount;
uint256 minSharesQuantity;
}
uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes;
address private comptrollerProxy;
address private denominationAsset;
address private fundOwner;
mapping(address => RequestInfo) private ownerToRequestInfo;
mapping(address => bool) private acctToIsRequestExecutor;
mapping(address => uint256) private ownerToLastRequestCancellation;
modifier onlyFundOwner() {
require(msg.sender == fundOwner, "Only fund owner callable");
_;
}
/// @notice Initializes a proxy instance that uses this library
/// @dev Serves as a per-proxy pseudo-constructor
function init(address _comptrollerProxy) external override {
require(comptrollerProxy == address(0), "init: Already initialized");
comptrollerProxy = _comptrollerProxy;
// Cache frequently-used values that require external calls
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
denominationAsset = comptrollerProxyContract.getDenominationAsset();
fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner();
}
/// @notice Cancels the shares request of the caller
function cancelRequest() external {
RequestInfo memory request = ownerToRequestInfo[msg.sender];
require(request.investmentAmount > 0, "cancelRequest: Request does not exist");
// Delete the request, start the cooldown period, and return the investment asset
delete ownerToRequestInfo[msg.sender];
ownerToLastRequestCancellation[msg.sender] = block.timestamp;
ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount);
emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity);
}
/// @notice Creates a shares request for the caller
/// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount
function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external {
require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0");
require(
ownerToRequestInfo[msg.sender].investmentAmount == 0,
"createRequest: The request owner can only create one request before executed or canceled"
);
require(
ownerToLastRequestCancellation[msg.sender] <
block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK),
"createRequest: Cannot create request during cancellation cooldown period"
);
// Create the Request and take custody of investment asset
ownerToRequestInfo[msg.sender] = RequestInfo({
investmentAmount: _investmentAmount,
minSharesQuantity: _minSharesQuantity
});
ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount);
emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity);
}
/// @notice Executes multiple shares requests
/// @param _requestOwners The owners of the pending shares requests
function executeRequests(address[] calldata _requestOwners) external {
require(
msg.sender == fundOwner || isRequestExecutor(msg.sender),
"executeRequests: Invalid caller"
);
require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty");
(
address[] memory buyers,
uint256[] memory investmentAmounts,
uint256[] memory minSharesQuantities,
uint256 totalInvestmentAmount
) = __convertRequestsToBuySharesParams(_requestOwners);
// Since ComptrollerProxy instances are fully trusted,
// we can approve them with the max amount of the denomination asset,
// and only top the approval back to max if ever necessary.
address comptrollerProxyCopy = comptrollerProxy;
ERC20 denominationAssetContract = ERC20(denominationAsset);
if (
denominationAssetContract.allowance(address(this), comptrollerProxyCopy) <
totalInvestmentAmount
) {
denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max);
}
ComptrollerLib(comptrollerProxyCopy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
);
}
/// @dev Helper to convert raw shares requests into the format required by buyShares().
/// It also removes any empty requests, which is necessary to prevent a DoS attack where a user
/// cancels their request earlier in the same block (can be repeated from multiple accounts).
/// This function also removes shares requests and fires success events as it loops through them.
function __convertRequestsToBuySharesParams(address[] memory _requestOwners)
private
returns (
address[] memory buyers_,
uint256[] memory investmentAmounts_,
uint256[] memory minSharesQuantities_,
uint256 totalInvestmentAmount_
)
{
uint256 existingRequestsCount = _requestOwners.length;
uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length);
// Loop through once to get the count of existing requests
for (uint256 i; i < _requestOwners.length; i++) {
allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount;
if (allInvestmentAmounts[i] == 0) {
existingRequestsCount--;
}
}
// Loop through a second time to format requests for buyShares(),
// and to delete the requests and emit events early so no further looping is needed.
buyers_ = new address[](existingRequestsCount);
investmentAmounts_ = new uint256[](existingRequestsCount);
minSharesQuantities_ = new uint256[](existingRequestsCount);
uint256 existingRequestsIndex;
for (uint256 i; i < _requestOwners.length; i++) {
if (allInvestmentAmounts[i] == 0) {
continue;
}
buyers_[existingRequestsIndex] = _requestOwners[i];
investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i];
minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]]
.minSharesQuantity;
totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]);
delete ownerToRequestInfo[_requestOwners[i]];
emit RequestExecuted(
msg.sender,
buyers_[existingRequestsIndex],
investmentAmounts_[existingRequestsIndex],
minSharesQuantities_[existingRequestsIndex]
);
existingRequestsIndex++;
}
return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_);
}
///////////////////////////////
// REQUEST EXECUTOR REGISTRY //
///////////////////////////////
/// @notice Adds accounts to request executors
/// @param _requestExecutors Accounts to add
function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
!isRequestExecutor(_requestExecutors[i]),
"addRequestExecutors: Value already set"
);
require(
_requestExecutors[i] != fundOwner,
"addRequestExecutors: The fund owner cannot be added"
);
acctToIsRequestExecutor[_requestExecutors[i]] = true;
emit RequestExecutorAdded(_requestExecutors[i]);
}
}
/// @notice Removes accounts from request executors
/// @param _requestExecutors Accounts to remove
function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
isRequestExecutor(_requestExecutors[i]),
"removeRequestExecutors: Account is not a request executor"
);
acctToIsRequestExecutor[_requestExecutors[i]] = false;
emit RequestExecutorRemoved(_requestExecutors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of `comptrollerProxy` variable
/// @return comptrollerProxy_ The `comptrollerProxy` variable value
function getComptrollerProxy() external view returns (address comptrollerProxy_) {
return comptrollerProxy;
}
/// @notice Gets the value of `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the value of `fundOwner` variable
/// @return fundOwner_ The `fundOwner` variable value
function getFundOwner() external view returns (address fundOwner_) {
return fundOwner;
}
/// @notice Gets the request info of a user
/// @param _requestOwner The address of the user that creates the request
/// @return requestInfo_ The request info created by the user
function getSharesRequestInfoForOwner(address _requestOwner)
external
view
returns (RequestInfo memory requestInfo_)
{
return ownerToRequestInfo[_requestOwner];
}
/// @notice Checks whether an account is a request executor
/// @param _who The account to check
/// @return isRequestExecutor_ True if _who is a request executor
function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) {
return acctToIsRequestExecutor[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAuthUserExecutedSharesRequestor Interface
/// @author Enzyme Council <[email protected]>
interface IAuthUserExecutedSharesRequestor {
function init(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./AuthUserExecutedSharesRequestorProxy.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances
contract AuthUserExecutedSharesRequestorFactory {
event SharesRequestorProxyDeployed(
address indexed comptrollerProxy,
address sharesRequestorProxy
);
address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
address private immutable DISPATCHER;
mapping(address => address) private comptrollerProxyToSharesRequestorProxy;
constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public {
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib;
DISPATCHER = _dispatcher;
}
/// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance
/// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy
/// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy
function deploySharesRequestorProxy(address _comptrollerProxy)
external
returns (address sharesRequestorProxy_)
{
// Confirm fund is genuine
VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy());
require(
vaultProxyContract.getAccessor() == _comptrollerProxy,
"deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy"
);
require(
IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) !=
address(0),
"deploySharesRequestorProxy: Not a genuine fund"
);
// Validate that the caller is the fund owner
require(
msg.sender == vaultProxyContract.getOwner(),
"deploySharesRequestorProxy: Only fund owner callable"
);
// Validate that a proxy does not already exist
require(
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0),
"deploySharesRequestorProxy: Proxy already exists"
);
// Deploy the proxy
bytes memory constructData = abi.encodeWithSelector(
IAuthUserExecutedSharesRequestor.init.selector,
_comptrollerProxy
);
sharesRequestorProxy_ = address(
new AuthUserExecutedSharesRequestorProxy(
constructData,
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB
)
);
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_;
emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_);
return sharesRequestorProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable
/// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value
function getAuthUserExecutedSharesRequestorLib()
external
view
returns (address authUserExecutedSharesRequestorLib_)
{
return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
}
/// @notice Gets the value of the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy
/// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address
function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy)
external
view
returns (address sharesRequestorProxy_)
{
return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/Proxy.sol";
contract AuthUserExecutedSharesRequestorProxy is Proxy {
constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib)
public
Proxy(_constructData, _authUserExecutedSharesRequestorLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Proxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all Proxy instances
/// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract Proxy {
constructor(bytes memory _constructData, address _contractLogic) public {
assembly {
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_contractLogic
)
}
(bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData);
require(success, string(returnData));
}
fallback() external payable {
assembly {
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../utils/Proxy.sol";
/// @title ComptrollerProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all ComptrollerProxy instances
contract ComptrollerProxy is Proxy {
constructor(bytes memory _constructData, address _comptrollerLib)
public
Proxy(_constructData, _comptrollerLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../persistent/dispatcher/IDispatcher.sol";
import "../../../persistent/utils/IMigrationHookHandler.sol";
import "../fund/comptroller/IComptroller.sol";
import "../fund/comptroller/ComptrollerProxy.sol";
import "../fund/vault/IVault.sol";
import "./IFundDeployer.sol";
/// @title FundDeployer Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract of the release.
/// It primarily coordinates fund deployment and fund migration, but
/// it is also deferred to for contract access control and for allowed calls
/// that can be made with a fund's VaultProxy as the msg.sender.
contract FundDeployer is IFundDeployer, IMigrationHookHandler {
event ComptrollerLibSet(address comptrollerLib);
event ComptrollerProxyDeployed(
address indexed creator,
address comptrollerProxy,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData,
bool indexed forMigration
);
event NewFundCreated(
address indexed creator,
address comptrollerProxy,
address vaultProxy,
address indexed fundOwner,
string fundName,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData
);
event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus);
event VaultCallDeregistered(address indexed contractAddress, bytes4 selector);
event VaultCallRegistered(address indexed contractAddress, bytes4 selector);
// Constants
address private immutable CREATOR;
address private immutable DISPATCHER;
address private immutable VAULT_LIB;
// Pseudo-constants (can only be set once)
address private comptrollerLib;
// Storage
ReleaseStatus private releaseStatus;
mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall;
mapping(address => address) private pendingComptrollerProxyToCreator;
modifier onlyLiveRelease() {
require(releaseStatus == ReleaseStatus.Live, "Release is not Live");
_;
}
modifier onlyMigrator(address _vaultProxy) {
require(
IVault(_vaultProxy).canMigrate(msg.sender),
"Only a permissioned migrator can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == getOwner(), "Only the contract owner can call this function");
_;
}
modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) {
require(
msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy],
"Only the ComptrollerProxy creator can call this function"
);
_;
}
constructor(
address _dispatcher,
address _vaultLib,
address[] memory _vaultCallContracts,
bytes4[] memory _vaultCallSelectors
) public {
if (_vaultCallContracts.length > 0) {
__registerVaultCalls(_vaultCallContracts, _vaultCallSelectors);
}
CREATOR = msg.sender;
DISPATCHER = _dispatcher;
VAULT_LIB = _vaultLib;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the comptrollerLib
/// @param _comptrollerLib The ComptrollerLib contract address
/// @dev Can only be set once
function setComptrollerLib(address _comptrollerLib) external onlyOwner {
require(
comptrollerLib == address(0),
"setComptrollerLib: This value can only be set once"
);
comptrollerLib = _comptrollerLib;
emit ComptrollerLibSet(_comptrollerLib);
}
/// @notice Sets the status of the protocol to a new state
/// @param _nextStatus The next status state to set
function setReleaseStatus(ReleaseStatus _nextStatus) external {
require(
msg.sender == IDispatcher(DISPATCHER).getOwner(),
"setReleaseStatus: Only the Dispatcher owner can call this function"
);
require(
_nextStatus != ReleaseStatus.PreLaunch,
"setReleaseStatus: Cannot return to PreLaunch status"
);
require(
comptrollerLib != address(0),
"setReleaseStatus: Can only set the release status when comptrollerLib is set"
);
ReleaseStatus prevStatus = releaseStatus;
require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status");
releaseStatus = _nextStatus;
emit ReleaseStatusSet(prevStatus, _nextStatus);
}
/// @notice Gets the current owner of the contract
/// @return owner_ The contract owner address
/// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the
/// contract's deployer, for convenience in setting up configuration.
/// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council)
/// sets the releaseStatus to `Live`.
function getOwner() public view override returns (address owner_) {
if (releaseStatus == ReleaseStatus.PreLaunch) {
return CREATOR;
}
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// FUND CREATION //
///////////////////
/// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous
/// release can migrate in a subsequent step
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createMigratedFundConfig(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_) {
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
true
);
pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender;
return comptrollerProxy_;
}
/// @notice Creates a new fund
/// @param _fundOwner The address of the owner for the fund
/// @param _fundName The name of the fund
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createNewFund(
address _fundOwner,
string calldata _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) {
return
__createNewFund(
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
}
/// @dev Helper to avoid the stack-too-deep error during createNewFund
function __createNewFund(
address _fundOwner,
string memory _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData
) private returns (address comptrollerProxy_, address vaultProxy_) {
require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty");
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
false
);
vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy(
VAULT_LIB,
_fundOwner,
comptrollerProxy_,
_fundName
);
IComptroller(comptrollerProxy_).activate(vaultProxy_, false);
emit NewFundCreated(
msg.sender,
comptrollerProxy_,
vaultProxy_,
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
return (comptrollerProxy_, vaultProxy_);
}
/// @dev Helper function to deploy a configured ComptrollerProxy
function __deployComptrollerProxy(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData,
bool _forMigration
) private returns (address comptrollerProxy_) {
require(
_denominationAsset != address(0),
"__deployComptrollerProxy: _denominationAsset cannot be empty"
);
bytes memory constructData = abi.encodeWithSelector(
IComptroller.init.selector,
_denominationAsset,
_sharesActionTimelock
);
comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib));
if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) {
IComptroller(comptrollerProxy_).configureExtensions(
_feeManagerConfigData,
_policyManagerConfigData
);
}
emit ComptrollerProxyDeployed(
msg.sender,
comptrollerProxy_,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
_forMigration
);
return comptrollerProxy_;
}
//////////////////
// MIGRATION IN //
//////////////////
/// @notice Cancels fund migration
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigration(address _vaultProxy) external {
__cancelMigration(_vaultProxy, false);
}
/// @notice Cancels fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigrationEmergency(address _vaultProxy) external {
__cancelMigration(_vaultProxy, true);
}
/// @notice Executes fund migration
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigration(address _vaultProxy) external {
__executeMigration(_vaultProxy, false);
}
/// @notice Executes fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigrationEmergency(address _vaultProxy) external {
__executeMigration(_vaultProxy, true);
}
/// @dev Unimplemented
function invokeMigrationInCancelHook(
address,
address,
address,
address
) external virtual override {
return;
}
/// @notice Signal a fund migration
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigration(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, false);
}
/// @notice Signal a fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, true);
}
/// @dev Helper to cancel a migration
function __cancelMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure);
}
/// @dev Helper to execute a migration
function __executeMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher dispatcherContract = IDispatcher(DISPATCHER);
(, address comptrollerProxy, , ) = dispatcherContract
.getMigrationRequestDetailsForVaultProxy(_vaultProxy);
dispatcherContract.executeMigration(_vaultProxy, _bypassFailure);
IComptroller(comptrollerProxy).activate(_vaultProxy, true);
delete pendingComptrollerProxyToCreator[comptrollerProxy];
}
/// @dev Helper to signal a migration
function __signalMigration(
address _vaultProxy,
address _comptrollerProxy,
bool _bypassFailure
)
private
onlyLiveRelease
onlyPendingComptrollerProxyCreator(_comptrollerProxy)
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).signalMigration(
_vaultProxy,
_comptrollerProxy,
VAULT_LIB,
_bypassFailure
);
}
///////////////////
// MIGRATION OUT //
///////////////////
/// @notice Allows "hooking into" specific moments in the migration pipeline
/// to execute arbitrary logic during a migration out of this release
/// @param _vaultProxy The VaultProxy being migrated
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address,
address,
address
) external override {
if (_hook != MigrationOutHook.PreMigrate) {
return;
}
require(
msg.sender == DISPATCHER,
"postMigrateOriginHook: Only Dispatcher can call this function"
);
// Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy
address comptrollerProxy = IVault(_vaultProxy).getAccessor();
// Wind down fund and destroy its config
IComptroller(comptrollerProxy).destruct();
}
//////////////
// REGISTRY //
//////////////
/// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to de-register
/// @param _selectors The selectors of the calls to de-register
function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts");
require(
_contracts.length == _selectors.length,
"deregisterVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
isRegisteredVaultCall(_contracts[i], _selectors[i]),
"deregisterVaultCalls: Call not registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false;
emit VaultCallDeregistered(_contracts[i], _selectors[i]);
}
}
/// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to register
/// @param _selectors The selectors of the calls to register
function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "registerVaultCalls: Empty _contracts");
__registerVaultCalls(_contracts, _selectors);
}
/// @dev Helper to register allowed vault calls
function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors)
private
{
require(
_contracts.length == _selectors.length,
"__registerVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
!isRegisteredVaultCall(_contracts[i], _selectors[i]),
"__registerVaultCalls: Call already registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true;
emit VaultCallRegistered(_contracts[i], _selectors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `comptrollerLib` variable value
/// @return comptrollerLib_ The `comptrollerLib` variable value
function getComptrollerLib() external view returns (address comptrollerLib_) {
return comptrollerLib;
}
/// @notice Gets the `CREATOR` variable value
/// @return creator_ The `CREATOR` variable value
function getCreator() external view returns (address creator_) {
return CREATOR;
}
/// @notice Gets the `DISPATCHER` variable value
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the creator of a pending ComptrollerProxy
/// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator
function getPendingComptrollerProxyCreator(address _comptrollerProxy)
external
view
returns (address pendingComptrollerProxyCreator_)
{
return pendingComptrollerProxyToCreator[_comptrollerProxy];
}
/// @notice Gets the `releaseStatus` variable value
/// @return status_ The `releaseStatus` variable value
function getReleaseStatus() external view override returns (ReleaseStatus status_) {
return releaseStatus;
}
/// @notice Gets the `VAULT_LIB` variable value
/// @return vaultLib_ The `VAULT_LIB` variable value
function getVaultLib() external view returns (address vaultLib_) {
return VAULT_LIB;
}
/// @notice Checks if a contract call is registered
/// @param _contract The contract of the call to check
/// @param _selector The selector of the call to check
/// @return isRegistered_ True if the call is registered
function isRegisteredVaultCall(address _contract, bytes4 _selector)
public
view
override
returns (bool isRegistered_)
{
return contractToSelectorToIsRegisteredVaultCall[_contract][_selector];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigrationHookHandler Interface
/// @author Enzyme Council <[email protected]>
interface IMigrationHookHandler {
enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel}
function invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../utils/AddressArrayLib.sol";
import "../../utils/AssetFinalityResolver.sol";
import "../policy-manager/IPolicyManager.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./integrations/IIntegrationAdapter.sol";
import "./IIntegrationManager.sol";
/// @title IntegrationManager
/// @author Enzyme Council <[email protected]>
/// @notice Extension to handle DeFi integration actions for funds
contract IntegrationManager is
IIntegrationManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin,
AssetFinalityResolver
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AdapterDeregistered(address indexed adapter, string indexed identifier);
event AdapterRegistered(address indexed adapter, string indexed identifier);
event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account);
event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account);
event CallOnIntegrationExecutedForFund(
address indexed comptrollerProxy,
address vaultProxy,
address caller,
address indexed adapter,
bytes4 indexed selector,
bytes integrationData,
address[] incomingAssets,
uint256[] incomingAssetAmounts,
address[] outgoingAssets,
uint256[] outgoingAssetAmounts
);
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
EnumerableSet.AddressSet private registeredAdapters;
mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser;
constructor(
address _fundDeployer,
address _policyManager,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
)
public
FundDeployerOwnerMixin(_fundDeployer)
AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver)
{
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
POLICY_MANAGER = _policyManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
/////////////
// GENERAL //
/////////////
/// @notice Activates the extension by storing the VaultProxy
function activateForFund(bool) external override {
__setValidatedVaultProxy(msg.sender);
}
/// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The user to authorize
function addAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, true);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true;
emit AuthUserAddedForFund(_comptrollerProxy, _who);
}
/// @notice Deactivate the extension by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
}
/// @notice Removes an authorized user from the IntegrationManager for the given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The authorized user to remove
function removeAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, false);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false;
emit AuthUserRemovedForFund(_comptrollerProxy, _who);
}
/// @notice Checks whether an account is an authorized IntegrationManager user for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The account to check
/// @return isAuthUser_ True if the account is an authorized user or the fund owner
function isAuthUserForFund(address _comptrollerProxy, address _who)
public
view
returns (bool isAuthUser_)
{
return
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] ||
_who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
}
/// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser
function __validateSetAuthUser(
address _comptrollerProxy,
address _who,
bool _nextIsAuthUser
) private view {
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0),
"__validateSetAuthUser: Fund has not been activated"
);
address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
require(
msg.sender == fundOwner,
"__validateSetAuthUser: Only the fund owner can call this function"
);
require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner");
if (_nextIsAuthUser) {
require(
!comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is already an authorized user"
);
} else {
require(
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is not an authorized user"
);
}
}
///////////////////////////////
// CALL-ON-EXTENSION ACTIONS //
///////////////////////////////
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _caller The user who called for this action
/// @param _actionId An ID representing the desired action
/// @param _callArgs The encoded args for the action
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external override {
// Since we validate and store the ComptrollerProxy-VaultProxy pairing during
// activateForFund(), this function does not require further validation of the
// sending ComptrollerProxy
address vaultProxy = comptrollerProxyToVaultProxy[msg.sender];
require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active");
require(
isAuthUserForFund(msg.sender, _caller),
"receiveCallFromComptroller: Not an authorized user"
);
// Dispatch the action
if (_actionId == 0) {
__callOnIntegration(_caller, vaultProxy, _callArgs);
} else if (_actionId == 1) {
__addZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else if (_actionId == 2) {
__removeZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @dev Adds assets with a zero balance as tracked assets of the fund
function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private {
address[] memory assets = abi.decode(_callArgs, (address[]));
for (uint256 i; i < assets.length; i++) {
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__addZeroBalanceTrackedAssets: Balance is not zero"
);
__addTrackedAsset(msg.sender, assets[i]);
}
}
/// @dev Removes assets with a zero balance from tracked assets of the fund
function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs)
private
{
address[] memory assets = abi.decode(_callArgs, (address[]));
address denominationAsset = IComptroller(msg.sender).getDenominationAsset();
for (uint256 i; i < assets.length; i++) {
require(
assets[i] != denominationAsset,
"__removeZeroBalanceTrackedAssets: Cannot remove denomination asset"
);
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__removeZeroBalanceTrackedAssets: Balance is not zero"
);
__removeTrackedAsset(msg.sender, assets[i]);
}
}
/////////////////////////
// CALL ON INTEGRATION //
/////////////////////////
/// @notice Universal method for calling third party contract functions through adapters
/// @param _caller The caller of this function via the ComptrollerProxy
/// @param _vaultProxy The VaultProxy of the fund
/// @param _callArgs The encoded args for this function
/// - _adapter Adapter of the integration on which to execute a call
/// - _selector Method selector of the adapter method to execute
/// - _integrationData Encoded arguments specific to the adapter
/// @dev msg.sender is the ComptrollerProxy.
/// Refer to specific adapter to see how to encode its arguments.
function __callOnIntegration(
address _caller,
address _vaultProxy,
bytes memory _callArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
__preCoIHook(adapter, selector);
/// Passing decoded _callArgs leads to stack-too-deep error
(
address[] memory incomingAssets,
uint256[] memory incomingAssetAmounts,
address[] memory outgoingAssets,
uint256[] memory outgoingAssetAmounts
) = __callOnIntegrationInner(_vaultProxy, _callArgs);
__postCoIHook(
adapter,
selector,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
__emitCoIEvent(
_vaultProxy,
_caller,
adapter,
selector,
integrationData,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
}
/// @dev Helper to execute the bulk of logic of callOnIntegration.
/// Avoids the stack-too-deep-error.
function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
(
address[] memory expectedIncomingAssets,
uint256[] memory preCallIncomingAssetBalances,
uint256[] memory minIncomingAssetAmounts,
SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory maxSpendAssetAmounts,
uint256[] memory preCallSpendAssetBalances
) = __preProcessCoI(vaultProxy, _callArgs);
__executeCoI(
vaultProxy,
_callArgs,
abi.encode(
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
expectedIncomingAssets
)
);
(
incomingAssets_,
incomingAssetAmounts_,
outgoingAssets_,
outgoingAssetAmounts_
) = __postProcessCoI(
vaultProxy,
expectedIncomingAssets,
preCallIncomingAssetBalances,
minIncomingAssetAmounts,
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
preCallSpendAssetBalances
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to decode CoI args
function __decodeCallOnIntegrationArgs(bytes memory _callArgs)
private
pure
returns (
address adapter_,
bytes4 selector_,
bytes memory integrationData_
)
{
return abi.decode(_callArgs, (address, bytes4, bytes));
}
/// @dev Helper to emit the CallOnIntegrationExecuted event.
/// Avoids stack-too-deep error.
function __emitCoIEvent(
address _vaultProxy,
address _caller,
address _adapter,
bytes4 _selector,
bytes memory _integrationData,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
emit CallOnIntegrationExecutedForFund(
msg.sender,
_vaultProxy,
_caller,
_adapter,
_selector,
_integrationData,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
);
}
/// @dev Helper to execute a call to an integration
/// @dev Avoids stack-too-deep error
function __executeCoI(
address _vaultProxy,
bytes memory _callArgs,
bytes memory _encodedAssetTransferArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
(bool success, bytes memory returnData) = adapter.call(
abi.encodeWithSelector(
selector,
_vaultProxy,
integrationData,
_encodedAssetTransferArgs
)
);
require(success, string(returnData));
}
/// @dev Helper to get the vault's balance of a particular asset
function __getVaultAssetBalance(address _vaultProxy, address _asset)
private
view
returns (uint256)
{
return ERC20(_asset).balanceOf(_vaultProxy);
}
/// @dev Helper to check if an asset is supported
function __isSupportedAsset(address _asset) private view returns (bool isSupported_) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) ||
IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset);
}
/// @dev Helper for the actions to take on external contracts prior to executing CoI
function __preCoIHook(address _adapter, bytes4 _selector) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PreCallOnIntegration,
abi.encode(_adapter, _selector)
);
}
/// @dev Helper for the internal actions to take prior to executing CoI
function __preProcessCoI(address _vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory expectedIncomingAssets_,
uint256[] memory preCallIncomingAssetBalances_,
uint256[] memory minIncomingAssetAmounts_,
SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory preCallSpendAssetBalances_
)
{
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered");
// Note that expected incoming and spend assets are allowed to overlap
// (e.g., a fee for the incomingAsset charged in a spend asset)
(
spendAssetsHandleType_,
spendAssets_,
maxSpendAssetAmounts_,
expectedIncomingAssets_,
minIncomingAssetAmounts_
) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData);
require(
spendAssets_.length == maxSpendAssetAmounts_.length,
"__preProcessCoI: Spend assets arrays unequal"
);
require(
expectedIncomingAssets_.length == minIncomingAssetAmounts_.length,
"__preProcessCoI: Incoming assets arrays unequal"
);
require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset");
require(
expectedIncomingAssets_.isUniqueSet(),
"__preProcessCoI: Duplicate incoming asset"
);
IVault vaultProxyContract = IVault(_vaultProxy);
preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length);
for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) {
require(
expectedIncomingAssets_[i] != address(0),
"__preProcessCoI: Empty incoming asset address"
);
require(
minIncomingAssetAmounts_[i] > 0,
"__preProcessCoI: minIncomingAssetAmount must be >0"
);
require(
__isSupportedAsset(expectedIncomingAssets_[i]),
"__preProcessCoI: Non-receivable incoming asset"
);
// Get pre-call balance of each incoming asset.
// If the asset is not tracked by the fund, allow the balance to default to 0.
if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) {
// We do not require incoming asset finality, but we attempt to finalize so that
// the final incoming asset amount is more accurate. There is no need to finalize
// post-tx.
preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
expectedIncomingAssets_[i],
false
);
}
}
// Get pre-call balances of spend assets and grant approvals to adapter
preCallSpendAssetBalances_ = new uint256[](spendAssets_.length);
for (uint256 i = 0; i < spendAssets_.length; i++) {
require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset");
require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount");
// A spend asset must either be a tracked asset of the fund or a supported asset,
// in order to prevent seeding the fund with a malicious token and performing arbitrary
// actions within an adapter.
require(
vaultProxyContract.isTrackedAsset(spendAssets_[i]) ||
__isSupportedAsset(spendAssets_[i]),
"__preProcessCoI: Non-spendable spend asset"
);
// If spend asset is also an incoming asset, no need to record its balance
if (!expectedIncomingAssets_.contains(spendAssets_[i])) {
// By requiring spend asset finality before CoI, we will know whether or
// not the asset balance was entirely spent during the call. There is no need
// to finalize post-tx.
preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
spendAssets_[i],
true
);
}
// Grant spend assets access to the adapter.
// Note that spendAssets_ is already asserted to a unique set.
if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) {
// Use exact approve amount rather than increasing allowances,
// because all adapters finish their actions atomically.
__approveAssetSpender(
msg.sender,
spendAssets_[i],
adapter,
maxSpendAssetAmounts_[i]
);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) {
__withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) {
__removeTrackedAsset(msg.sender, spendAssets_[i]);
}
}
}
/// @dev Helper for the actions to take on external contracts after executing CoI
function __postCoIHook(
address _adapter,
bytes4 _selector,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PostCallOnIntegration,
abi.encode(
_adapter,
_selector,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
)
);
}
/// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI
function __postProcessCoI(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
address[] memory increasedSpendAssets;
uint256[] memory increasedSpendAssetAmounts;
(
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets,
increasedSpendAssetAmounts
) = __reconcileCoISpendAssets(
_vaultProxy,
_spendAssetsHandleType,
_spendAssets,
_maxSpendAssetAmounts,
_preCallSpendAssetBalances
);
(incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets(
_vaultProxy,
_expectedIncomingAssets,
_preCallIncomingAssetBalances,
_minIncomingAssetAmounts,
increasedSpendAssets,
increasedSpendAssetAmounts
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to process incoming asset balance changes.
/// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets".
function __reconcileCoIIncomingAssets(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
address[] memory _increasedSpendAssets,
uint256[] memory _increasedSpendAssetAmounts
) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) {
// Incoming assets = expected incoming assets + spend assets with increased balances
uint256 incomingAssetsCount = _expectedIncomingAssets.length.add(
_increasedSpendAssets.length
);
// Calculate and validate incoming asset amounts
incomingAssets_ = new address[](incomingAssetsCount);
incomingAssetAmounts_ = new uint256[](incomingAssetsCount);
for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) {
uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i])
.sub(_preCallIncomingAssetBalances[i]);
require(
balanceDiff >= _minIncomingAssetAmounts[i],
"__reconcileCoIAssets: Received incoming asset less than expected"
);
// Even if the asset's previous balance was >0, it might not have been tracked
__addTrackedAsset(msg.sender, _expectedIncomingAssets[i]);
incomingAssets_[i] = _expectedIncomingAssets[i];
incomingAssetAmounts_[i] = balanceDiff;
}
// Append increaseSpendAssets to incomingAsset vars
if (_increasedSpendAssets.length > 0) {
uint256 incomingAssetIndex = _expectedIncomingAssets.length;
for (uint256 i = 0; i < _increasedSpendAssets.length; i++) {
incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i];
incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i];
incomingAssetIndex++;
}
}
return (incomingAssets_, incomingAssetAmounts_);
}
/// @dev Helper to process spend asset balance changes.
/// "outgoingAssets" are the spend assets with a decrease in balance.
/// "increasedSpendAssets" are the spend assets with an unexpected increase in balance.
/// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of
/// the spendAsset, which would be transferred to the fund at the end of the tx.
function __reconcileCoISpendAssets(
address _vaultProxy,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_,
address[] memory increasedSpendAssets_,
uint256[] memory increasedSpendAssetAmounts_
)
{
// Determine spend asset balance changes
uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length);
uint256 outgoingAssetsCount;
uint256 increasedSpendAssetsCount;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssetsCount++;
continue;
}
// Determine if the asset is outgoing or incoming, and store the post-balance for later use
postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]);
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
outgoingAssetsCount++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetsCount++;
}
}
// Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance)
outgoingAssets_ = new address[](outgoingAssetsCount);
outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount);
increasedSpendAssets_ = new address[](increasedSpendAssetsCount);
increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount);
uint256 outgoingAssetsIndex;
uint256 increasedSpendAssetsIndex;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset.
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately.
// No need to validate the max spend asset amount.
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
outgoingAssetsIndex++;
continue;
}
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
if (postCallSpendAssetBalances[i] == 0) {
__removeTrackedAsset(msg.sender, _spendAssets[i]);
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
} else {
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub(
postCallSpendAssetBalances[i]
);
}
require(
outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i],
"__reconcileCoISpendAssets: Spent amount greater than expected"
);
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetsIndex++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i]
.sub(_preCallSpendAssetBalances[i]);
increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i];
increasedSpendAssetsIndex++;
}
}
return (
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets_,
increasedSpendAssetAmounts_
);
}
///////////////////////////
// INTEGRATIONS REGISTRY //
///////////////////////////
/// @notice Remove integration adapters from the list of registered adapters
/// @param _adapters Addresses of adapters to be deregistered
function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(
adapterIsRegistered(_adapters[i]),
"deregisterAdapters: Adapter is not registered"
);
registeredAdapters.remove(_adapters[i]);
emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
/// @notice Add integration adapters to the list of registered adapters
/// @param _adapters Addresses of adapters to be registered
function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty");
require(
!adapterIsRegistered(_adapters[i]),
"registerAdapters: Adapter already registered"
);
registeredAdapters.add(_adapters[i]);
emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Checks if an integration adapter is registered
/// @param _adapter The adapter to check
/// @return isRegistered_ True if the adapter is registered
function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) {
return registeredAdapters.contains(_adapter);
}
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets all registered integration adapters
/// @return registeredAdaptersArray_ A list of all registered integration adapters
function getRegisteredAdapters()
external
view
returns (address[] memory registeredAdaptersArray_)
{
registeredAdaptersArray_ = new address[](registeredAdapters.length());
for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) {
registeredAdaptersArray_[i] = registeredAdapters.at(i);
}
return registeredAdaptersArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../utils/AdapterBase.sol";
/// @title SynthetixAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Synthetix
contract SynthetixAdapter is AdapterBase {
address private immutable ORIGINATOR;
address private immutable SYNTHETIX;
address private immutable SYNTHETIX_PRICE_FEED;
bytes32 private immutable TRACKING_CODE;
constructor(
address _integrationManager,
address _synthetixPriceFeed,
address _originator,
address _synthetix,
bytes32 _trackingCode
) public AdapterBase(_integrationManager) {
ORIGINATOR = _originator;
SYNTHETIX = _synthetix;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
TRACKING_CODE = _trackingCode;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "SYNTHETIX";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.None,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Synthetix
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address incomingAsset,
,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address[] memory synths = new address[](2);
synths[0] = outgoingAsset;
synths[1] = incomingAsset;
bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED)
.getCurrencyKeysForSynths(synths);
ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking(
_vaultProxy,
currencyKeys[0],
outgoingAssetAmount,
currencyKeys[1],
ORIGINATOR,
TRACKING_CODE
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ORIGINATOR` variable
/// @return originator_ The `ORIGINATOR` variable value
function getOriginator() external view returns (address originator_) {
return ORIGINATOR;
}
/// @notice Gets the `SYNTHETIX` variable
/// @return synthetix_ The `SYNTHETIX` variable value
function getSynthetix() external view returns (address synthetix_) {
return SYNTHETIX;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
/// @notice Gets the `TRACKING_CODE` variable
/// @return trackingCode_ The `TRACKING_CODE` variable value
function getTrackingCode() external view returns (bytes32 trackingCode_) {
return TRACKING_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../interfaces/IChainlinkAggregator.sol";
import "../../utils/DispatcherOwnerMixin.sol";
import "./IPrimitivePriceFeed.sol";
/// @title ChainlinkPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Chainlink oracles as price sources
contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator);
event PrimitiveAdded(
address indexed primitive,
address aggregator,
RateAsset rateAsset,
uint256 unit
);
event PrimitiveRemoved(address indexed primitive);
event PrimitiveUpdated(
address indexed primitive,
address prevAggregator,
address nextAggregator
);
event StalePrimitiveRemoved(address indexed primitive);
event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold);
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
uint256 private constant ETH_UNIT = 10**18;
address private immutable WETH_TOKEN;
address private ethUsdAggregator;
uint256 private staleRateThreshold;
mapping(address => AggregatorInfo) private primitiveToAggregatorInfo;
mapping(address => uint256) private primitiveToUnit;
constructor(
address _dispatcher,
address _wethToken,
address _ethUsdAggregator,
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) public DispatcherOwnerMixin(_dispatcher) {
WETH_TOKEN = _wethToken;
staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer
__setEthUsdAggregator(_ethUsdAggregator);
if (_primitives.length > 0) {
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
}
// EXTERNAL FUNCTIONS
/// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
function calcCanonicalValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) public view override returns (uint256 quoteAssetAmount_, bool isValid_) {
// Case where _baseAsset == _quoteAsset is handled by ValueInterpreter
int256 baseAssetRate = __getLatestRateData(_baseAsset);
if (baseAssetRate <= 0) {
return (0, false);
}
int256 quoteAssetRate = __getLatestRateData(_quoteAsset);
if (quoteAssetRate <= 0) {
return (0, false);
}
(quoteAssetAmount_, isValid_) = __calcConversionAmount(
_baseAsset,
_baseAssetAmount,
uint256(baseAssetRate),
_quoteAsset,
uint256(quoteAssetRate)
);
return (quoteAssetAmount_, isValid_);
}
/// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
/// @dev Live and canonical values are the same for Chainlink
function calcLiveValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) external view override returns (uint256 quoteAssetAmount_, bool isValid_) {
return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0);
}
/// @notice Sets the `ehUsdAggregator` variable value
/// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set
function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner {
__setEthUsdAggregator(_nextEthUsdAggregator);
}
// PRIVATE FUNCTIONS
/// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset
function __calcConversionAmount(
address _baseAsset,
uint256 _baseAssetAmount,
uint256 _baseAssetRate,
address _quoteAsset,
uint256 _quoteAssetRate
) private view returns (uint256 quoteAssetAmount_, bool isValid_) {
RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset);
RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset);
uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset);
uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset);
// If rates are both in ETH or both in USD
if (baseAssetRateAsset == quoteAssetRateAsset) {
return (
__calcConversionAmountSameRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate
),
true
);
}
int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer();
if (ethPerUsdRate <= 0) {
return (0, false);
}
// If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD
if (baseAssetRateAsset == RateAsset.ETH) {
return (
__calcConversionAmountEthRateAssetToUsdRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
// If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH
return (
__calcConversionAmountUsdRateAssetToEthRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
/// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate
function __calcConversionAmountEthRateAssetToUsdRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow.
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div(
ETH_UNIT
);
return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates
function __calcConversionAmountSameRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
return
_baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_baseAssetUnit.mul(_quoteAssetRate)
);
}
/// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate
function __calcConversionAmountUsdRateAssetToEthRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_ethPerUsdRate
);
return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to get the latest rate for a given primitive
function __getLatestRateData(address _primitive) private view returns (int256 rate_) {
if (_primitive == WETH_TOKEN) {
return int256(ETH_UNIT);
}
address aggregator = primitiveToAggregatorInfo[_primitive].aggregator;
require(aggregator != address(0), "__getLatestRateData: Primitive does not exist");
return IChainlinkAggregator(aggregator).latestAnswer();
}
/// @dev Helper to set the `ethUsdAggregator` value
function __setEthUsdAggregator(address _nextEthUsdAggregator) private {
address prevEthUsdAggregator = ethUsdAggregator;
require(
_nextEthUsdAggregator != prevEthUsdAggregator,
"__setEthUsdAggregator: Value already set"
);
__validateAggregator(_nextEthUsdAggregator);
ethUsdAggregator = _nextEthUsdAggregator;
emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator);
}
/////////////////////////
// PRIMITIVES REGISTRY //
/////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyDispatcherOwner {
require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty");
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner {
require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0),
"removePrimitives: Primitive not yet added"
);
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit PrimitiveRemoved(_primitives[i]);
}
}
/// @notice Removes stale primitives from the feed
/// @param _primitives The stale primitives to remove
/// @dev Callable by anybody
function removeStalePrimitives(address[] calldata _primitives) external {
require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive");
require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale");
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit StalePrimitiveRemoved(_primitives[i]);
}
}
/// @notice Sets the `staleRateThreshold` variable
/// @param _nextStaleRateThreshold The next `staleRateThreshold` value
function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner {
uint256 prevStaleRateThreshold = staleRateThreshold;
require(
_nextStaleRateThreshold != prevStaleRateThreshold,
"__setStaleRateThreshold: Value already set"
);
staleRateThreshold = _nextStaleRateThreshold;
emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold);
}
/// @notice Updates the aggregators for given primitives
/// @param _primitives The primitives to update
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators)
external
onlyDispatcherOwner
{
require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty");
require(
_primitives.length == _aggregators.length,
"updatePrimitives: Unequal _primitives and _aggregators array lengths"
);
for (uint256 i; i < _primitives.length; i++) {
address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added");
require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set");
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i];
emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]);
}
}
/// @notice Checks whether the current rate is considered stale for the specified aggregator
/// @param _aggregator The Chainlink aggregator of which to check staleness
/// @return rateIsStale_ True if the rate is considered stale
function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) {
return
IChainlinkAggregator(_aggregator).latestTimestamp() <
block.timestamp.sub(staleRateThreshold);
}
/// @dev Helper to add primitives to the feed
function __addPrimitives(
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) private {
require(
_primitives.length == _aggregators.length,
"__addPrimitives: Unequal _primitives and _aggregators array lengths"
);
require(
_primitives.length == _rateAssets.length,
"__addPrimitives: Unequal _primitives and _rateAssets array lengths"
);
for (uint256 i = 0; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0),
"__addPrimitives: Value already set"
);
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
// Store the amount that makes up 1 unit given the asset's decimals
uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals());
primitiveToUnit[_primitives[i]] = unit;
emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit);
}
}
/// @dev Helper to validate an aggregator by checking its return values for the expected interface
function __validateAggregator(address _aggregator) private view {
require(_aggregator != address(0), "__validateAggregator: Empty _aggregator");
require(
IChainlinkAggregator(_aggregator).latestAnswer() > 0,
"__validateAggregator: No rate detected"
);
require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the aggregatorInfo variable value for a primitive
/// @param _primitive The primitive asset for which to get the aggregatorInfo value
/// @return aggregatorInfo_ The aggregatorInfo value
function getAggregatorInfoForPrimitive(address _primitive)
external
view
returns (AggregatorInfo memory aggregatorInfo_)
{
return primitiveToAggregatorInfo[_primitive];
}
/// @notice Gets the `ethUsdAggregator` variable value
/// @return ethUsdAggregator_ The `ethUsdAggregator` variable value
function getEthUsdAggregator() external view returns (address ethUsdAggregator_) {
return ethUsdAggregator;
}
/// @notice Gets the `staleRateThreshold` variable value
/// @return staleRateThreshold_ The `staleRateThreshold` variable value
function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) {
return staleRateThreshold;
}
/// @notice Gets the `WETH_TOKEN` variable value
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Gets the rateAsset variable value for a primitive
/// @return rateAsset_ The rateAsset variable value
/// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus
/// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the
/// behavior more explicit
function getRateAssetForPrimitive(address _primitive)
public
view
returns (RateAsset rateAsset_)
{
if (_primitive == WETH_TOKEN) {
return RateAsset.ETH;
}
return primitiveToAggregatorInfo[_primitive].rateAsset;
}
/// @notice Gets the unit variable value for a primitive
/// @return unit_ The unit variable value
function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) {
if (_primitive == WETH_TOKEN) {
return ETH_UNIT;
}
return primitiveToUnit[_primitive];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
/// @dev This contract acts as a centralized rate provider for mocks.
/// Suited for a dev environment, it doesn't take into account gas costs.
contract CentralizedRateProvider is Ownable {
using SafeMath for uint256;
address private immutable WETH;
uint256 private maxDeviationPerSender;
// Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env).
address private valueInterpreter;
address private aggregateDerivativePriceFeed;
address private primitivePriceFeed;
constructor(address _weth, uint256 _maxDeviationPerSender) public {
maxDeviationPerSender = _maxDeviationPerSender;
WETH = _weth;
}
/// @dev Calculates the value of a _baseAsset relative to a _quoteAsset.
/// Label to ValueInterprete's calcLiveAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public returns (uint256 value_) {
uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals());
uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals());
// 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) {
(value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
_amount,
_quoteAsset
);
return value_;
}
// 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) {
(uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
10**uint256(ERC20(_quoteAsset).decimals()),
_baseAsset
);
uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate);
value_ = _amount.mul(rate).div(baseDecimalsRate);
return value_;
}
// 3. If both assets are derivatives, calculate the rate against ETH.
(uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
baseDecimalsRate,
WETH
);
(uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
quoteDecimalsRate,
WETH
);
value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div(
baseDecimalsRate
);
return value_;
}
/// @dev Calculates a randomized live value of an asset
/// Aggregation of two randomization seeds: msg.sender, and by block.number.
function calcLiveAssetValueRandomized(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
// Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)]
uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress(
liveAssetValue,
msg.sender,
maxDeviationPerSender
);
// Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)]
value_ = __calcValueRandomizedByUint(
senderRandomizedValue_,
block.number,
_maxDeviationPerBlock
);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness
function calcLiveAssetValueRandomizedByBlockNumber(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness
function calcLiveAssetValueRandomizedBySender(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender);
return value_;
}
function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner {
maxDeviationPerSender = _maxDeviationPerSender;
}
/// @dev Connector from release environment, inject price variables into the provider.
function setReleasePriceAddresses(
address _valueInterpreter,
address _aggregateDerivativePriceFeed,
address _primitivePriceFeed
) external onlyOwner {
valueInterpreter = _valueInterpreter;
aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed;
primitivePriceFeed = _primitivePriceFeed;
}
// PRIVATE FUNCTIONS
/// @dev Calculates a a pseudo-randomized value as a seed an address
function __calcValueRandomizedByAddress(
uint256 _meanValue,
address _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Value between [0, 100]
uint256 senderRandomFactor = uint256(uint8(_seed))
.mul(100)
.div(256)
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation);
return value_;
}
/// @dev Calculates a a pseudo-randomized value as a seed an uint256
function __calcValueRandomizedByUint(
uint256 _meanValue,
uint256 _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Depending on the _seed number, it will be one of {20, 40, 60, 80, 100}
uint256 randomFactor = (_seed.mod(2).mul(20))
.add((_seed.mod(3).mul(40)))
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation);
return value_;
}
/// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation)
/// TODO: Refactor to use 18 decimal precision
function __calcDeviatedValue(
uint256 _meanValue,
uint256 _offset,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
return
_meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub(
_meanValue.mul(_maxDeviation).div(uint256(100))
);
}
///////////////////
// STATE GETTERS //
///////////////////
function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) {
return maxDeviationPerSender;
}
function getValueInterpreter() public view returns (address valueInterpreter_) {
return valueInterpreter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IUniswapV2Pair.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
/// @dev This price source mocks the integration with Uniswap Pair
/// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/>
contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) {
using SafeMath for uint256;
address private immutable TOKEN_0;
address private immutable TOKEN_1;
address private immutable CENTRALIZED_RATE_PROVIDER;
constructor(
address _centralizedRateProvider,
address _token0,
address _token1
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
TOKEN_0 = _token0;
TOKEN_1 = _token1;
}
/// @dev returns reserves for each token on the Uniswap Pair
/// Reserves will be used to calculate the pair price
/// Inherited from IUniswapV2Pair
function getReserves()
external
returns (
uint112 reserve0_,
uint112 reserve1_,
uint32 blockTimestampLast_
)
{
uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this));
reserve0_ = uint112(baseAmount);
reserve1_ = uint112(
CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN_0,
baseAmount,
TOKEN_1
)
);
return (reserve0_, reserve1_, blockTimestampLast_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Inherited from IUniswapV2Pair
function token0() public view returns (address) {
return TOKEN_0;
}
/// @dev Inherited from IUniswapV2Pair
function token1() public view returns (address) {
return TOKEN_1;
}
/// @dev Inherited from IUniswapV2Pair
function kLast() public pure returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MockToken is ERC20Burnable, Ownable {
using SafeMath for uint256;
mapping(address => bool) private addressToIsMinter;
modifier onlyMinter() {
require(
addressToIsMinter[msg.sender] || owner() == msg.sender,
"msg.sender is not owner or minter"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
_mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals)));
}
function mintFor(address _who, uint256 _amount) external onlyMinter {
_mint(_who, _amount);
}
function mint(uint256 _amount) external onlyMinter {
_mint(msg.sender, _amount);
}
function addMinters(address[] memory _minters) public onlyOwner {
for (uint256 i = 0; i < _minters.length; i++) {
addressToIsMinter[_minters[i]] = true;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @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 ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @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);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../release/core/fund/comptroller/ComptrollerLib.sol";
import "./MockToken.sol";
/// @title MockReentrancyToken Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions
contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) {
bool public bad;
address public comptrollerProxy;
function makeItReentracyToken(address _comptrollerProxy) external {
bad = true;
comptrollerProxy = _comptrollerProxy;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).redeemShares();
} else {
_transfer(_msgSender(), recipient, amount);
}
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).buyShares(
new address[](0),
new uint256[](0),
new uint256[](0)
);
} else {
_transfer(sender, recipient, amount);
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixProxyERC20.sol";
import "./../../release/interfaces/ISynthetixSynth.sol";
import "./MockToken.sol";
contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken {
using SafeMath for uint256;
bytes32 public override currencyKey;
uint256 public constant WAITING_PERIOD_SECS = 3 * 60;
mapping(address => uint256) public timelockByAccount;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes32 _currencyKey
) public MockToken(_name, _symbol, _decimals) {
currencyKey = _currencyKey;
}
function setCurrencyKey(bytes32 _currencyKey) external onlyOwner {
currencyKey = _currencyKey;
}
function _isLocked(address account) internal view returns (bool) {
return timelockByAccount[account] >= now;
}
function _beforeTokenTransfer(
address from,
address,
uint256
) internal override {
require(!_isLocked(from), "Cannot settle during waiting period");
}
function target() external view override returns (address) {
return address(this);
}
function isLocked(address account) external view returns (bool) {
return _isLocked(account);
}
function burnFrom(address account, uint256 amount) public override {
_burn(account, amount);
}
function lock(address account) public {
timelockByAccount[account] = now.add(WAITING_PERIOD_SECS);
}
function unlock(address account) public {
timelockByAccount[account] = 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IUniswapV2Factory.sol";
import "../../../../interfaces/IUniswapV2Router2.sol";
import "../utils/AdapterBase.sol";
/// @title UniswapV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Uniswap v2
contract UniswapV2Adapter is AdapterBase {
using SafeMath for uint256;
address private immutable FACTORY;
address private immutable ROUTER;
constructor(
address _integrationManager,
address _router,
address _factory
) public AdapterBase(_integrationManager) {
FACTORY = _factory;
ROUTER = _router;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "UNISWAP_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAssets[0];
spendAssets_[1] = outgoingAssets[1];
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0];
spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1];
incomingAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
outgoingAssets[0],
outgoingAssets[1]
);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
incomingAssets[0],
incomingAssets[1]
);
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](2);
incomingAssets_[0] = incomingAssets[0];
incomingAssets_[1] = incomingAssets[1];
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0];
minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1];
} else if (_selector == TAKE_ORDER_SELECTOR) {
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2");
spendAssets_ = new address[](1);
spendAssets_[0] = path[0];
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = path[path.length - 1];
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
uint256[2] memory minOutgoingAssetAmounts,
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(
_vaultProxy,
outgoingAssets[0],
outgoingAssets[1],
maxOutgoingAssetAmounts[0],
maxOutgoingAssetAmounts[1],
minOutgoingAssetAmounts[0],
minOutgoingAssetAmounts[1]
);
}
/// @notice Redeems pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
// More efficient to parse pool token from _encodedAssetTransferArgs than external call
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__redeem(
_vaultProxy,
spendAssets[0],
outgoingAssetAmount,
incomingAssets[0],
incomingAssets[1],
minIncomingAssetAmounts[0],
minIncomingAssetAmounts[1]
);
}
/// @notice Trades assets on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
__takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the lend encoded call arguments
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[2] memory outgoingAssets_,
uint256[2] memory maxOutgoingAssetAmounts_,
uint256[2] memory minOutgoingAssetAmounts_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256));
}
/// @dev Helper to decode the redeem encoded call arguments
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
address[2] memory incomingAssets_,
uint256[2] memory minIncomingAssetAmounts_
)
{
return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2]));
}
/// @dev Helper to decode the take order encoded call arguments
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[] memory path_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[], uint256, uint256));
}
/// @dev Helper to execute lend. Avoids stack-too-deep error.
function __lend(
address _vaultProxy,
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired);
__approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired);
// Execute lend on Uniswap
IUniswapV2Router2(ROUTER).addLiquidity(
_tokenA,
_tokenB,
_amountADesired,
_amountBDesired,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute redeem. Avoids stack-too-deep error.
function __redeem(
address _vaultProxy,
address _poolToken,
uint256 _poolTokenAmount,
address _tokenA,
address _tokenB,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount);
// Execute redeem on Uniswap
IUniswapV2Router2(ROUTER).removeLiquidity(
_tokenA,
_tokenB,
_poolTokenAmount,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
uint256 _outgoingAssetAmount,
uint256 _minIncomingAssetAmount,
address[] memory _path
) private {
__approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount);
// Execute fill
IUniswapV2Router2(ROUTER).swapExactTokensForTokens(
_outgoingAssetAmount,
_minIncomingAssetAmount,
_path,
_vaultProxy,
block.timestamp.add(1)
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FACTORY` variable
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `ROUTER` variable
/// @return router_ The `ROUTER` variable value
function getRouter() external view returns (address router_) {
return ROUTER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title UniswapV2Router2 Interface
/// @author Enzyme Council <[email protected]>
/// @dev Minimal interface for our interactions with Uniswap V2's Router2
interface IUniswapV2Router2 {
function addLiquidity(
address,
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
);
function removeLiquidity(
address,
address,
uint256,
uint256,
uint256,
address,
uint256
) external returns (uint256, uint256);
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeToken.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CurvePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Curve pool tokens
contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event DerivativeAdded(
address indexed derivative,
address indexed pool,
address indexed invariantProxyAsset,
uint256 invariantProxyAssetDecimals
);
event DerivativeRemoved(address indexed derivative);
// Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes.
// We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools.
struct DerivativeInfo {
address pool;
address invariantProxyAsset;
uint256 invariantProxyAssetDecimals;
}
uint256 private constant VIRTUAL_PRICE_UNIT = 10**18;
address private immutable ADDRESS_PROVIDER;
mapping(address => DerivativeInfo) private derivativeToInfo;
constructor(address _dispatcher, address _addressProvider)
public
DispatcherOwnerMixin(_dispatcher)
{
ADDRESS_PROVIDER = _addressProvider;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
public
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative];
require(
derivativeInfo.pool != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
underlyings_ = new address[](1);
underlyings_[0] = derivativeInfo.invariantProxyAsset;
underlyingAmounts_ = new uint256[](1);
if (derivativeInfo.invariantProxyAssetDecimals == 18) {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.div(VIRTUAL_PRICE_UNIT);
} else {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.mul(10**derivativeInfo.invariantProxyAssetDecimals)
.div(VIRTUAL_PRICE_UNIT.mul(2));
}
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return derivativeToInfo[_asset].pool != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
/// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants,
/// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools
function addDerivatives(
address[] calldata _derivatives,
address[] calldata _invariantProxyAssets
) external onlyDispatcherOwner {
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(
_derivatives.length == _invariantProxyAssets.length,
"addDerivatives: Unequal arrays"
);
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(
_invariantProxyAssets[i] != address(0),
"addDerivatives: Empty invariantProxyAsset"
);
require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set");
// First, try assuming that the derivative is an LP token
ICurveRegistry curveRegistryContract = ICurveRegistry(
ICurveAddressProvider(ADDRESS_PROVIDER).get_registry()
);
address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]);
// If the derivative is not a valid LP token, try to treat it as a liquidity gauge token
if (pool == address(0)) {
// We cannot confirm whether a liquidity gauge token is a valid token
// for a particular liquidity gauge, due to some pools using
// old liquidity gauge contracts that did not incorporate a token
pool = curveRegistryContract.get_pool_from_lp_token(
ICurveLiquidityGaugeToken(_derivatives[i]).lp_token()
);
// Likely unreachable as above calls will revert on Curve, but doesn't hurt
require(
pool != address(0),
"addDerivatives: Not a valid LP token or liquidity gauge token"
);
}
uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals();
derivativeToInfo[_derivatives[i]] = DerivativeInfo({
pool: pool,
invariantProxyAsset: _invariantProxyAssets[i],
invariantProxyAssetDecimals: invariantProxyAssetDecimals
});
// Confirm that a non-zero price can be returned for the registered derivative
(, uint256[] memory underlyingAmounts) = calcUnderlyingValues(
_derivatives[i],
1 ether
);
require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price");
emit DerivativeAdded(
_derivatives[i],
pool,
_invariantProxyAssets[i],
invariantProxyAssetDecimals
);
}
}
/// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative");
require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set");
delete derivativeToInfo[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `DerivativeInfo` for a given derivative
/// @param _derivative The derivative for which to get the `DerivativeInfo`
/// @return derivativeInfo_ The `DerivativeInfo` value
function getDerivativeInfo(address _derivative)
external
view
returns (DerivativeInfo memory derivativeInfo_)
{
return derivativeToInfo[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface ICurveAddressProvider {
function get_address(uint256) external view returns (address);
function get_registry() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeToken interface
/// @author Enzyme Council <[email protected]>
/// @notice Common interface functions for all Curve liquidity gauge token contracts
interface ICurveLiquidityGaugeToken {
function lp_token() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityPool interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityPool {
function coins(uint256) external view returns (address);
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistry interface
/// @author Enzyme Council <[email protected]>
interface ICurveRegistry {
function get_gauges(address) external view returns (address[10] memory, int128[10] memory);
function get_lp_token(address) external view returns (address);
function get_pool_from_lp_token(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeV2.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../../interfaces/ICurveStableSwapSteth.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase2.sol";
/// @title CurveLiquidityStethAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth)
contract CurveLiquidityStethAdapter is AdapterBase2 {
int128 private constant POOL_INDEX_ETH = 0;
int128 private constant POOL_INDEX_STETH = 1;
address private immutable LIQUIDITY_GAUGE_TOKEN;
address private immutable LP_TOKEN;
address private immutable POOL;
address private immutable STETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _liquidityGaugeToken,
address _lpToken,
address _pool,
address _stethToken,
address _wethToken
) public AdapterBase2(_integrationManager) {
LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken;
LP_TOKEN = _lpToken;
POOL = _pool;
STETH_TOKEN = _stethToken;
WETH_TOKEN = _wethToken;
// Max approve contracts to spend relevant tokens
ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max);
ERC20(_stethToken).safeApprove(_pool, type(uint256).max);
}
/// @dev Needed to receive ETH from redemption and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_LIQUIDITY_STETH";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) {
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
if (outgoingWethAmount > 0 && outgoingStethAmount > 0) {
spendAssets_ = new address[](2);
spendAssets_[0] = WETH_TOKEN;
spendAssets_[1] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingWethAmount;
spendAssetAmounts_[1] = outgoingStethAmount;
} else if (outgoingWethAmount > 0) {
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingWethAmount;
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingStethAmount;
}
incomingAssets_ = new address[](1);
if (_selector == LEND_SELECTOR) {
incomingAssets_[0] = LP_TOKEN;
} else {
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
if (_selector == REDEEM_SELECTOR) {
spendAssets_[0] = LP_TOKEN;
} else {
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
if (receiveSingleAsset) {
incomingAssets_ = new address[](1);
minIncomingAssetAmounts_ = new uint256[](1);
if (minIncomingWethAmount == 0) {
require(
minIncomingStethAmount > 0,
"parseAssetsForMethod: No min asset amount specified for receiveSingleAsset"
);
incomingAssets_[0] = STETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingStethAmount;
} else {
require(
minIncomingStethAmount == 0,
"parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset"
);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
}
} else {
incomingAssets_ = new address[](2);
incomingAssets_[0] = WETH_TOKEN;
incomingAssets_[1] = STETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
minIncomingAssetAmounts_[1] = minIncomingStethAmount;
}
} else if (_selector == STAKE_SELECTOR) {
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLPTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLPTokenAmount;
} else if (_selector == UNSTAKE_SELECTOR) {
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
}
/// @notice Lends assets for steth LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lendAndStake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
__stake(ERC20(LP_TOKEN).balanceOf(address(this)));
}
/// @notice Redeems steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLPTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__redeem(
outgoingLPTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
/// @notice Stakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function stake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
__stake(outgoingLPTokenAmount);
}
/// @notice Unstakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
}
/// @notice Unstakes steth LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
__redeem(
outgoingLiquidityGaugeTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to execute lend
function __lend(
uint256 _outgoingWethAmount,
uint256 _outgoingStethAmount,
uint256 _minIncomingLPTokenAmount
) private {
if (_outgoingWethAmount > 0) {
IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount);
}
ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}(
[_outgoingWethAmount, _outgoingStethAmount],
_minIncomingLPTokenAmount
);
}
/// @dev Helper to execute redeem
function __redeem(
uint256 _outgoingLPTokenAmount,
uint256 _minIncomingWethAmount,
uint256 _minIncomingStethAmount,
bool _redeemSingleAsset
) private {
if (_redeemSingleAsset) {
// "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been
// validated in parseAssetsForMethod()
if (_minIncomingWethAmount > 0) {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_ETH,
_minIncomingWethAmount
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
} else {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_STETH,
_minIncomingStethAmount
);
}
} else {
ICurveStableSwapSteth(POOL).remove_liquidity(
_outgoingLPTokenAmount,
[_minIncomingWethAmount, _minIncomingStethAmount]
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
/// @dev Helper to execute stake
function __stake(uint256 _lpTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this));
}
/// @dev Helper to execute unstake
function __unstake(uint256 _liquidityGaugeTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingWethAmount_,
uint256 outgoingStethAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256));
}
/// @dev Helper to decode the encoded call arguments for redeeming.
/// If `receiveSingleAsset_` is `true`, then one (and only one) of
/// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0
/// to indicate which asset is to be received.
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256 minIncomingWethAmount_,
uint256 minIncomingStethAmount_,
bool receiveSingleAsset_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLPTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLiquidityGaugeTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable
/// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value
function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) {
return LIQUIDITY_GAUGE_TOKEN;
}
/// @notice Gets the `LP_TOKEN` variable
/// @return lpToken_ The `LP_TOKEN` variable value
function getLPToken() external view returns (address lpToken_) {
return LP_TOKEN;
}
/// @notice Gets the `POOL` variable
/// @return pool_ The `POOL` variable value
function getPool() external view returns (address pool_) {
return POOL;
}
/// @notice Gets the `STETH_TOKEN` variable
/// @return stethToken_ The `STETH_TOKEN` variable value
function getStethToken() external view returns (address stethToken_) {
return STETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeV2 interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityGaugeV2 {
function deposit(uint256, address) external;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveStableSwapSteth interface
/// @author Enzyme Council <[email protected]>
interface ICurveStableSwapSteth {
function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256);
function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory);
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./AdapterBase.sol";
/// @title AdapterBase2 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters that extends AdapterBase
/// @dev This is a temporary contract that will be merged into AdapterBase with the next release
abstract contract AdapterBase2 is AdapterBase {
/// @dev Provides a standard implementation for transferring incoming assets and
/// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action
modifier postActionAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(
,
address[] memory spendAssets,
,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @dev Helper to transfer full asset balances of current contract to the specified target
function __transferFullAssetBalances(address _target, address[] memory _assets) internal {
for (uint256 i = 0; i < _assets.length; i++) {
uint256 balance = ERC20(_assets[i]).balanceOf(address(this));
if (balance > 0) {
ERC20(_assets[i]).safeTransfer(_target, balance);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IParaSwapAugustusSwapper.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title ParaSwapAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with ParaSwap
contract ParaSwapAdapter is AdapterBase {
using SafeMath for uint256;
string private constant REFERRER = "enzyme";
address private immutable EXCHANGE;
address private immutable TOKEN_TRANSFER_PROXY;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _tokenTransferProxy,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
TOKEN_TRANSFER_PROXY = _tokenTransferProxy;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH refund from sent network fees
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PARASWAP";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
// Format outgoing assets depending on if there are network fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
// We are not performing special logic if the incomingAsset is the fee asset
if (outgoingAsset == WETH_TOKEN) {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAsset;
spendAssets_[1] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingAssetAmount;
spendAssetAmounts_[1] = totalNetworkFees;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on ParaSwap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
__takeOrder(_vaultProxy, _encodedCallArgs);
}
// PRIVATE FUNCTIONS
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to decode the encoded callOnIntegration call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics
address outgoingAsset_,
uint256 outgoingAssetAmount_,
IParaSwapAugustusSwapper.Path[] memory paths_
)
{
return
abi.decode(
_encodedCallArgs,
(address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[])
);
}
/// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata.
/// Avoids the stack-too-deep error.
function __encodeMultiSwapCallData(
address _vaultProxy,
address _incomingAsset,
uint256 _minIncomingAssetAmount,
uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics
address _outgoingAsset,
uint256 _outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private pure returns (bytes memory multiSwapCallData) {
return
abi.encodeWithSelector(
IParaSwapAugustusSwapper.multiSwap.selector,
_outgoingAsset, // fromToken
_incomingAsset, // toToken
_outgoingAssetAmount, // fromAmount
_minIncomingAssetAmount, // toAmount
_expectedIncomingAssetAmount, // expectedAmount
_paths, // path
0, // mintPrice
payable(_vaultProxy), // beneficiary
0, // donationPercentage
REFERRER // referrer
);
}
/// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call.
/// Avoids the stack-too-deep error.
function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees)
private
{
(bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}(
_multiSwapCallData
);
require(success, string(returnData));
}
/// @dev Helper for the inner takeOrder() logic.
/// Avoids the stack-too-deep error.
function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private {
(
address incomingAsset,
uint256 minIncomingAssetAmount,
uint256 expectedIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount);
// If there are network fees, unwrap enough WETH to cover the fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
__unwrapWeth(totalNetworkFees);
}
// Get the callData for the low-level multiSwap() call
bytes memory multiSwapCallData = __encodeMultiSwapCallData(
_vaultProxy,
incomingAsset,
minIncomingAssetAmount,
expectedIncomingAssetAmount,
outgoingAsset,
outgoingAssetAmount,
paths
);
// Execute the trade on ParaSwap
__executeMultiSwap(multiSwapCallData, totalNetworkFees);
// If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned
if (totalNetworkFees > 0) {
__wrapEth();
}
}
/// @dev Helper to unwrap specified amount of WETH into ETH.
/// Avoids the stack-too-deep error.
function __unwrapWeth(uint256 _amount) private {
IWETH(payable(WETH_TOKEN)).withdraw(_amount);
}
/// @dev Helper to wrap all ETH in contract as WETH.
/// Avoids the stack-too-deep error.
function __wrapEth() private {
uint256 ethBalance = payable(address(this)).balance;
if (ethBalance > 0) {
IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}();
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `TOKEN_TRANSFER_PROXY` variable
/// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value
function getTokenTransferProxy() external view returns (address tokenTransferProxy_) {
return TOKEN_TRANSFER_PROXY;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title ParaSwap IAugustusSwapper interface
interface IParaSwapAugustusSwapper {
struct Route {
address payable exchange;
address targetExchange;
uint256 percent;
bytes payload;
uint256 networkFee;
}
struct Path {
address to;
uint256 totalNetworkFee;
Route[] routes;
}
function multiSwap(
address,
address,
uint256,
uint256,
uint256,
Path[] calldata,
uint256,
address payable,
uint256,
string calldata
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IParaSwapAugustusSwapper.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockParaSwapIntegratee is SwapperBase {
using SafeMath for uint256;
address private immutable MOCK_CENTRALIZED_RATE_PROVIDER;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public {
MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Must be `public` to avoid error
function multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
uint256, // toAmount (min received amount)
uint256, // expectedAmount
IParaSwapAugustusSwapper.Path[] memory _paths,
uint256, // mintPrice
address, // beneficiary
uint256, // donationPercentage
string memory // referrer
) public payable returns (uint256) {
return __multiSwap(_fromToken, _toToken, _fromAmount, _paths);
}
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to avoid the stack-too-deep error
function __multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private returns (uint256) {
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _toToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation);
uint256 totalNetworkFees = __calcTotalNetworkFees(_paths);
address[] memory assetsToIntegratee;
uint256[] memory assetsToIntegrateeAmounts;
if (totalNetworkFees > 0) {
assetsToIntegratee = new address[](2);
assetsToIntegratee[1] = ETH_ADDRESS;
assetsToIntegrateeAmounts = new uint256[](2);
assetsToIntegrateeAmounts[1] = totalNetworkFees;
} else {
assetsToIntegratee = new address[](1);
assetsToIntegrateeAmounts = new uint256[](1);
}
assetsToIntegratee[0] = _fromToken;
assetsToIntegrateeAmounts[0] = _fromAmount;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
///////////////////
// STATE GETTERS //
///////////////////
function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) {
return blockNumberDeviation;
}
function getCentralizedRateProvider()
external
view
returns (address centralizedRateProvider_)
{
return MOCK_CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract SwapperBase is EthConstantMixin {
receive() external payable {}
function __swapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256 _actualRate
) internal returns (uint256 destAmount_) {
address[] memory assetsToIntegratee = new address[](1);
assetsToIntegratee[0] = _srcToken;
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
assetsToIntegrateeAmounts[0] = _srcAmount;
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _destToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = _actualRate;
__swap(
_trader,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
function __swap(
address payable _trader,
address[] memory _assetsToIntegratee,
uint256[] memory _assetsToIntegrateeAmounts,
address[] memory _assetsFromIntegratee,
uint256[] memory _assetsFromIntegrateeAmounts
) internal {
// Take custody of incoming assets
for (uint256 i = 0; i < _assetsToIntegratee.length; i++) {
address asset = _assetsToIntegratee[i];
uint256 amount = _assetsToIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsToIntegratee");
require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts");
// Incoming ETH amounts can be ignored
if (asset == ETH_ADDRESS) {
continue;
}
ERC20(asset).transferFrom(_trader, address(this), amount);
}
// Distribute outgoing assets
for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) {
address asset = _assetsFromIntegratee[i];
uint256 amount = _assetsFromIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsFromIntegratee");
require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts");
if (asset == ETH_ADDRESS) {
_trader.transfer(amount);
} else {
ERC20(asset).transfer(_trader, amount);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
abstract contract EthConstantMixin {
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/NormalizedRateProviderBase.sol";
import "../../utils/SwapperBase.sol";
abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
NormalizedRateProviderBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
override
returns (uint256)
{
// 1. Return constant if base asset is quote asset
if (_baseAsset == _quoteAsset) {
return 10**RATE_PRECISION;
}
// 2. Check for a direct rate
uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset];
if (directRate > 0) {
return directRate;
}
// 3. Check for inverse direct rate
uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset];
if (iDirectRate > 0) {
return 10**(RATE_PRECISION.mul(2)).div(iDirectRate);
}
// 4. Else return 1
return 10**RATE_PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./RateProviderBase.sol";
abstract contract NormalizedRateProviderBase is RateProviderBase {
using SafeMath for uint256;
uint256 public immutable RATE_PRECISION;
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
) public RateProviderBase(_specialAssets, _specialAssetDecimals) {
RATE_PRECISION = _ratePrecision;
for (uint256 i = 0; i < _defaultRateAssets.length; i++) {
for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) {
assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] =
10**_ratePrecision;
assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] =
10**_ratePrecision;
}
}
}
// TODO: move to main contracts' utils for use with prices
function __calcDenormalizedQuoteAssetAmount(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _rate
) internal view returns (uint256) {
return
_rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div(
10**(RATE_PRECISION.add(_baseAssetDecimals))
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract RateProviderBase is EthConstantMixin {
mapping(address => mapping(address => uint256)) public assetToAssetRate;
// Handles non-ERC20 compliant assets like ETH and USD
mapping(address => uint8) public specialAssetToDecimals;
constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public {
require(
_specialAssets.length == _specialAssetDecimals.length,
"constructor: _specialAssets and _specialAssetDecimals are uneven lengths"
);
for (uint256 i = 0; i < _specialAssets.length; i++) {
specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i];
}
specialAssetToDecimals[ETH_ADDRESS] = 18;
}
function __getDecimalsForAsset(address _asset) internal view returns (uint256) {
uint256 decimals = specialAssetToDecimals[_asset];
if (decimals == 0) {
decimals = uint256(ERC20(_asset).decimals());
}
return decimals;
}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
virtual
returns (uint256)
{
return assetToAssetRate[_baseAsset][_quoteAsset];
}
function setRates(
address[] calldata _baseAssets,
address[] calldata _quoteAssets,
uint256[] calldata _rates
) external {
require(
_baseAssets.length == _quoteAssets.length,
"setRates: _baseAssets and _quoteAssets are uneven lengths"
);
require(
_baseAssets.length == _rates.length,
"setRates: _baseAssets and _rates are uneven lengths"
);
for (uint256 i = 0; i < _baseAssets.length; i++) {
assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i];
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @title AssetUnitCacheMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin to store a cache of asset units
abstract contract AssetUnitCacheMixin {
event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit);
mapping(address => uint256) private assetToUnit;
/// @notice Caches the decimal-relative unit for a given asset
/// @param _asset The asset for which to cache the decimal-relative unit
/// @dev Callable by any account
function cacheAssetUnit(address _asset) public {
uint256 prevUnit = getCachedUnitForAsset(_asset);
uint256 nextUnit = 10**uint256(ERC20(_asset).decimals());
if (nextUnit != prevUnit) {
assetToUnit[_asset] = nextUnit;
emit AssetUnitCached(_asset, prevUnit, nextUnit);
}
}
/// @notice Caches the decimal-relative units for multiple given assets
/// @param _assets The assets for which to cache the decimal-relative units
/// @dev Callable by any account
function cacheAssetUnits(address[] memory _assets) public {
for (uint256 i; i < _assets.length; i++) {
cacheAssetUnit(_assets[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the cached decimal-relative unit for a given asset
/// @param _asset The asset for which to get the cached decimal-relative unit
/// @return unit_ The cached decimal-relative unit
function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) {
return assetToUnit[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
/// @title SinglePeggedDerivativePriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying
abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed {
address private immutable DERIVATIVE;
address private immutable UNDERLYING;
constructor(address _derivative, address _underlying) public {
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"constructor: Unequal decimals"
);
DERIVATIVE = _derivative;
UNDERLYING = _underlying;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = UNDERLYING;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == DERIVATIVE;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE` variable value
/// @return derivative_ The `DERIVATIVE` variable value
function getDerivative() external view returns (address derivative_) {
return DERIVATIVE;
}
/// @notice Gets the `UNDERLYING` variable value
/// @return underlying_ The `UNDERLYING` variable value
function getUnderlying() external view returns (address underlying_) {
return UNDERLYING;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SinglePeggedDerivativePriceFeedBase
contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _derivative, address _underlying)
public
SinglePeggedDerivativePriceFeedBase(_derivative, _underlying)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title StakehoundEthPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH
contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]yme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title LidoStethPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/)
contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IKyberNetworkProxy.sol";
import "../../../../interfaces/IWETH.sol";
import "../../../../utils/MathHelpers.sol";
import "../utils/AdapterBase.sol";
/// @title KyberAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Kyber Network
contract KyberAdapter is AdapterBase, MathHelpers {
address private immutable EXCHANGE;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "KYBER_NETWORK";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(
incomingAsset != outgoingAsset,
"parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same"
);
require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Kyber
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
uint256 minExpectedRate = __calcNormalizedRate(
ERC20(outgoingAsset).decimals(),
outgoingAssetAmount,
ERC20(incomingAsset).decimals(),
minIncomingAssetAmount
);
if (outgoingAsset == WETH_TOKEN) {
__swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate);
} else if (incomingAsset == WETH_TOKEN) {
__swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate);
} else {
__swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
/// @dev Executes a swap of ETH to ERC20
function __swapNativeAssetToToken(
address _incomingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}(
_incomingAsset,
_minExpectedRate
);
}
/// @dev Executes a swap of ERC20 to ETH
function __swapTokenToNativeAsset(
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToEther(
_outgoingAsset,
_outgoingAssetAmount,
_minExpectedRate
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
/// @dev Executes a swap of ERC20 to ERC20
function __swapTokenToToken(
address _incomingAsset,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToToken(
_outgoingAsset,
_outgoingAssetAmount,
_incomingAsset,
_minExpectedRate
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Kyber Network interface
interface IKyberNetworkProxy {
function swapEtherToToken(address, uint256) external payable returns (uint256);
function swapTokenToEther(
address,
uint256,
uint256
) external returns (uint256);
function swapTokenToToken(
address,
uint256,
address,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/utils/MathHelpers.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers {
using SafeMath for uint256;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable WETH;
uint256 private constant PRECISION = 18;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address _centralizedRateProvider,
address _weth,
uint256 _blockNumberDeviation
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
WETH = _weth;
blockNumberDeviation = _blockNumberDeviation;
}
function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount);
return msg.value;
}
function swapTokenToEther(
address _srcToken,
uint256 _srcAmount,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount);
return _srcAmount;
}
function swapTokenToToken(
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount);
return _srcAmount;
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
function getExpectedRate(
address _srcToken,
address _destToken,
uint256 _amount
) external returns (uint256 rate_, uint256 worstRate_) {
if (_srcToken == ETH_ADDRESS) {
_srcToken = WETH;
}
if (_destToken == ETH_ADDRESS) {
_destToken = WETH;
}
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken);
rate_ = __calcNormalizedRate(
ERC20(_srcToken).decimals(),
_amount,
ERC20(_destToken).decimals(),
destAmount
);
worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100);
}
///////////////////
// STATE GETTERS //
///////////////////
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getWeth() public view returns (address) {
return WETH;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/MockChainlinkPriceSource.sol";
/// @dev This price source offers two different options getting prices
/// The first one is getting a fixed rate, which can be useful for tests
/// The second approach calculates dinamically the rate making use of a chainlink price source
/// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates }
contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates {
using SafeMath for uint256;
mapping(bytes32 => uint256) private fixedRate;
mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator;
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
constructor(address _ethUsdAggregator) public {
currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({
aggregator: _ethUsdAggregator,
rateAsset: RateAsset.USD
});
}
function setPriceSourcesForCurrencyKeys(
bytes32[] calldata _currencyKeys,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyOwner {
require(
_currencyKeys.length == _aggregators.length &&
_rateAssets.length == _aggregators.length
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
}
}
function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner {
fixedRate[_currencyKey] = _rate;
}
/// @dev Calculates the rate from a currency key against USD
function rateAndInvalid(bytes32 _currencyKey)
external
view
override
returns (uint256 rate_, bool isInvalid_)
{
uint256 storedRate = getFixedRate(_currencyKey);
if (storedRate != 0) {
rate_ = storedRate;
} else {
AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey);
address aggregator = aggregatorInfo.aggregator;
if (aggregator == address(0)) {
rate_ = 0;
isInvalid_ = true;
return (rate_, isInvalid_);
}
uint256 decimals = MockChainlinkPriceSource(aggregator).decimals();
rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul(
10**(uint256(18).sub(decimals))
);
if (aggregatorInfo.rateAsset == RateAsset.ETH) {
uint256 ethToUsd = uint256(
MockChainlinkPriceSource(
getAggregatorFromCurrencyKey(bytes32("ETH"))
.aggregator
)
.latestAnswer()
);
rate_ = rate_.mul(ethToUsd).div(10**8);
}
}
isInvalid_ = (rate_ == 0);
return (rate_, isInvalid_);
}
///////////////////
// STATE GETTERS //
///////////////////
function getAggregatorFromCurrencyKey(bytes32 _currencyKey)
public
view
returns (AggregatorInfo memory _aggregator)
{
return currencyKeyToAggregator[_currencyKey];
}
function getFixedRate(bytes32 _currencyKey) public view returns (uint256) {
return fixedRate[_currencyKey];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
contract MockChainlinkPriceSource {
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
uint256 public DECIMALS;
int256 public latestAnswer;
uint256 public latestTimestamp;
uint256 public roundId;
address public aggregator;
constructor(uint256 _decimals) public {
DECIMALS = _decimals;
latestAnswer = int256(10**_decimals);
latestTimestamp = now;
roundId = 1;
aggregator = address(this);
}
function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external {
latestAnswer = _nextAnswer;
latestTimestamp = _nextTimestamp;
roundId = roundId + 1;
emit AnswerUpdated(latestAnswer, roundId, latestTimestamp);
}
function setAggregator(address _nextAggregator) external {
aggregator = _nextAggregator;
}
function decimals() public view returns (uint256) {
return DECIMALS;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockSynthetixToken.sol";
/// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts
/// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals
/// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts>
contract MockSynthetixIntegratee is Ownable, MockToken {
using SafeMath for uint256;
mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval;
mapping(bytes32 => address) private currencyKeyToSynth;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable EXCHANGE_RATES;
uint256 private immutable FEE;
uint256 private constant UNIT_FEE = 1000;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _centralizedRateProvider,
address _exchangeRates,
uint256 _fee
) public MockToken(_name, _symbol, _decimals) {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
EXCHANGE_RATES = address(_exchangeRates);
FEE = _fee;
}
receive() external payable {}
function exchangeOnBehalfWithTracking(
address _exchangeForAddress,
bytes32 _srcCurrencyKey,
uint256 _srcAmount,
bytes32 _destinationCurrencyKey,
address,
bytes32
) external returns (uint256 amountReceived_) {
require(
canExchangeFor(_exchangeForAddress, msg.sender),
"exchangeOnBehalfWithTracking: Not approved to act on behalf"
);
amountReceived_ = __calculateAndSwap(
_exchangeForAddress,
_srcAmount,
_srcCurrencyKey,
_destinationCurrencyKey
);
return amountReceived_;
}
function getAmountsForExchange(
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
)
public
returns (
uint256 amountReceived_,
uint256 fee_,
uint256 exchangeFeeRate_
)
{
address srcToken = currencyKeyToSynth[_srcCurrencyKey];
address destToken = currencyKeyToSynth[_destCurrencyKey];
require(
currencyKeyToSynth[_srcCurrencyKey] != address(0) &&
currencyKeyToSynth[_destCurrencyKey] != address(0),
"getAmountsForExchange: Currency key doesn't have an associated synth"
);
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken);
exchangeFeeRate_ = FEE;
amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE);
fee_ = destAmount.sub(amountReceived_);
return (amountReceived_, fee_, exchangeFeeRate_);
}
function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths)
external
{
require(
_currencyKeys.length == _synths.length,
"setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths"
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToSynth[_currencyKeys[i]] = _synths[i];
}
}
function approveExchangeOnBehalf(address _delegate) external {
authorizerToDelegateToApproval[msg.sender][_delegate] = true;
}
function __calculateAndSwap(
address _exchangeForAddress,
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
) private returns (uint256 amountReceived_) {
MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]);
MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]);
require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed");
require(
address(destSynth) != address(0),
"__calculateAndSwap: Destination synth is not listed"
);
require(
!srcSynth.isLocked(_exchangeForAddress),
"__calculateAndSwap: Cannot settle during waiting period"
);
(amountReceived_, , ) = getAmountsForExchange(
_srcAmount,
_srcCurrencyKey,
_destCurrencyKey
);
srcSynth.burnFrom(_exchangeForAddress, _srcAmount);
destSynth.mintFor(_exchangeForAddress, amountReceived_);
destSynth.lock(_exchangeForAddress);
return amountReceived_;
}
function requireAndGetAddress(bytes32 _name, string calldata)
external
view
returns (address resolvedAddress_)
{
if (_name == "ExchangeRates") {
return EXCHANGE_RATES;
}
return address(this);
}
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
)
{}
///////////////////
// STATE GETTERS //
///////////////////
function canExchangeFor(address _authorizer, address _delegate)
public
view
returns (bool canExchange_)
{
return authorizerToDelegateToApproval[_authorizer][_delegate];
}
function getExchangeRates() public view returns (address exchangeRates_) {
return EXCHANGE_RATES;
}
function getFee() public view returns (uint256 fee_) {
return FEE;
}
function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) {
return currencyKeyToSynth[_currencyKey];
}
function getUnitFee() public pure returns (uint256 fee_) {
return UNIT_FEE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../prices/CentralizedRateProvider.sol";
import "./utils/SimpleMockIntegrateeBase.sol";
/// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/>
/// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/>
contract MockUniswapV2Integratee is SwapperBase, Ownable {
using SafeMath for uint256;
mapping(address => mapping(address => address)) private assetToAssetToPair;
address private immutable CENTRALIZED_RATE_PROVIDER;
uint256 private constant PRECISION = 18;
// Set in %, defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair,
address _centralizedRateProvider,
uint256 _blockNumberDeviation
) public {
addPair(_listOfToken0, _listOfToken1, _listOfPair);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Adds the maximum possible value from {_amountADesired _amountBDesired}
/// Makes use of the value interpreter to perform those calculations
function addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
)
{
__addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired);
}
/// @dev Removes the specified amount of liquidity
/// Returns 50% of the incoming liquidity value on each token.
function removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity,
uint256,
uint256,
address,
uint256
) public returns (uint256, uint256) {
__removeLiquidity(_tokenA, _tokenB, _liquidity);
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256,
address[] calldata path,
address,
uint256
) external returns (uint256[] memory) {
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation);
__swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut);
}
/// @dev We don't calculate any intermediate values here because they aren't actually used
/// Returns the randomized by sender value of the edge path assets
function getAmountsOut(uint256 _amountIn, address[] calldata _path)
external
returns (uint256[] memory amounts_)
{
require(_path.length >= 2, "getAmountsOut: path must be >= 2");
address assetIn = _path[0];
address assetOut = _path[_path.length - 1];
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut);
amounts_ = new uint256[](_path.length);
amounts_[0] = _amountIn;
amounts_[_path.length - 1] = amountOut;
return amounts_;
}
function addPair(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair
) public onlyOwner {
require(
_listOfPair.length == _listOfToken0.length,
"constructor: _listOfPair and _listOfToken0 have an unequal length"
);
require(
_listOfPair.length == _listOfToken1.length,
"constructor: _listOfPair and _listOfToken1 have an unequal length"
);
for (uint256 i; i < _listOfPair.length; i++) {
address token0 = _listOfToken0[i];
address token1 = _listOfToken1[i];
address pair = _listOfPair[i];
assetToAssetToPair[token0][token1] = pair;
assetToAssetToPair[token1][token0] = pair;
}
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
// PRIVATE FUNCTIONS
/// Avoids stack-too-deep error.
function __addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired
) private {
address pair = getPair(_tokenA, _tokenB);
uint256 amountA;
uint256 amountB;
uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenA, _amountADesired, _tokenB);
uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA);
if (amountBFromA >= _amountBDesired) {
amountA = amountAFromB;
amountB = _amountBDesired;
} else {
amountA = _amountADesired;
amountB = amountBFromA;
}
uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA);
// Calculate the inverse rate to know the amount of LPToken to return from a unit of token
uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken);
// Total liquidity can be calculated as 2x liquidity from amount A
uint256 totalLiquidity = uint256(2).mul(
amountA.mul(inverseRate).div(uint256(10**PRECISION))
);
require(
ERC20(pair).balanceOf(address(this)) >= totalLiquidity,
"__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount"
);
address[] memory assetsToIntegratee = new address[](2);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](2);
address[] memory assetsFromIntegratee = new address[](1);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsToIntegratee[0] = _tokenA;
assetsToIntegrateeAmounts[0] = amountA;
assetsToIntegratee[1] = _tokenB;
assetsToIntegrateeAmounts[1] = amountB;
assetsFromIntegratee[0] = pair;
assetsFromIntegrateeAmounts[0] = totalLiquidity;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
/// Avoids stack-too-deep error.
function __removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity
) private {
address pair = assetToAssetToPair[_tokenA][_tokenB];
require(pair != address(0), "__removeLiquidity: this pair doesn't exist");
uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenA)
.div(uint256(2));
uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenB)
.div(uint256(2));
address[] memory assetsToIntegratee = new address[](1);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
address[] memory assetsFromIntegratee = new address[](2);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2);
assetsToIntegratee[0] = pair;
assetsToIntegrateeAmounts[0] = _liquidity;
assetsFromIntegratee[0] = _tokenA;
assetsFromIntegrateeAmounts[0] = amountA;
assetsFromIntegratee[1] = _tokenB;
assetsFromIntegrateeAmounts[1] = amountB;
require(
ERC20(_tokenA).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount"
);
require(
ERC20(_tokenB).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount"
);
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue
function feeTo() external pure returns (address) {
return address(0);
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
function getPair(address _token0, address _token1) public view returns (address) {
return assetToAssetToPair[_token0][_token1];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockIntegrateeBase.sol";
abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
MockIntegrateeBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRateAndSwapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken
) internal returns (uint256 destAmount_) {
uint256 actualRate = __getRate(_srcToken, _destToken);
__swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate);
return actualRate;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "../../prices/CentralizedRateProvider.sol";
import "../../utils/SwapperBase.sol";
contract MockCTokenBase is ERC20, SwapperBase, Ownable {
address internal immutable TOKEN;
address internal immutable CENTRALIZED_RATE_PROVIDER;
uint256 internal rate;
mapping(address => mapping(address => uint256)) internal _allowances;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
TOKEN = _token;
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
rate = _initialRate;
}
function approve(address _spender, uint256 _amount) public virtual override returns (bool) {
_allowances[msg.sender][_spender] = _amount;
return true;
}
/// @dev Overriden `allowance` function, give the integratee infinite approval by default
function allowance(address _owner, address _spender) public view override returns (uint256) {
if (_spender == address(this) || _owner == _spender) {
return 2**256 - 1;
} else {
return _allowances[_owner][_spender];
}
}
/// @dev Necessary as this contract doesn't directly inherit from MockToken
function mintFor(address _who, uint256 _amount) external onlyOwner {
_mint(_who, _amount);
}
/// @dev Necessary to allow updates on persistent deployments (e.g Kovan)
function setRate(uint256 _rate) public onlyOwner {
rate = _rate;
}
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual override returns (bool) {
_transfer(_sender, _recipient, _amount);
return true;
}
// INTERNAL FUNCTIONS
/// @dev Calculates the cTokenAmount given a tokenAmount
/// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset
function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) {
uint256 tokenDecimals = ERC20(TOKEN).decimals();
uint256 cTokenDecimals = decimals();
// Result in Token Decimals
uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN);
// Result in cToken decimals
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div(
tokenPerCTokenUnit
);
// Amount in token decimals, result in cToken decimals
cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Part of ICERC20 token interface
function underlying() public view returns (address) {
return TOKEN;
}
/// @dev Part of ICERC20 token interface.
/// Called from CompoundPriceFeed, returns the actual Rate cToken/Token
function exchangeRateStored() public view returns (uint256) {
return rate;
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCTokenIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate)
{}
function mint(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN,
_amount,
address(this)
);
__swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount);
return _amount;
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCEtherIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _weth,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate)
{}
function mint() external payable {
uint256 amount = msg.value;
uint256 destAmount = __calcCTokenAmount(amount);
__swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount);
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveSwapsERC20.sol";
import "../../../../interfaces/ICurveSwapsEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CurveExchangeAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for swapping assets on Curve <https://www.curve.fi/>
contract CurveExchangeAdapter is AdapterBase {
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address private immutable ADDRESS_PROVIDER;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _addressProvider,
address _wethToken
) public AdapterBase(_integrationManager) {
ADDRESS_PROVIDER = _addressProvider;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_EXCHANGE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(pool != address(0), "parseAssetsForMethod: No pool address provided");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Curve
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2);
__takeOrder(
_vaultProxy,
swaps,
pool,
outgoingAsset,
outgoingAssetAmount,
incomingAsset,
minIncomingAssetAmount
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the take order encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address pool_,
address outgoingAsset_,
uint256 outgoingAssetAmount_,
address incomingAsset_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256));
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
address _swaps,
address _pool,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
address _incomingAsset,
uint256 _minIncomingAssetAmount
) private {
if (_outgoingAsset == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount);
ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}(
_pool,
ETH_ADDRESS,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
} else if (_incomingAsset == WETH_TOKEN) {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
ETH_ADDRESS,
_outgoingAssetAmount,
_minIncomingAssetAmount,
address(this)
);
// wrap received ETH and send back to the vault
uint256 receivedAmount = payable(address(this)).balance;
IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}();
ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount);
} else {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsERC20 {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsEther Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsEther {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
import "./SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title PeggedDerivativesPriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings,
/// and have the same decimals as their underlying
abstract contract PeggedDerivativesPriceFeedBase is
IDerivativePriceFeed,
SingleUnderlyingDerivativeRegistryMixin
{
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address underlying = getUnderlyingForDerivative(_derivative);
require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = underlying;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return getUnderlyingForDerivative(_asset) != address(0);
}
/// @dev Provides validation that the derivative and underlying have the same decimals.
/// Can be overrode by the inheriting price feed using super() to implement further validation.
function __validateDerivative(address _derivative, address _underlying)
internal
virtual
override
{
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"__validateDerivative: Unequal decimals"
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../utils/DispatcherOwnerMixin.sol";
/// @title SingleUnderlyingDerivativeRegistryMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin for derivative price feeds that handle multiple derivatives
/// that each have a single underlying asset
abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address indexed underlying);
event DerivativeRemoved(address indexed derivative);
mapping(address => address) private derivativeToUnderlying;
constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {}
/// @notice Adds derivatives with corresponding underlyings to the price feed
/// @param _derivatives The derivatives to add
/// @param _underlyings The corresponding underlyings to add
function addDerivatives(address[] memory _derivatives, address[] memory _underlyings)
external
virtual
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(_underlyings[i] != address(0), "addDerivatives: Empty underlying");
require(
getUnderlyingForDerivative(_derivatives[i]) == address(0),
"addDerivatives: Value already set"
);
__validateDerivative(_derivatives[i], _underlyings[i]);
derivativeToUnderlying[_derivatives[i]] = _underlyings[i];
emit DerivativeAdded(_derivatives[i], _underlyings[i]);
}
}
/// @notice Removes derivatives from the price feed
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(
getUnderlyingForDerivative(_derivatives[i]) != address(0),
"removeDerivatives: Value not set"
);
delete derivativeToUnderlying[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair
function __validateDerivative(address, address) internal virtual {
// UNIMPLEMENTED
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the underlying asset for a given derivative
/// @param _derivative The derivative for which to get the underlying asset
/// @return underlying_ The underlying asset
function getUnderlyingForDerivative(address _derivative)
public
view
returns (address underlying_)
{
return derivativeToUnderlying[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of PeggedDerivativesPriceFeedBase
contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase {
constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin
contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin {
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAaveProtocolDataProvider.sol";
import "./utils/PeggedDerivativesPriceFeedBase.sol";
/// @title AavePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Aave
contract AavePriceFeed is PeggedDerivativesPriceFeedBase {
address private immutable PROTOCOL_DATA_PROVIDER;
constructor(address _dispatcher, address _protocolDataProvider)
public
PeggedDerivativesPriceFeedBase(_dispatcher)
{
PROTOCOL_DATA_PROVIDER = _protocolDataProvider;
}
function __validateDerivative(address _derivative, address _underlying) internal override {
super.__validateDerivative(_derivative, _underlying);
(address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER)
.getReserveTokensAddresses(_underlying);
require(
aTokenAddress == _derivative,
"__validateDerivative: Invalid aToken or token provided"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value
/// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value
function getProtocolDataProvider() external view returns (address protocolDataProvider_) {
return PROTOCOL_DATA_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveProtocolDataProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveProtocolDataProvider {
function getReserveTokensAddresses(address)
external
view
returns (
address,
address,
address
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol";
import "../../../../interfaces/IAaveLendingPool.sol";
import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol";
import "../utils/AdapterBase.sol";
/// @title AaveAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Aave Lending <https://aave.com/>
contract AaveAdapter is AdapterBase {
address private immutable AAVE_PRICE_FEED;
address private immutable LENDING_POOL_ADDRESS_PROVIDER;
uint16 private constant REFERRAL_CODE = 158;
constructor(
address _integrationManager,
address _lendingPoolAddressProvider,
address _aavePriceFeed
) public AdapterBase(_integrationManager) {
LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider;
AAVE_PRICE_FEED = _aavePriceFeed;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "AAVE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = aToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else if (_selector == REDEEM_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = aToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).deposit(
spendAssets[0],
spendAssetAmounts[0],
_vaultProxy,
REFERRAL_CODE
);
}
/// @notice Redeems an amount of aTokens from AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).withdraw(
incomingAssets[0],
spendAssetAmounts[0],
_vaultProxy
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address aToken, uint256 amount)
{
return abi.decode(_encodedCallArgs, (address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AAVE_PRICE_FEED` variable
/// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value
function getAavePriceFeed() external view returns (address aavePriceFeed_) {
return AAVE_PRICE_FEED;
}
/// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable
/// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value
function getLendingPoolAddressProvider()
external
view
returns (address lendingPoolAddressProvider_)
{
return LENDING_POOL_ADDRESS_PROVIDER;
}
/// @notice Gets the `REFERRAL_CODE` variable
/// @return referralCode_ The `REFERRAL_CODE` variable value
function getReferralCode() external pure returns (uint16 referralCode_) {
return REFERRAL_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPool interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPool {
function deposit(
address,
uint256,
address,
uint16
) external;
function withdraw(
address,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPoolAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPoolAddressProvider {
function getLendingPool() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings
contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Non-whitelisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Must whitelist denominationAsset"
);
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/// @title AddressListPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice An abstract mixin contract for policies that use an address list
abstract contract AddressListPolicyMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event AddressesAdded(address indexed comptrollerProxy, address[] items);
event AddressesRemoved(address indexed comptrollerProxy, address[] items);
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList;
// EXTERNAL FUNCTIONS
/// @notice Get all addresses in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @return list_ The addresses in the fund's list
function getList(address _comptrollerProxy) external view returns (address[] memory list_) {
list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length());
for (uint256 i = 0; i < list_.length; i++) {
list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i);
}
return list_;
}
// PUBLIC FUNCTIONS
/// @notice Check if an address is in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _item The address to check against the list
/// @return isInList_ True if the address is in the list
function isInList(address _comptrollerProxy, address _item)
public
view
returns (bool isInList_)
{
return comptrollerProxyToList[_comptrollerProxy].contains(_item);
}
// INTERNAL FUNCTIONS
/// @dev Helper to add addresses to the calling fund's list
function __addToList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__addToList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].add(_items[i]),
"__addToList: Address already exists in list"
);
}
emit AddressesAdded(_comptrollerProxy, _items);
}
/// @dev Helper to remove addresses from the calling fund's list
function __removeFromList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__removeFromList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].remove(_items[i]),
"__removeFromList: Address does not exist in list"
);
}
emit AddressesRemoved(_comptrollerProxy, _items);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings
contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Blacklisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
!assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Cannot blacklist denominationAsset"
);
__addToList(_comptrollerProxy, assets);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of adapters for use by a fund
contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPreValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook
abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (address adapter_, bytes4 selector_)
{
return abi.decode(_encodedRuleArgs, (address, bytes4));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title GuaranteedRedemption Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that guarantees that shares will either be continuously redeemable or
/// redeemable within a predictable daily window by preventing trading during a configurable daily period
contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin {
using SafeMath for uint256;
event AdapterAdded(address adapter);
event AdapterRemoved(address adapter);
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 startTimestamp,
uint256 duration
);
event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer);
struct RedemptionWindow {
uint256 startTimestamp;
uint256 duration;
}
uint256 private constant ONE_DAY = 24 * 60 * 60;
mapping(address => bool) private adapterToCanBlockRedemption;
mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow;
uint256 private redemptionWindowBuffer;
constructor(
address _policyManager,
address _fundDeployer,
uint256 _redemptionWindowBuffer,
address[] memory _redemptionBlockingAdapters
) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) {
redemptionWindowBuffer = _redemptionWindowBuffer;
__addRedemptionBlockingAdapters(_redemptionBlockingAdapters);
}
// EXTERNAL FUNCTIONS
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
(uint256 startTimestamp, uint256 duration) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
if (startTimestamp == 0) {
require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0");
return;
}
// Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer
require(
duration > 0 && duration <= 23 hours,
"addFundSettings: duration must be between 1 second and 23 hours"
);
comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp;
comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration;
emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "GUARANTEED_REDEMPTION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
if (!adapterCanBlockRedemption(_adapter)) {
return true;
}
RedemptionWindow memory redemptionWindow
= comptrollerProxyToRedemptionWindow[_comptrollerProxy];
// If no RedemptionWindow is set, the fund can never use redemption-blocking adapters
if (redemptionWindow.startTimestamp == 0) {
return false;
}
uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart(
redemptionWindow.startTimestamp
);
// A fund can't trade during its redemption window, nor in the buffer beforehand.
// The lower bound is only relevant when the startTimestamp is in the future,
// so we check it last.
if (
block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) ||
block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer)
) {
return true;
}
return false;
}
/// @notice Sets a new value for the redemptionWindowBuffer variable
/// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer
/// @dev The redemptionWindowBuffer is added to the beginning of the redemption window,
/// and should always be >= the longest potential block on redemption amongst all adapters.
/// (e.g., Synthetix blocks token transfers during a timelock after trading synths)
function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer)
external
onlyFundDeployerOwner
{
uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer;
require(
_nextRedemptionWindowBuffer != prevRedemptionWindowBuffer,
"setRedemptionWindowBuffer: Value already set"
);
redemptionWindowBuffer = _nextRedemptionWindowBuffer;
emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the start of the most recent redemption window
/// @param _startTimestamp The initial startTimestamp for the redemption window
/// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window
function calcLatestRedemptionWindowStart(uint256 _startTimestamp)
public
view
returns (uint256 latestRedemptionWindowStart_)
{
if (block.timestamp <= _startTimestamp) {
return _startTimestamp;
}
uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp);
uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY);
return block.timestamp.sub(timeSincePeriodStart);
}
///////////////////////////////////////////
// REDEMPTION-BLOCKING ADAPTERS REGISTRY //
///////////////////////////////////////////
/// @notice Add adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be added
function addRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"__addRedemptionBlockingAdapters: _adapters cannot be empty"
);
__addRedemptionBlockingAdapters(_adapters);
}
/// @notice Remove adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be removed
function removeRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"removeRedemptionBlockingAdapters: _adapters cannot be empty"
);
for (uint256 i; i < _adapters.length; i++) {
require(
adapterCanBlockRedemption(_adapters[i]),
"removeRedemptionBlockingAdapters: adapter is not added"
);
adapterToCanBlockRedemption[_adapters[i]] = false;
emit AdapterRemoved(_adapters[i]);
}
}
/// @dev Helper to mark adapters that can block shares redemption
function __addRedemptionBlockingAdapters(address[] memory _adapters) private {
for (uint256 i; i < _adapters.length; i++) {
require(
_adapters[i] != address(0),
"__addRedemptionBlockingAdapters: adapter cannot be empty"
);
require(
!adapterCanBlockRedemption(_adapters[i]),
"__addRedemptionBlockingAdapters: adapter already added"
);
adapterToCanBlockRedemption[_adapters[i]] = true;
emit AdapterAdded(_adapters[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `redemptionWindowBuffer` variable
/// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value
function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) {
return redemptionWindowBuffer;
}
/// @notice Gets the RedemptionWindow settings for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return redemptionWindow_ The RedemptionWindow settings
function getRedemptionWindowForFund(address _comptrollerProxy)
external
view
returns (RedemptionWindow memory redemptionWindow_)
{
return comptrollerProxyToRedemptionWindow[_comptrollerProxy];
}
/// @notice Checks whether an adapter can block shares redemption
/// @param _adapter The address of the adapter to check
/// @return canBlockRedemption_ True if the adapter can block shares redemption
function adapterCanBlockRedemption(address _adapter)
public
view
returns (bool canBlockRedemption_)
{
return adapterToCanBlockRedemption[_adapter];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of adapters from use by a fund
contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return !isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title InvestorWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund
contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "INVESTOR_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investor The investor for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _investor)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _investor);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address buyer, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, buyer);
}
/// @dev Helper to update the investor whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreBuyShares policy hook
abstract contract PreBuySharesValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256, uint256, uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title MinMaxInvestment Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that restricts the amount of the fund's denomination asset that a user can
/// send in a single call to buy shares in a fund
contract MinMaxInvestment is PreBuySharesValidatePolicyBase {
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 minInvestmentAmount,
uint256 maxInvestmentAmount
);
struct FundSettings {
uint256 minInvestmentAmount;
uint256 maxInvestmentAmount;
}
mapping(address => FundSettings) private comptrollerProxyToFundSettings;
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MIN_MAX_INVESTMENT";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investmentAmount The investment amount for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, uint256 _investmentAmount)
public
view
returns (bool isValid_)
{
uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount;
uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount;
// Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund
// temporarily
if (minInvestmentAmount == 0) {
return _investmentAmount <= maxInvestmentAmount;
} else if (maxInvestmentAmount == 0) {
return _investmentAmount >= minInvestmentAmount;
}
return
_investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, investmentAmount);
}
/// @dev Helper to set the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private {
(uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
require(
maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount,
"__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount"
);
comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount = minInvestmentAmount;
comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount = maxInvestmentAmount;
emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the min and max investment amount for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return fundSettings_ The fund settings
function getFundSettings(address _comptrollerProxy)
external
view
returns (FundSettings memory fundSettings_)
{
return comptrollerProxyToFundSettings[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/BuySharesSetupPolicyBase.sol";
/// @title BuySharesCallerWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund
contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "BUY_SHARES_CALLER_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _buySharesCaller The buyShares caller for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _buySharesCaller)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _buySharesCaller);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address caller, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, caller);
}
/// @dev Helper to update the whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesSetupPolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook
abstract contract BuySharesSetupPolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address caller_,
uint256[] memory investmentAmounts_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256[], uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/vault/VaultLib.sol";
import "../utils/AdapterBase.sol";
/// @title TrackedAssetsAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops)
contract TrackedAssetsAdapter is AdapterBase {
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @notice Add multiple assets to the Vault's list of tracked assets
/// @dev No need to perform any validation or implement any logic
function addTrackedAssets(
address,
bytes calldata,
bytes calldata
) external view {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "TRACKED_ASSETS";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(
_selector == ADD_TRACKED_ASSETS_SELECTOR,
"parseAssetsForMethod: _selector invalid"
);
incomingAssets_ = __decodeCallArgs(_encodedCallArgs);
minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length);
for (uint256 i; i < minIncomingAssetAmounts_.length; i++) {
minIncomingAssetAmounts_[i] = 1;
}
return (
spendAssetsHandleType_,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address[] memory incomingAssets_)
{
return abi.decode(_encodedCallArgs, (address[]));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/ProxiableVaultLib.sol";
/// @title VaultProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822
/// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract VaultProxy {
constructor(bytes memory _constructData, address _vaultLib) public {
// "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to
// `bytes32(keccak256('mln.proxiable.vaultlib'))`
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_vaultLib).proxiableUUID(),
"constructor: _vaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib)
}
(bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line
require(success, string(returnData));
}
fallback() external payable {
assembly {
// solium-disable-line
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigrationHookHandler.sol";
import "../utils/IMigratableVault.sol";
import "../vault/VaultProxy.sol";
import "./IDispatcher.sol";
/// @title Dispatcher Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract linking multiple releases.
/// It handles the deployment of new VaultProxy instances,
/// and the regulation of fund migration from a previous release to the current one.
/// It can also be referred to for access-control based on this contract's owner.
/// @dev DO NOT EDIT CONTRACT
contract Dispatcher is IDispatcher {
event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer);
event MigrationCancelled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationExecuted(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationSignaled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock);
event NominatedOwnerSet(address indexed nominatedOwner);
event NominatedOwnerRemoved(address indexed nominatedOwner);
event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner);
event MigrationInCancelHookFailed(
bytes failureReturnData,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event MigrationOutHookFailed(
bytes failureReturnData,
IMigrationHookHandler.MigrationOutHook hook,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event SharesTokenSymbolSet(string _nextSymbol);
event VaultProxyDeployed(
address indexed fundDeployer,
address indexed owner,
address vaultProxy,
address indexed vaultLib,
address vaultAccessor,
string fundName
);
struct MigrationRequest {
address nextFundDeployer;
address nextVaultAccessor;
address nextVaultLib;
uint256 executableTimestamp;
}
address private currentFundDeployer;
address private nominatedOwner;
address private owner;
uint256 private migrationTimelock;
string private sharesTokenSymbol;
mapping(address => address) private vaultProxyToFundDeployer;
mapping(address => MigrationRequest) private vaultProxyToMigrationRequest;
modifier onlyCurrentFundDeployer() {
require(
msg.sender == currentFundDeployer,
"Only the current FundDeployer can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the contract owner can call this function");
_;
}
constructor() public {
migrationTimelock = 2 days;
owner = msg.sender;
sharesTokenSymbol = "ENZF";
}
/////////////
// GENERAL //
/////////////
/// @notice Sets a new `symbol` value for VaultProxy instances
/// @param _nextSymbol The symbol value to set
function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner {
sharesTokenSymbol = _nextSymbol;
emit SharesTokenSymbolSet(_nextSymbol);
}
////////////////////
// ACCESS CONTROL //
////////////////////
/// @notice Claim ownership of the contract
function claimOwnership() external override {
address nextOwner = nominatedOwner;
require(
msg.sender == nextOwner,
"claimOwnership: Only the nominatedOwner can call this function"
);
delete nominatedOwner;
address prevOwner = owner;
owner = nextOwner;
emit OwnershipTransferred(prevOwner, nextOwner);
}
/// @notice Revoke the nomination of a new contract owner
function removeNominatedOwner() external override onlyOwner {
address removedNominatedOwner = nominatedOwner;
require(
removedNominatedOwner != address(0),
"removeNominatedOwner: There is no nominated owner"
);
delete nominatedOwner;
emit NominatedOwnerRemoved(removedNominatedOwner);
}
/// @notice Set a new FundDeployer for use within the contract
/// @param _nextFundDeployer The address of the FundDeployer contract
function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner {
require(
_nextFundDeployer != address(0),
"setCurrentFundDeployer: _nextFundDeployer cannot be empty"
);
require(
__isContract(_nextFundDeployer),
"setCurrentFundDeployer: Non-contract _nextFundDeployer"
);
address prevFundDeployer = currentFundDeployer;
require(
_nextFundDeployer != prevFundDeployer,
"setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer"
);
currentFundDeployer = _nextFundDeployer;
emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer);
}
/// @notice Nominate a new contract owner
/// @param _nextNominatedOwner The account to nominate
/// @dev Does not prohibit overwriting the current nominatedOwner
function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner {
require(
_nextNominatedOwner != address(0),
"setNominatedOwner: _nextNominatedOwner cannot be empty"
);
require(
_nextNominatedOwner != owner,
"setNominatedOwner: _nextNominatedOwner is already the owner"
);
require(
_nextNominatedOwner != nominatedOwner,
"setNominatedOwner: _nextNominatedOwner is already nominated"
);
nominatedOwner = _nextNominatedOwner;
emit NominatedOwnerSet(_nextNominatedOwner);
}
/// @dev Helper to check whether an address is a deployed contract
function __isContract(address _who) private view returns (bool isContract_) {
uint256 size;
assembly {
size := extcodesize(_who)
}
return size > 0;
}
////////////////
// DEPLOYMENT //
////////////////
/// @notice Deploys a VaultProxy
/// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy
/// @param _owner The account to set as the VaultProxy's owner
/// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor
/// @param _fundName The name of the fund
/// @dev Input validation should be handled by the VaultProxy during deployment
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external override onlyCurrentFundDeployer returns (address vaultProxy_) {
require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor");
bytes memory constructData = abi.encodeWithSelector(
IMigratableVault.init.selector,
_owner,
_vaultAccessor,
_fundName
);
vaultProxy_ = address(new VaultProxy(constructData, _vaultLib));
address fundDeployer = msg.sender;
vaultProxyToFundDeployer[vaultProxy_] = fundDeployer;
emit VaultProxyDeployed(
fundDeployer,
_owner,
vaultProxy_,
_vaultLib,
_vaultAccessor,
_fundName
);
return vaultProxy_;
}
////////////////
// MIGRATIONS //
////////////////
/// @notice Cancels a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to cancel the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
/// @dev Because this function must also be callable by a permissioned migrator, it has an
/// extra migration hook to the nextFundDeployer for the case where cancelMigration()
/// is called directly (rather than via the nextFundDeployer).
function cancelMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(nextFundDeployer != address(0), "cancelMigration: No migration request exists");
// TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works.
require(
msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender),
"cancelMigration: Not an allowed caller"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
uint256 executableTimestamp = request.executableTimestamp;
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostCancel,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
__invokeMigrationInCancelHook(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationCancelled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Executes a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to execute the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function executeMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(
nextFundDeployer != address(0),
"executeMigration: No migration request exists for _vaultProxy"
);
require(
msg.sender == nextFundDeployer,
"executeMigration: Only the target FundDeployer can call this function"
);
require(
nextFundDeployer == currentFundDeployer,
"executeMigration: The target FundDeployer is no longer the current FundDeployer"
);
uint256 executableTimestamp = request.executableTimestamp;
require(
block.timestamp >= executableTimestamp,
"executeMigration: The migration timelock has not elapsed"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
// Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib
IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib);
IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor);
// Update the FundDeployer that migrated the VaultProxy
vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer;
// Remove the migration request
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationExecuted(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Sets a new migration timelock
/// @param _nextTimelock The number of seconds for the new timelock
function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner {
uint256 prevTimelock = migrationTimelock;
require(
_nextTimelock != prevTimelock,
"setMigrationTimelock: _nextTimelock is the current timelock"
);
migrationTimelock = _nextTimelock;
emit MigrationTimelockSet(prevTimelock, _nextTimelock);
}
/// @notice Signals a migration by creating a migration request
/// @param _vaultProxy The VaultProxy contract for which to signal migration
/// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy
/// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external override onlyCurrentFundDeployer {
require(
__isContract(_nextVaultAccessor),
"signalMigration: Non-contract _nextVaultAccessor"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist");
address nextFundDeployer = msg.sender;
require(
nextFundDeployer != prevFundDeployer,
"signalMigration: Can only migrate to a new FundDeployer"
);
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
uint256 executableTimestamp = block.timestamp + migrationTimelock;
vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({
nextFundDeployer: nextFundDeployer,
nextVaultAccessor: _nextVaultAccessor,
nextVaultLib: _nextVaultLib,
executableTimestamp: executableTimestamp
});
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
emit MigrationSignaled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
executableTimestamp
);
}
/// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _nextFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationInCancelHook.selector,
_vaultProxy,
_prevFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked("MigrationOutCancelHook: ", returnData))
);
emit MigrationInCancelHookFailed(
returnData,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook _hook,
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _prevFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationOutHook.selector,
_hook,
_vaultProxy,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData))
);
emit MigrationOutHookFailed(
returnData,
_hook,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to return a revert reason string prefix for a given MigrationOutHook
function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook)
private
pure
returns (string memory failureReasonPrefix_)
{
if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) {
return "MigrationOutHook.PreSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) {
return "MigrationOutHook.PostSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) {
return "MigrationOutHook.PreMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) {
return "MigrationOutHook.PostMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) {
return "MigrationOutHook.PostCancel: ";
}
return "";
}
///////////////////
// STATE GETTERS //
///////////////////
// Provides several potentially helpful getters that are not strictly necessary
/// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds
/// @return currentFundDeployer_ The current FundDeployer contract address
function getCurrentFundDeployer()
external
view
override
returns (address currentFundDeployer_)
{
return currentFundDeployer;
}
/// @notice Gets the FundDeployer with which a given VaultProxy is associated
/// @param _vaultProxy The VaultProxy instance
/// @return fundDeployer_ The FundDeployer contract address
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
override
returns (address fundDeployer_)
{
return vaultProxyToFundDeployer[_vaultProxy];
}
/// @notice Gets the details of a pending migration request for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return nextFundDeployer_ The FundDeployer contract address from which the migration
/// request was made
/// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy
/// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy
/// @return executableTimestamp_ The timestamp at which the migration request can be executed
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
override
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
)
{
MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy];
if (r.executableTimestamp > 0) {
return (
r.nextFundDeployer,
r.nextVaultAccessor,
r.nextVaultLib,
r.executableTimestamp
);
}
}
/// @notice Gets the amount of time that must pass between signaling and executing a migration
/// @return migrationTimelock_ The timelock value (in seconds)
function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) {
return migrationTimelock;
}
/// @notice Gets the account that is nominated to be the next owner of this contract
/// @return nominatedOwner_ The account that is nominated to be the owner
function getNominatedOwner() external view override returns (address nominatedOwner_) {
return nominatedOwner;
}
/// @notice Gets the owner of this contract
/// @return owner_ The account that is the owner
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the shares token `symbol` value for use in VaultProxy instances
/// @return sharesTokenSymbol_ The `symbol` value
function getSharesTokenSymbol()
external
view
override
returns (string memory sharesTokenSymbol_)
{
return sharesTokenSymbol;
}
/// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed
/// @param _vaultProxy The VaultProxy instance
/// @return secondsRemaining_ The number of seconds remaining on the timelock
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
override
returns (uint256 secondsRemaining_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
if (executableTimestamp == 0) {
return 0;
}
if (block.timestamp >= executableTimestamp) {
return 0;
}
return executableTimestamp - block.timestamp;
}
/// @notice Checks whether a migration request that is executable exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasExecutableRequest_ True if a migration request exists and is executable
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasExecutableRequest_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
return executableTimestamp > 0 && block.timestamp >= executableTimestamp;
}
/// @notice Checks whether a migration request exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasMigrationRequest_ True if a migration request exists
function hasMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasMigrationRequest_)
{
return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../persistent/vault/VaultLibBaseCore.sol";
/// @title MockVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock VaultLib implementation that only extends VaultLibBaseCore
contract MockVaultLib is VaultLibBaseCore {
function getAccessor() external view returns (address) {
return accessor;
}
function getCreator() external view returns (address) {
return creator;
}
function getMigrator() external view returns (address) {
return migrator;
}
function getOwner() external view returns (address) {
return owner;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ICERC20 Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound tokens (cTokens)
interface ICERC20 is IERC20 {
function decimals() external view returns (uint8);
function mint(uint256) external returns (uint256);
function redeem(uint256) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function underlying() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CompoundPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Compound Tokens (cTokens)
contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event CTokenAdded(address indexed cToken, address indexed token);
uint256 private constant CTOKEN_RATE_DIVISOR = 10**18;
mapping(address => address) private cTokenToToken;
constructor(
address _dispatcher,
address _weth,
address _ceth,
address[] memory cERC20Tokens
) public DispatcherOwnerMixin(_dispatcher) {
// Set cEth
cTokenToToken[_ceth] = _weth;
emit CTokenAdded(_ceth, _weth);
// Set any other cTokens
if (cERC20Tokens.length > 0) {
__addCERC20Tokens(cERC20Tokens);
}
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = cTokenToToken[_derivative];
require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative");
underlyingAmounts_ = new uint256[](1);
// Returns a rate scaled to 10^18
underlyingAmounts_[0] = _derivativeAmount
.mul(ICERC20(_derivative).exchangeRateStored())
.div(CTOKEN_RATE_DIVISOR);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return cTokenToToken[_asset] != address(0);
}
//////////////////////
// CTOKENS REGISTRY //
//////////////////////
/// @notice Adds cTokens to the price feed
/// @param _cTokens cTokens to add
/// @dev Only allows CERC20 tokens. CEther is set in the constructor.
function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner {
__addCERC20Tokens(_cTokens);
}
/// @dev Helper to add cTokens
function __addCERC20Tokens(address[] memory _cTokens) private {
require(_cTokens.length > 0, "__addCTokens: Empty _cTokens");
for (uint256 i; i < _cTokens.length; i++) {
require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set");
address token = ICERC20(_cTokens[i]).underlying();
cTokenToToken[_cTokens[i]] = token;
emit CTokenAdded(_cTokens[i], token);
}
}
////////////////////
// STATE GETTERS //
///////////////////
/// @notice Returns the underlying asset of a given cToken
/// @param _cToken The cToken for which to get the underlying asset
/// @return token_ The underlying token
function getTokenFromCToken(address _cToken) public view returns (address token_) {
return cTokenToToken[_cToken];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../../interfaces/ICEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CompoundAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Compound <https://compound.finance/>
contract CompoundAdapter is AdapterBase {
address private immutable COMPOUND_PRICE_FEED;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _compoundPriceFeed,
address _wethToken
) public AdapterBase(_integrationManager) {
COMPOUND_PRICE_FEED = _compoundPriceFeed;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during cEther lend/redeem
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "COMPOUND";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = tokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = cToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minCTokenAmount;
} else if (_selector == REDEEM_SELECTOR) {
(address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = cToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = cTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
if (spendAssets[0] == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]);
ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}();
} else {
__approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]);
ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]);
}
}
/// @notice Redeems an amount of cTokens from Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]);
if (incomingAssets[0] == WETH_TOKEN) {
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address cToken_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `COMPOUND_PRICE_FEED` variable
/// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value
function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) {
return COMPOUND_PRICE_FEED;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
/// @title ICEther Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound Ether
interface ICEther {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IChai Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Chai contract
interface IChai is IERC20 {
function exit(address, uint256) external;
function join(address, uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IChai.sol";
import "../utils/AdapterBase.sol";
/// @title ChaiAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Chai <https://github.com/dapphub/chai>
contract ChaiAdapter is AdapterBase {
address private immutable CHAI;
address private immutable DAI;
constructor(
address _integrationManager,
address _chai,
address _dai
) public AdapterBase(_integrationManager) {
CHAI = _chai;
DAI = _dai;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "CHAI";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = DAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = daiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = CHAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minChaiAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = CHAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = chaiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = DAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minDaiAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lend Dai for Chai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(DAI, CHAI, daiAmount);
// Execute Lend on Chai
// Chai.join allows specifying the vaultProxy as the destination of Chai tokens
IChai(CHAI).join(_vaultProxy, daiAmount);
}
/// @notice Redeem Chai for Dai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs);
// Execute redeem on Chai
// Chai.exit sends Dai back to the adapter
IChai(CHAI).exit(address(this), chaiAmount);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/SwapperBase.sol";
contract MockGenericIntegratee is SwapperBase {
function swap(
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
msg.sender,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
function swapOnBehalf(
address payable _trader,
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
_trader,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
import "../utils/SwapperBase.sol";
contract MockChaiIntegratee is MockToken, SwapperBase {
address private immutable CENTRALIZED_RATE_PROVIDER;
address public immutable DAI;
constructor(
address _dai,
address _centralizedRateProvider,
uint8 _decimals
) public MockToken("Chai", "CHAI", _decimals) {
_setupDecimals(_decimals);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
DAI = _dai;
}
function join(address, uint256 _daiAmount) external {
uint256 tokenDecimals = ERC20(DAI).decimals();
uint256 chaiDecimals = decimals();
// Calculate the amount of tokens per one unit of DAI
uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI);
// Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div(
daiPerChaiUnit
);
// Mint and send those CHAI to sender
uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals);
_mint(address(this), destAmount);
__swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount);
}
function exit(address payable _trader, uint256 _chaiAmount) external {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_chaiAmount,
DAI
);
// Burn CHAI of the trader.
_burn(_trader, _chaiAmount);
// Release DAI to the trader.
ERC20(DAI).transfer(msg.sender, destAmount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title AlphaHomoraV1Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/>
contract AlphaHomoraV1Adapter is AdapterBase {
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _ibethToken,
address _wethToken
) public AdapterBase(_integrationManager) {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during redemption
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ALPHA_HOMORA_V1";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = wethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = IBETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIbethAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = IBETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = ibethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minWethAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends WETH for ibETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IWETH(payable(WETH_TOKEN)).withdraw(wethAmount);
IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}();
}
/// @notice Redeems ibETH for WETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAlphaHomoraV1Bank interface
/// @author Enzyme Council <[email protected]>
interface IAlphaHomoraV1Bank {
function deposit() external payable;
function totalETH() external view returns (uint256);
function totalSupply() external view returns (uint256);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../IDerivativePriceFeed.sol";
/// @title AlphaHomoraV1PriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Alpha Homora v1 ibETH
contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(address _ibethToken, address _wethToken) public {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH_TOKEN;
underlyingAmounts_ = new uint256[](1);
IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN);
underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div(
alphaHomoraBankContract.totalSupply()
);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == IBETH_TOKEN;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IMakerDaoPot.sol";
import "../IDerivativePriceFeed.sol";
/// @title ChaiPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Chai
contract ChaiPriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
uint256 private constant CHI_DIVISOR = 10**27;
address private immutable CHAI;
address private immutable DAI;
address private immutable DSR_POT;
constructor(
address _chai,
address _dai,
address _dsrPot
) public {
CHAI = _chai;
DAI = _dai;
DSR_POT = _dsrPot;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
/// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported");
underlyings_ = new address[](1);
underlyings_[0] = DAI;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div(
CHI_DIVISOR
);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == CHAI;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
/// @notice Gets the `DSR_POT` variable value
/// @return dsrPot_ The `DSR_POT` variable value
function getDsrPot() external view returns (address dsrPot_) {
return DSR_POT;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @notice Limited interface for Maker DSR's Pot contract
/// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md
interface IMakerDaoPot {
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./FeeBase.sol";
/// @title EntranceRateFeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund
abstract contract EntranceRateFeeBase is FeeBase {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate);
event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity);
uint256 private constant RATE_DIVISOR = 10**18;
IFeeManager.SettlementType private immutable SETTLEMENT_TYPE;
mapping(address => uint256) private comptrollerProxyToRate;
constructor(address _feeManager, IFeeManager.SettlementType _settlementType)
public
FeeBase(_feeManager)
{
require(
_settlementType == IFeeManager.SettlementType.Burn ||
_settlementType == IFeeManager.SettlementType.Direct,
"constructor: Invalid _settlementType"
);
SETTLEMENT_TYPE = _settlementType;
}
// EXTERNAL FUNCTIONS
/// @notice Add the fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 rate = abi.decode(_settingsData, (uint256));
require(rate > 0, "addFundSettings: Fee rate must be >0");
comptrollerProxyToRate[_comptrollerProxy] = rate;
emit FundSettingsAdded(_comptrollerProxy, rate);
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](1);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settles the fee
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settlementData Encoded args to use in calculating the settlement
/// @return settlementType_ The type of settlement
/// @return payer_ The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address,
IFeeManager.FeeHook,
bytes calldata _settlementData,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
)
{
uint256 sharesBought;
(payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData);
uint256 rate = comptrollerProxyToRate[_comptrollerProxy];
sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate));
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
emit Settled(_comptrollerProxy, payer_, sharesDue_);
return (SETTLEMENT_TYPE, payer_, sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `rate` variable for a fund
/// @param _comptrollerProxy The ComptrollerProxy contract for the fund
/// @return rate_ The `rate` variable value
function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) {
return comptrollerProxyToRate[_comptrollerProxy];
}
/// @notice Gets the `SETTLEMENT_TYPE` variable
/// @return settlementType_ The `SETTLEMENT_TYPE` variable value
function getSettlementType()
external
view
returns (IFeeManager.SettlementType settlementType_)
{
return SETTLEMENT_TYPE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateDirectFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that transfers the fee shares to the fund manager
contract EntranceRateDirectFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_DIRECT";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateBurnFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that burns the fee shares
contract EntranceRateBurnFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_BURN";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract MockChaiPriceSource {
using SafeMath for uint256;
uint256 private chiStored = 10**27;
uint256 private rhoStored = now;
function drip() external returns (uint256) {
require(now >= rhoStored, "drip: invalid now");
rhoStored = now;
chiStored = chiStored.mul(99).div(100);
return chi();
}
////////////////////
// STATE GETTERS //
///////////////////
function chi() public view returns (uint256) {
return chiStored;
}
function rho() public view returns (uint256) {
return rhoStored;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/DispatcherOwnerMixin.sol";
import "./IAggregatedDerivativePriceFeed.sol";
/// @title AggregatedDerivativePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches
/// rate requests to the appropriate feed
contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address priceFeed);
event DerivativeRemoved(address indexed derivative);
event DerivativeUpdated(
address indexed derivative,
address prevPriceFeed,
address nextPriceFeed
);
mapping(address => address) private derivativeToPriceFeed;
constructor(
address _dispatcher,
address[] memory _derivatives,
address[] memory _priceFeeds
) public DispatcherOwnerMixin(_dispatcher) {
if (_derivatives.length > 0) {
__addDerivatives(_derivatives, _priceFeeds);
}
}
/// @notice Gets the rates for 1 unit of the derivative to its underlying assets
/// @param _derivative The derivative for which to get the rates
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The rates for the _derivative to the underlyings_
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address derivativePriceFeed = derivativeToPriceFeed[_derivative];
require(
derivativePriceFeed != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
return
IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues(
_derivative,
_derivativeAmount
);
}
/// @notice Checks whether an asset is a supported derivative
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported derivative
/// @dev This should be as low-cost and simple as possible
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return derivativeToPriceFeed[_asset] != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty");
__addDerivatives(_derivatives, _priceFeeds);
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty");
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] != address(0),
"removeDerivatives: Derivative not yet added"
);
delete derivativeToPriceFeed[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @notice Updates a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to update
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty");
require(
_derivatives.length == _priceFeeds.length,
"updateDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]];
require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added");
require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set");
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]);
}
}
/// @dev Helper to add derivative-feed pairs
function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds)
private
{
require(
_derivatives.length == _priceFeeds.length,
"__addDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] == address(0),
"__addDerivatives: Already added"
);
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeAdded(_derivatives[i], _priceFeeds[i]);
}
}
/// @dev Helper to validate a derivative price feed
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view {
require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative");
require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed");
require(
IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative),
"__validateDerivativePriceFeed: Unsupported derivative"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the registered price feed for a given derivative
/// @return priceFeed_ The price feed contract address
function getPriceFeedForDerivative(address _derivative)
external
view
override
returns (address priceFeed_)
{
return derivativeToPriceFeed[_derivative];
}
}
| Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) TODO: Refactor to use 18 decimal precision | function __calcDeviatedValue(
uint256 _meanValue,
uint256 _offset,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
return
_meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub(
_meanValue.mul(_maxDeviation).div(uint256(100))
);
}
| 1,697,573 |
./full_match/10/0x0D4a13ad6f852469aDdbEb4A09Eb91310da3FE85/sources/contracts/oracles/BridgedUsdpOracle.sol | returns Q112-encoded value | function assetToUsd(address asset, uint amount) public override view returns (uint) {
require(bridgedUsdp[asset], 'Unit Protocol: TOKEN_IS_NOT_SUPPORTED');
return amount.mul(Q112);
}
| 3,780,023 |
pragma solidity 0.4.18;
/**
* Math operations with safety checks
*/
contract BaseSafeMath {
/*
standard uint256 functions
*/
function add(uint256 a, uint256 b) internal pure
returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure
returns (uint256) {
assert(b <= a);
return a - b;
}
function mul(uint256 a, uint256 b) internal pure
returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure
returns (uint256) {
assert( b > 0 );
uint256 c = a / b;
return c;
}
function min(uint256 x, uint256 y) internal pure
returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure
returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions
*/
function madd(uint128 a, uint128 b) internal pure
returns (uint128) {
uint128 c = a + b;
assert(c >= a);
return c;
}
function msub(uint128 a, uint128 b) internal pure
returns (uint128) {
assert(b <= a);
return a - b;
}
function mmul(uint128 a, uint128 b) internal pure
returns (uint128) {
uint128 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function mdiv(uint128 a, uint128 b) internal pure
returns (uint128) {
assert( b > 0 );
uint128 c = a / b;
return c;
}
function mmin(uint128 x, uint128 y) internal pure
returns (uint128 z) {
return x <= y ? x : y;
}
function mmax(uint128 x, uint128 y) internal pure
returns (uint128 z) {
return x >= y ? x : y;
}
/*
uint64 functions
*/
function miadd(uint64 a, uint64 b) internal pure
returns (uint64) {
uint64 c = a + b;
assert(c >= a);
return c;
}
function misub(uint64 a, uint64 b) internal pure
returns (uint64) {
assert(b <= a);
return a - b;
}
function mimul(uint64 a, uint64 b) internal pure
returns (uint64) {
uint64 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function midiv(uint64 a, uint64 b) internal pure
returns (uint64) {
assert( b > 0 );
uint64 c = a / b;
return c;
}
function mimin(uint64 x, uint64 y) internal pure
returns (uint64 z) {
return x <= y ? x : y;
}
function mimax(uint64 x, uint64 y) internal pure
returns (uint64 z) {
return x >= y ? x : y;
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
contract BaseERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowed;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal;
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success);
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success);
}
/**
* @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 publishOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
publishOwner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == publishOwner);
_;
}
/**
* @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));
OwnershipTransferred(publishOwner, newOwner);
publishOwner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract LightCoinToken is BaseERC20, BaseSafeMath, Pausable {
//The solidity created time
address public owner;
address public lockOwner;
uint256 public lockAmount ;
uint256 public startTime ;
function LightCoinToken() public {
owner = 0x55ae8974743DB03761356D703A9cfc0F24045ebb;
lockOwner = 0x07d4C8CC52BB7c4AB46A1A65DCEEdC1ab29aBDd6;
startTime = 1515686400;
name = "Lightcoin";
symbol = "Light";
decimals = 8;
///totalSupply = 21000000000000000000;
totalSupply = 2.1e19;
balanceOf[owner] = totalSupply * 90 /100;
lockAmount = totalSupply * 10 / 100 ;
Transfer(address(0), owner, balanceOf[owner]);
}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function getBalanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOf[_owner];
}
function _transfer(address _from, address _to, uint256 _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Save this for an assertion in the future
uint previousBalances = add(balanceOf[_from], balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] = sub(balanceOf[_from], _value);
// Add the same to the recipient
balanceOf[_to] = add(balanceOf[_to], _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(add(balanceOf[_from], balanceOf[_to]) == previousBalances);
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) {
// Check allowance
allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function releaseToken() public{
uint256 releaseBegin = add(startTime, 2 * 365 * 86400);
require(now >= releaseBegin );
uint256 interval = sub(now, releaseBegin);
uint256 i = div(interval, (0.5 * 365 * 86400));
if (i > 3)
{
i = 3;
}
uint256 releasevalue = div(totalSupply, 40);
uint256 remainInterval = sub(3, i);
require(lockAmount > mul(remainInterval, releasevalue));
lockAmount = sub(lockAmount, releasevalue);
balanceOf[lockOwner] = add( balanceOf[lockOwner], releasevalue);
Transfer(address(0), lockOwner, releasevalue);
}
function () public payable{ revert(); }
} | _owner The address from which the balance will be retrieved return The balance | function getBalanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOf[_owner];
}
| 7,947,536 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol";
import "./interfaces/IBPool.sol";
import "./interfaces/IBRegistry.sol";
import "./interfaces/IEurPriceFeed.sol";
import "./interfaces/IXTokenWrapper.sol";
import "hardhat/console.sol";
interface IDecimals {
function decimals() external view returns (uint8);
}
/**
* @title SmtPriceFeed
* @author Protofire
* @dev Contract module to retrieve SMT price per asset.
*/
contract SmtPriceFeed is Ownable {
using SafeMath for uint256;
uint256 public constant decimals = 18;
uint256 public constant ONE = 10**18;
address public constant ETH_TOKEN_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/// @dev Address smt
address public smt;
/// @dev Address of BRegistry
IBRegistry public registry;
/// @dev Address of EurPriceFeed module
IEurPriceFeed public eurPriceFeed;
/// @dev Address of XTokenWrapper module
IXTokenWrapper public xTokenWrapper;
/**
* @dev Emitted when `registry` address is set.
*/
event RegistrySet(address registry);
/**
* @dev Emitted when `eurPriceFeed` address is set.
*/
event EurPriceFeedSet(address eurPriceFeed);
/**
* @dev Emitted when `smt` address is set.
*/
event SmtSet(address smt);
/**
* @dev Emitted when `xTokenWrapper` address is set.
*/
event XTokenWrapperSet(address xTokenWrapper);
/**
* @dev Sets the values for {registry}, {eurPriceFeed} {smt} and {xTokenWrapper}.
*
* Sets ownership to the account that deploys the contract.
*
*/
constructor(
address _registry,
address _eurPriceFeed,
address _smt,
address _xTokenWrapper
) {
_setRegistry(_registry);
_setEurPriceFeed(_eurPriceFeed);
_setSmt(_smt);
_setXTokenWrapper(_xTokenWrapper);
}
/**
* @dev Sets `_registry` as the new registry.
*
* Requirements:
*
* - the caller must be the owner.
* - `_registry` should not be the zero address.
*
* @param _registry The address of the registry.
*/
function setRegistry(address _registry) external onlyOwner {
_setRegistry(_registry);
}
/**
* @dev Sets `_eurPriceFeed` as the new EurPriceFeed.
*
* Requirements:
*
* - the caller must be the owner.
* - `_eurPriceFeed` should not be the zero address.
*
* @param _eurPriceFeed The address of the EurPriceFeed.
*/
function setEurPriceFeed(address _eurPriceFeed) external onlyOwner {
_setEurPriceFeed(_eurPriceFeed);
}
/**
* @dev Sets `_smt` as the new Smt.
*
* Requirements:
*
* - the caller must be the owner.
* - `_smt` should not be the zero address.
*
* @param _smt The address of the Smt.
*/
function setSmt(address _smt) external onlyOwner {
_setSmt(_smt);
}
/**
* @dev Sets `_xTokenWrapper` as the new xTokenWrapper.
*
* Requirements:
*
* - the caller must be the owner.
* - `_xTokenWrapper` should not be the zero address.
*
* @param _xTokenWrapper The address of the xTokenWrapper.
*/
function setXTokenWrapper(address _xTokenWrapper) external onlyOwner {
_setXTokenWrapper(_xTokenWrapper);
}
/**
* @dev Sets `_registry` as the new registry.
*
* Requirements:
*
* - `_registry` should not be the zero address.
*
* @param _registry The address of the registry.
*/
function _setRegistry(address _registry) internal {
require(_registry != address(0), "registry is the zero address");
emit RegistrySet(_registry);
registry = IBRegistry(_registry);
}
/**
* @dev Sets `_eurPriceFeed` as the new EurPriceFeed.
*
* Requirements:
*
* - `_eurPriceFeed` should not be the zero address.
*
* @param _eurPriceFeed The address of the EurPriceFeed.
*/
function _setEurPriceFeed(address _eurPriceFeed) internal {
require(_eurPriceFeed != address(0), "eurPriceFeed is the zero address");
emit EurPriceFeedSet(_eurPriceFeed);
eurPriceFeed = IEurPriceFeed(_eurPriceFeed);
}
/**
* @dev Sets `_smt` as the new Smt.
*
* Requirements:
*
* - `_smt` should not be the zero address.
*
* @param _smt The address of the Smt.
*/
function _setSmt(address _smt) internal {
require(_smt != address(0), "smt is the zero address");
emit SmtSet(_smt);
smt = _smt;
}
/**
* @dev Sets `_xTokenWrapper` as the new xTokenWrapper.
*
* Requirements:
*
* - `_xTokenWrapper` should not be the zero address.
*
* @param _xTokenWrapper The address of the xTokenWrapper.
*/
function _setXTokenWrapper(address _xTokenWrapper) internal {
require(_xTokenWrapper != address(0), "xTokenWrapper is the zero address");
emit XTokenWrapperSet(_xTokenWrapper);
xTokenWrapper = IXTokenWrapper(_xTokenWrapper);
}
/**
* @dev Gets the price of `_asset` in SMT.
*
* @param _asset address of asset to get the price.
*/
function getPrice(address _asset) external view returns (uint256) {
uint8 assetDecimals = IDecimals(_asset).decimals();
return calculateAmount(_asset, 10**assetDecimals);
}
/**
* @dev Gets how many SMT represents the `_amount` of `_asset`.
*
* @param _asset address of asset to get the amount.
* @param _assetAmountIn amount of `_asset`.
*/
function calculateAmount(address _asset, uint256 _assetAmountIn) public view returns (uint256) {
// pools will include the wrapepd SMT
address xSMT = xTokenWrapper.tokenToXToken(smt);
address xETH = xTokenWrapper.tokenToXToken(ETH_TOKEN_ADDRESS);
//if same token, didn't modify the token amount
if (_asset == xSMT) {
return _assetAmountIn;
}
// get amount from some of the pools
uint256 amount = getAvgAmountFromPools(_asset, xSMT, _assetAmountIn);
// not pool with SMT/asset pair -> calculate base on SMT/ETH pool and Asset/ETH external price feed
if (amount == 0) {
// pools will include the wrapepd ETH
uint256 ethSmtAmount = getAvgAmountFromPools(xETH, xSMT, ONE);
address assetEthFeed = eurPriceFeed.assetEthFeed(_asset);
if (assetEthFeed != address(0)) {
// always 18 decimals
int256 assetEthPrice = AggregatorV2V3Interface(assetEthFeed).latestAnswer();
if (assetEthPrice > 0) {
uint8 assetDecimals = IDecimals(_asset).decimals();
uint256 assetToEthAmount = _assetAmountIn.mul(uint256(assetEthPrice)).div(10**assetDecimals);
amount = assetToEthAmount.mul(ethSmtAmount).div(ONE);
}
}
}
return amount;
}
/**
* @dev Gets SMT/ETH based on the avg price from pools containig the pair.
*
* To be consume by EurPriceFeed module as the `assetEthFeed` from xSMT.
*/
function latestAnswer() external view returns (int256) {
// pools will include the wrapepd SMT and wrapped ETH
uint256 price =
getAvgAmountFromPools(
xTokenWrapper.tokenToXToken(smt),
xTokenWrapper.tokenToXToken(ETH_TOKEN_ADDRESS),
ONE
);
return int256(price);
}
function getAvgAmountFromPools(
address _assetIn,
address _assetOut,
uint256 _assetAmountIn
) internal view returns (uint256) {
address[] memory poolAddresses = registry.getBestPoolsWithLimit(_assetIn, _assetOut, 10);
uint256 totalAmount;
for (uint256 i = 0; i < poolAddresses.length; i++) {
totalAmount += calcOutGivenIn(poolAddresses[i], _assetIn, _assetOut, _assetAmountIn);
}
return totalAmount > 0 ? totalAmount.div(poolAddresses.length) : 0;
}
function calcOutGivenIn(
address poolAddress,
address _assetIn,
address _assetOut,
uint256 _assetAmountIn
) internal view returns (uint256) {
IBPool pool = IBPool(poolAddress);
uint256 tokenBalanceIn = pool.getBalance(_assetIn);
uint256 tokenBalanceOut = pool.getBalance(_assetOut);
uint256 tokenWeightIn = pool.getDenormalizedWeight(_assetIn);
uint256 tokenWeightOut = pool.getDenormalizedWeight(_assetOut);
return pool.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _assetAmountIn, 0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 () {
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
pragma solidity ^0.7.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IBPool
* @author Protofire
* @dev Balancer BPool contract interface.
*
*/
interface IBPool {
function getDenormalizedWeight(address token) external view returns (uint256);
function getBalance(address token) external view returns (uint256);
function calcOutGivenIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountIn,
uint256 swapFee
) external pure returns (uint256 tokenAmountOut);
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IBRegistry
* @author Protofire
* @dev Balancer BRegistry contract interface.
*
*/
interface IBRegistry {
function getBestPoolsWithLimit(
address fromToken,
address destToken,
uint256 limit
) external view returns (address[] memory);
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IEurPriceFeed
* @author Protofire
* @dev Interface to be implemented by any EurPriceFeed logic contract used in the protocol.
*
*/
interface IEurPriceFeed {
/**
* @dev Gets the price `_asset` ETH price feed.
*
* @param _asset address of asset to get the price feed.
*/
function assetEthFeed(address _asset) external view returns (address);
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IXTokenWrapper
* @author Protofire
* @dev XTokenWrapper Interface.
*
*/
interface IXTokenWrapper {
/**
* @dev Token to xToken registry.
*/
function tokenToXToken(address _token) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 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
pragma solidity ^0.7.0;
interface AggregatorInterface {
function latestAnswer()
external
view
returns (
int256
);
function latestTimestamp()
external
view
returns (
uint256
);
function latestRound()
external
view
returns (
uint256
);
function getAnswer(
uint256 roundId
)
external
view
returns (
int256
);
function getTimestamp(
uint256 roundId
)
external
view
returns (
uint256
);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
);
}
| IXTokenWrapper Protofire XTokenWrapper Interface./ | interface IXTokenWrapper {
function tokenToXToken(address _token) external view returns (address);
}
pragma solidity ^0.7.0;
}
| 10,331,447 |
./partial_match/1/0x9d9006a209C041D5E6aA5E27e25794785Af16dBe/sources/SHIANA.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("SHIANA", "SHIANA") {
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 = 20;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 50;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 2_000_000_000 * 1e18;
maxTransactionAmount = 10_000_000 * 1e18;
maxWallet = 10_000_000 * 1e18;
swapTokensAtAmount = (totalSupply * 5) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0x10f3fC37716F9F8866B65264cA10d0b8C2882120);
devWallet = address(0x10f3fC37716F9F8866B65264cA10d0b8C2882120);
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);
| 2,681,481 |
./full_match/137/0xc2768beF7a6BB57F0FfA169a9ED4017c09696FF1/sources/contracts/Peronio.sol | Returns current USDC and MAI token balances in the FARM | function stakedTokens()
external
view
returns (uint256 usdcAmount, uint256 maiAmount)
{
return _stakedTokens();
}
| 4,717,803 |
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPool.sol";
import "../cover/Quotation.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "./MCR.sol";
contract Pool is IPool, MasterAware, ReentrancyGuard {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
struct AssetData {
uint112 minAmount;
uint112 maxAmount;
uint32 lastSwapTime;
// 18 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint maxSlippageRatio;
}
/* storage */
address[] public assets;
mapping(address => AssetData) public assetData;
// contracts
Quotation public quotation;
NXMToken public nxmToken;
TokenController public tokenController;
MCR public mcr;
// parameters
address public swapController;
uint public minPoolEth;
PriceFeedOracle public priceFeedOracle;
address public swapOperator;
/* constants */
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant MCR_RATIO_DECIMALS = 4;
uint public constant MAX_MCR_RATIO = 40000; // 400%
uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points
uint internal constant CONSTANT_C = 5800000;
uint internal constant CONSTANT_A = 1028 * 1e13;
uint internal constant TOKEN_EXPONENT = 4;
/* events */
event Payout(address indexed to, address indexed asset, uint amount);
event NXMSold (address indexed member, uint nxmIn, uint ethOut);
event NXMBought (address indexed member, uint ethIn, uint nxmOut);
event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut);
/* logic */
modifier onlySwapOperator {
require(msg.sender == swapOperator, "Pool: not swapOperator");
_;
}
constructor (
address[] memory _assets,
uint112[] memory _minAmounts,
uint112[] memory _maxAmounts,
uint[] memory _maxSlippageRatios,
address _master,
address _priceOracle,
address _swapOperator
) public {
require(_assets.length == _minAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch");
for (uint i = 0; i < _assets.length; i++) {
address asset = _assets[i];
require(asset != address(0), "Pool: asset is zero address");
require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min");
require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min");
assets.push(asset);
assetData[asset].minAmount = _minAmounts[i];
assetData[asset].maxAmount = _maxAmounts[i];
assetData[asset].maxSlippageRatio = _maxSlippageRatios[i];
}
master = INXMMaster(_master);
priceFeedOracle = PriceFeedOracle(_priceOracle);
swapOperator = _swapOperator;
}
// fallback function
function() external payable {}
// for legacy Pool1 upgrade compatibility
function sendEther() external payable {}
/**
* @dev Calculates total value of all pool assets in ether
*/
function getPoolValueInEth() public view returns (uint) {
uint total = address(this).balance;
for (uint i = 0; i < assets.length; i++) {
address assetAddress = assets[i];
IERC20 token = IERC20(assetAddress);
uint rate = priceFeedOracle.getAssetToEthRate(assetAddress);
require(rate > 0, "Pool: zero rate");
uint assetBalance = token.balanceOf(address(this));
uint assetValue = assetBalance.mul(rate).div(1e18);
total = total.add(assetValue);
}
return total;
}
/* asset related functions */
function getAssets() external view returns (address[] memory) {
return assets;
}
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
) {
AssetData memory data = assetData[_asset];
return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio);
}
function addAsset(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_asset != address(0), "Pool: asset is zero address");
require(_max >= _min, "Pool: max < min");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
require(_asset != assets[i], "Pool: asset exists");
}
assets.push(_asset);
assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio);
}
function removeAsset(address _asset) external onlyGovernance {
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
delete assetData[_asset];
assets[i] = assets[assets.length - 1];
assets.pop();
return;
}
revert("Pool: asset not found");
}
function setAssetDetails(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_min <= _max, "Pool: min > max");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
assetData[_asset].minAmount = _min;
assetData[_asset].maxAmount = _max;
assetData[_asset].maxSlippageRatio = _maxSlippageRatio;
return;
}
revert("Pool: asset not found");
}
/* claim related functions */
/**
* @dev Execute the payout in case a claim is accepted
* @param asset token address or 0xEee...EEeE for ether
* @param payoutAddress send funds to this address
* @param amount amount to send
*/
function sendClaimPayout (
address asset,
address payable payoutAddress,
uint amount
) external onlyInternal nonReentrant returns (bool success) {
bool ok;
if (asset == ETH) {
// solhint-disable-next-line avoid-low-level-calls
(ok, /* data */) = payoutAddress.call.value(amount)("");
} else {
ok = _safeTokenTransfer(asset, payoutAddress, amount);
}
if (ok) {
emit Payout(payoutAddress, asset, amount);
}
return ok;
}
/**
* @dev safeTransfer implementation that does not revert
* @param tokenAddress ERC20 address
* @param to destination
* @param value amount to send
* @return success true if the transfer was successfull
*/
function _safeTokenTransfer (
address tokenAddress,
address to,
uint256 value
) internal returns (bool) {
// token address is not a contract
if (!tokenAddress.isContract()) {
return false;
}
IERC20 token = IERC20(tokenAddress);
bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = tokenAddress.call(data);
// low-level call failed/reverted
if (!success) {
return false;
}
// tokens that don't have return data
if (returndata.length == 0) {
return true;
}
// tokens that have return data will return a bool
return abi.decode(returndata, (bool));
}
/* pool lifecycle functions */
function transferAsset(
address asset,
address payable destination,
uint amount
) external onlyGovernance nonReentrant {
require(assetData[asset].maxAmount == 0, "Pool: max not zero");
require(destination != address(0), "Pool: dest zero");
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferableAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferableAmount);
}
function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant {
// transfer ether
uint ethBalance = address(this).balance;
(bool ok, /* data */) = newPoolAddress.call.value(ethBalance)("");
require(ok, "Pool: transfer failed");
// transfer assets
for (uint i = 0; i < assets.length; i++) {
IERC20 token = IERC20(assets[i]);
uint tokenBalance = token.balanceOf(address(this));
token.safeTransfer(newPoolAddress, tokenBalance);
}
}
/**
* @dev Update dependent contract address
* @dev Implements MasterAware interface function
*/
function changeDependentContractAddress() public {
nxmToken = NXMToken(master.tokenAddress());
tokenController = TokenController(master.getLatestAddress("TC"));
quotation = Quotation(master.getLatestAddress("QT"));
mcr = MCR(master.getLatestAddress("MC"));
}
/* cover purchase functions */
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable onlyMember whenNotPaused {
require(coverCurr == "ETH", "Pool: Unexpected asset type");
require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyMember whenNotPaused {
require(coverCurr != "ETH", "Pool: Unexpected asset type");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused {
IERC20 token = IERC20(asset);
token.safeTransferFrom(from, address(this), amount);
}
function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused {
if (asset == ETH) {
(bool ok, /* data */) = swapOperator.call.value(amount)("");
require(ok, "Pool: Eth transfer failed");
return;
}
IERC20 token = IERC20(asset);
token.safeTransfer(swapOperator, amount);
}
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused {
assetData[asset].lastSwapTime = lastSwapTime;
}
/* token sale functions */
/**
* @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) {
sellNXM(_amount, 0);
return true;
}
/**
* @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) external view returns (uint weiToPay) {
return getEthForNXM(amount);
}
/**
* @dev Buys NXM tokens with ETH.
* @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number.
* @return boughtTokens number of bought tokens.
*/
function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused {
uint ethIn = msg.value;
require(ethIn > 0, "Pool: ethIn > 0");
uint totalAssetValue = getPoolValueInEth().sub(ethIn);
uint mcrEth = mcr.getMCR();
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%");
uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth);
require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut");
tokenController.mint(msg.sender, tokensOut);
// evaluate the new MCR for the current asset value including the ETH paid in
mcr.updateMCRInternal(totalAssetValue.add(ethIn), false);
emit NXMBought(msg.sender, ethIn, tokensOut);
}
/**
* @dev Sell NXM tokens and receive ETH.
* @param tokenAmount Amount of tokens to sell.
* @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number.
* @return ethOut amount of ETH received in exchange for the tokens.
*/
function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused {
require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance");
require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting");
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth);
require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%");
require(ethOut >= minEthOut, "Pool: ethOut < minEthOut");
tokenController.burnFrom(msg.sender, tokenAmount);
(bool ok, /* data */) = msg.sender.call.value(ethOut)("");
require(ok, "Pool: Sell transfer failed");
// evaluate the new MCR for the current asset value excluding the paid out ETH
mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false);
emit NXMSold(msg.sender, tokenAmount, ethOut);
}
/**
* @dev Get value in tokens for an ethAmount purchase.
* @param ethAmount amount of ETH used for buying.
* @return tokenValue tokens obtained by buying worth of ethAmount
*/
function getNXMForEth(
uint ethAmount
) public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth);
}
function calculateNXMForEth(
uint ethAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Purchases worth higher than 5% of MCReth are not allowed"
);
/*
The price formula is:
P(V) = A + MCReth / C * MCR% ^ 4
where MCR% = V / MCReth
P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4
To compute the number of tokens issued we can integrate with respect to V the following:
ΔT = ΔV / P(V)
which assumes that for an infinitesimally small change in locked value V price is constant and we
get an infinitesimally change in token supply ΔT.
This is not computable on-chain, below we use an approximation that works well assuming
* MCR% stays within [100%, 400%]
* ethAmount <= 5% * MCReth
Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted.
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V.
adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue)
adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1
Evaluating the above using the antiderivative of the function we get:
adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3)
*/
if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) {
/*
If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A.
If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price).
This avoids overflow in the calculateIntegralAtPoint computation.
This approximation is safe from arbitrage since at MCR% < 100% no sells are possible.
*/
uint tokenPrice = CONSTANT_A;
return ethAmount.mul(1e18).div(tokenPrice);
}
// MCReth * C /(3 * V0 ^ 3)
uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth);
// MCReth * C / (3 * V1 ^3)
uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount);
uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth);
uint adjustedTokenAmount = point0.sub(point1);
/*
Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above,
and to that add the A constant (the price offset previously removed in the adjusted Price formula)
to obtain the finalPrice and ultimately the tokenValue based on the finalPrice.
adjustedPrice = ethAmount / adjustedTokenAmount
finalPrice = adjustedPrice + A
tokenValue = ethAmount / finalPrice
*/
// ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount
uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount);
uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A);
return ethAmount.mul(1e18).div(tokenPrice);
}
/**
* @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18
* computation result is multiplied by 1e18 to allow for a precision of 18 decimals.
* NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity
* WARNING: this low-level function should be called from a contract which checks that
* mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0
*/
function calculateIntegralAtPoint(
uint assetValue,
uint mcrEth
) internal pure returns (uint) {
return CONSTANT_C
.mul(1e18)
.div(3)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue);
}
function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) {
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth);
}
/**
* @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%.
* for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%.
* for values higher than that sell spread may exceed 2.5%
* (The higher amount being sold at any given time the higher the spread)
*/
function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
// Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
// Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
// Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ]
// Sell Spread = 2.5%
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) {
return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth);
}
/**
* @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4
*/
function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) {
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS);
return mcrEth
.mul(mcrRatio ** TOKEN_EXPONENT)
.div(CONSTANT_C)
.div(precisionDecimals)
.add(CONSTANT_A);
}
/**
* @dev Returns the NXM price in a given asset
* @param asset Asset name.
*/
function getTokenPrice(address asset) public view returns (uint tokenPrice) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth);
return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth);
}
function getMCRRatio() public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateMCRRatio(totalAssetValue, mcrEth);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MIN_ETH") {
minPoolEth = value;
return;
}
revert("Pool: unknown parameter");
}
function updateAddressParameters(bytes8 code, address value) external onlyGovernance {
if (code == "SWP_OP") {
swapOperator = value;
return;
}
if (code == "PRC_FEED") {
priceFeedOracle = PriceFeedOracle(value);
return;
}
revert("Pool: unknown parameter");
}
}
pragma solidity ^0.5.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.
*
* _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;
}
}
pragma solidity ^0.5.0;
/**
* @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);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 ERC20;` 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));
}
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");
}
}
}
pragma solidity ^0.5.0;
/**
* @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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity ^0.5.5;
/**
* @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 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");
}
}
/*
Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
*/
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract MasterAware {
INXMMaster public master;
modifier onlyMember {
require(master.isMember(msg.sender), "Caller is not a member");
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function changeDependentContractAddress() external;
function changeMasterAddress(address masterAddress) public onlyMaster {
master = INXMMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IPool {
function transferAssetToSwapOperator(address asset, uint amount) external;
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
);
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external;
function minPoolEth() external returns (uint);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../claims/Incidents.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "./QuotationData.sol";
contract Quotation is MasterAware, ReentrancyGuard {
using SafeMath for uint;
ClaimsReward public cr;
Pool public pool;
IPooledStaking public pooledStaking;
QuotationData public qd;
TokenController public tc;
TokenData public td;
Incidents public incidents;
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
cr = ClaimsReward(master.getLatestAddress("CR"));
pool = Pool(master.getLatestAddress("P1"));
pooledStaking = IPooledStaking(master.getLatestAddress("PS"));
qd = QuotationData(master.getLatestAddress("QD"));
tc = TokenController(master.getLatestAddress("TC"));
td = TokenData(master.getLatestAddress("TD"));
incidents = Incidents(master.getLatestAddress("IC"));
}
// solhint-disable-next-line no-empty-blocks
function sendEther() public payable {}
/**
* @dev Expires a cover after a set period of time and changes the status of the cover
* @dev Reduces the total and contract sum assured
* @param coverId Cover Id.
*/
function expireCover(uint coverId) external {
uint expirationDate = qd.getValidityOfCover(coverId);
require(expirationDate < now, "Quotation: cover is not due to expire");
uint coverStatus = qd.getCoverStatusNo(coverId);
require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired");
(/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId);
require(!hasOpenClaim, "Quotation: cover has an open claim");
if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) {
(,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId);
qd.subFromTotalSumAssured(currency, amount);
qd.subFromTotalSumAssuredSC(contractAddress, currency, amount);
}
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired));
}
function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external {
uint gracePeriod = tc.claimSubmissionGracePeriod();
for (uint i = 0; i < coverIds.length; i++) {
uint expirationDate = qd.getValidityOfCover(coverIds[i]);
require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration");
}
tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes);
}
function getWithdrawableCoverNoteCoverIds(
address coverOwner
) public view returns (
uint[] memory expiredCoverIds,
bytes32[] memory lockReasons
) {
uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner);
uint[] memory expiredIdsQueue = new uint[](coverIds.length);
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint expiredQueueLength = 0;
for (uint i = 0; i < coverIds.length; i++) {
uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]);
uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod);
(/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]);
if (!hasOpenClaim && gracePeriodExpirationDate < now) {
expiredIdsQueue[expiredQueueLength] = coverIds[i];
expiredQueueLength++;
}
}
expiredCoverIds = new uint[](expiredQueueLength);
lockReasons = new bytes32[](expiredQueueLength);
for (uint i = 0; i < expiredQueueLength; i++) {
expiredCoverIds[i] = expiredIdsQueue[i];
lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i]));
}
}
function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) {
uint withdrawableAmount;
bytes32[] memory lockReasons;
(/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner);
for (uint i = 0; i < lockReasons.length; i++) {
uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]);
withdrawableAmount = withdrawableAmount.add(coverNoteAmount);
}
return withdrawableAmount;
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] calldata coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyMember whenNotPaused {
tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyInternal {
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s,
false
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySignature(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
require(contractAddress != address(0));
bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
coverDetails[0],
currency,
coverPeriod,
contractAddress,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover(//solhint-disable-line
address payable from,
address contractAddress,
bytes4 coverCurrency,
uint[] memory coverDetails,
uint16 coverPeriod
) internal {
address underlyingToken = incidents.underlyingToken(contractAddress);
if (underlyingToken != address(0)) {
address coverAsset = cr.getCurrencyAssetAddress(coverCurrency);
require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product");
}
uint cid = qd.getCoverLength();
qd.addCover(
coverPeriod,
coverDetails[0],
from,
coverCurrency,
contractAddress,
coverDetails[1],
coverDetails[2]
);
uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100);
if (underlyingToken == address(0)) {
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod);
bytes32 reason = keccak256(abi.encodePacked("CN", from, cid));
// mint and lock cover note
td.setDepositCNAmount(cid, coverNoteAmount);
tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod);
} else {
// minted directly to member's wallet
tc.mint(from, coverNoteAmount);
}
qd.addInTotalSumAssured(coverCurrency, coverDetails[0]);
qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]);
uint coverPremiumInNXM = coverDetails[2];
uint stakersRewardPercentage = td.stakerCommissionPer();
uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100);
pooledStaking.accumulateReward(contractAddress, rewardValue);
}
/**
* @dev Makes a cover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool isNXM
) internal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
address asset = cr.getCurrencyAssetAddress(coverCurr);
if (coverCurr != "ETH" && !isNXM) {
pool.transferAssetFrom(asset, from, coverDetails[1]);
}
require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
function createCover(
address payable from,
address scAddress,
bytes4 currency,
uint[] calldata coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyInternal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, currency, coverDetails, coverPeriod);
}
// referenced in master, keeping for now
// solhint-disable-next-line no-empty-blocks
function transferAssetsToNewContract(address) external pure {}
function freeUpHeldCovers() external nonReentrant {
IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI"));
uint membershipFee = td.joiningFee();
uint lastCoverId = 106;
for (uint id = 1; id <= lastCoverId; id++) {
if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) {
continue;
}
(/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id);
(/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id);
uint refundedETH = membershipFee;
uint coverPremium = coverDetails[1];
if (qd.refundEligible(userAddress)) {
qd.setRefundEligible(userAddress, false);
}
qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
if (currency == "ETH") {
refundedETH = refundedETH.add(coverPremium);
} else {
require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed");
}
userAddress.transfer(refundedETH);
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface Aggregator {
function latestAnswer() external view returns (int);
}
contract PriceFeedOracle {
using SafeMath for uint;
mapping(address => address) public aggregators;
address public daiAddress;
address public stETH;
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor (
address _daiAggregator,
address _daiAddress,
address _stEthAddress
) public {
aggregators[_daiAddress] = _daiAggregator;
daiAddress = _daiAddress;
stETH = _stEthAddress;
}
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/
function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH || asset == stETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregatorAddress).latestAnswer();
require(rate > 0, "PriceFeedOracle: Rate must be > 0");
return uint(rate);
}
/**
* @dev Returns the amount of currency that is equivalent to ethIn amount of ether.
* @param asset quoted Supported values: ["DAI", "ETH"]
* @param ethIn amount of ether to be converted to the currency
* @return price in ether
*/
function getAssetForEth(address asset, uint ethIn) external view returns (uint) {
if (asset == daiAddress) {
return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress));
}
if (asset == ETH || asset == stETH) {
return ethIn;
}
revert("PriceFeedOracle: Unknown asset");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "./external/OZIERC20.sol";
import "./external/OZSafeMath.sol";
contract NXMToken is OZIERC20 {
using OZSafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
mapping(address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @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 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 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 Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @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 returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @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 canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, 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
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @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
)
internal
{
_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);
}
/**
* @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(amount <= _balances[account]);
_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 value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// 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(
value);
_burn(account, value);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
import "../../interfaces/IPooledStaking.sol";
import "../claims/ClaimsData.sol";
import "./NXMToken.sol";
import "./external/LockHandler.sol";
contract TokenController is LockHandler, Iupgradable {
using SafeMath for uint256;
struct CoverInfo {
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// note: still 224 bits available here, can be used later
}
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime;
uint public claimSubmissionGracePeriod;
// coverId => CoverInfo
mapping(uint => CoverInfo) public coverInfo;
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount);
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
modifier onlyGovernance {
require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance");
_;
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
function markCoverClaimOpen(uint coverId) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// reads all of them using a single SLOAD
(claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim);
// no safemath for uint16 but should be safe from
// overflows as there're max 2 claims per cover
claimCount = claimCount + 1;
require(claimCount <= 2, "TokenController: Max claim count exceeded");
require(hasOpenClaim == false, "TokenController: Cover already has an open claim");
require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims");
// should use a single SSTORE for both
(info.claimCount, info.hasOpenClaim) = (claimCount, true);
}
/**
* @param coverId cover id (careful, not claim id!)
* @param isAccepted claim verdict
*/
function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open");
// should use a single SSTORE for both
(info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted);
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) {
require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address");
token.operatorTransfer(_from, _value);
token.transfer(_to, _value);
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause {
require(minCALockTime <= _time, "TokenController: Must lock for minimum time");
require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
// If tokens are already locked, then functions extendLock or
// increaseClaimAssessmentLock should be used to make any changes
_lock(msg.sender, "CLA", _amount, _time);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Mints and locks a specified amount of tokens against an address,
* for a CN reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function mintCoverNote(
address _of,
bytes32 _reason,
uint256 _amount,
uint256 _time
) external onlyInternal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.mint(address(this), _amount);
uint256 lockedUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, lockedUntil, false);
emit Locked(_of, _reason, _amount, lockedUntil);
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _time Lock extension time in seconds
*/
function extendClaimAssessmentLock(uint256 _time) external checkPause {
uint256 validity = getLockedTokensValidity(msg.sender, "CLA");
require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
_extendLock(msg.sender, "CLA", _time);
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _amount Number of tokens to be increased
*/
function increaseClaimAssessmentLock(uint256 _amount) external checkPause
{
require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked");
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount);
emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity);
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom(address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the withdrawable tokens against CLA of a specified address
* @param _of Address of user, claiming back withdrawable tokens against CLA
*/
function withdrawClaimAssessmentTokens(address _of) external checkPause {
uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA");
if (withdrawableTokens > 0) {
locked[_of]["CLA"].claimed = true;
emit Unlocked(_of, "CLA", withdrawableTokens);
token.transfer(_of, withdrawableTokens);
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param value value to set
*/
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MNCLT") {
minCALockTime = value;
return;
}
if (code == "GRACEPER") {
claimSubmissionGracePeriod = value;
return;
}
revert("TokenController: invalid param code");
}
function getLockReasons(address _of) external view returns (bytes32[] memory reasons) {
return lockReason[_of];
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) {
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns tokens locked and validity for a specified address and reason
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLockedWithValidity(address _of, bytes32 _reason)
public
view
returns (uint256 amount, uint256 validity)
{
bool claimed = locked[_of][_reason].claimed;
amount = locked[_of][_reason].amount;
validity = locked[_of][_reason].validity;
if (claimed) {
amount = 0;
}
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total amount of locked and staked tokens.
* Used by MemberRoles to check eligibility for withdraw / switch membership.
* Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes
* Does not take into account pending burns.
* @param _of member whose locked tokens are to be calculate
*/
function totalLockedBalance(address _of) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.operatorTransfer(_of, _amount);
uint256 validUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.transfer(_of, _amount);
emit Unlocked(_of, _reason, _amount);
}
function withdrawCoverNote(
address _of,
uint[] calldata _coverIds,
uint[] calldata _indexes
) external onlyInternal {
uint reasonCount = lockReason[_of].length;
uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found");
uint totalAmount = 0;
// The iteration is done from the last to first to prevent reason indexes from
// changing due to the way we delete the items (copy last to current and pop last).
// The provided indexes array must be ordered, otherwise reason index checks will fail.
for (uint i = _coverIds.length; i > 0; i--) {
bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim;
require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim");
// note: cover owner is implicitly checked using the reason hash
bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1]));
uint _reasonIndex = _indexes[i - 1];
require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index");
uint amount = locked[_of][_reason].amount;
totalAmount = totalAmount.add(amount);
delete locked[_of][_reason];
if (lastReasonIndex != _reasonIndex) {
lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
emit Unlocked(_of, _reason, amount);
if (lastReasonIndex > 0) {
lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch");
}
}
token.transfer(_of, totalAmount);
}
function removeEmptyReason(address _of, bytes32 _reason, uint _index) external {
_removeEmptyReason(_of, _reason, _index);
}
function removeMultipleEmptyReasons(
address[] calldata _members,
bytes32[] calldata _reasons,
uint[] calldata _indexes
) external {
require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ");
require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ");
for (uint i = _members.length; i > 0; i--) {
uint idx = i - 1;
_removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]);
}
}
function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal {
uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty");
require(lockReason[_of][_index] == _reason, "TokenController: bad reason index");
require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero");
if (lastReasonIndex != _index) {
lockReason[_of][_index] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
}
function initialize() external {
require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized");
claimSubmissionGracePeriod = 120 days;
migrate();
}
function migrate() internal {
ClaimsData cd = ClaimsData(ms.getLatestAddress("CD"));
uint totalClaims = cd.actualClaimLength() - 1;
// fix stuck claims 21 & 22
cd.changeFinalVerdict(20, -1);
cd.setClaimStatus(20, 6);
cd.changeFinalVerdict(21, -1);
cd.setClaimStatus(21, 6);
// reduce claim assessment lock period for members locked for more than 180 days
// extracted using scripts/extract-ca-locked-more-than-180.js
address payable[3] memory members = [
0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc,
0x6b5DCDA27b5c3d88e71867D6b10b35372208361F,
0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617
];
for (uint i = 0; i < members.length; i++) {
if (locked[members[i]]["CLA"].validity > now + 180 days) {
locked[members[i]]["CLA"].validity = now + 180 days;
}
}
for (uint i = 1; i <= totalClaims; i++) {
(/*id*/, uint status) = cd.getClaimStatusNumber(i);
(/*id*/, uint coverId) = cd.getClaimCoverId(i);
int8 verdict = cd.getFinalVerdict(i);
// SLOAD
CoverInfo memory info = coverInfo[coverId];
info.claimCount = info.claimCount + 1;
info.hasAcceptedClaim = (status == 14);
info.hasOpenClaim = (verdict == 0);
// SSTORE
coverInfo[coverId] = info;
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenData.sol";
import "./LegacyMCR.sol";
contract MCR is MasterAware {
using SafeMath for uint;
Pool public pool;
QuotationData public qd;
// sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot)
uint96 _unused;
// the following values are expressed in basis points
uint24 public mcrFloorIncrementThreshold = 13000;
uint24 public maxMCRFloorIncrement = 100;
uint24 public maxMCRIncrement = 500;
uint24 public gearingFactor = 48000;
// min update between MCR updates in seconds
uint24 public minUpdateTime = 3600;
uint112 public mcrFloor;
uint112 public mcr;
uint112 public desiredMCR;
uint32 public lastUpdateTime;
LegacyMCR public previousMCR;
event MCRUpdated(
uint mcr,
uint desiredMCR,
uint mcrFloor,
uint mcrETHWithGear,
uint totalSumAssured
);
uint constant UINT24_MAX = ~uint24(0);
uint constant MAX_MCR_ADJUSTMENT = 100;
uint constant BASIS_PRECISION = 10000;
constructor (address masterAddress) public {
changeMasterAddress(masterAddress);
if (masterAddress != address(0)) {
previousMCR = LegacyMCR(master.getLatestAddress("MC"));
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
qd = QuotationData(master.getLatestAddress("QD"));
pool = Pool(master.getLatestAddress("P1"));
initialize();
}
function initialize() internal {
address currentMCR = master.getLatestAddress("MC");
if (address(previousMCR) == address(0) || currentMCR != address(this)) {
// already initialized or not ready for initialization
return;
}
// fetch MCR parameters from previous contract
uint112 minCap = 7000 * 1e18;
mcrFloor = uint112(previousMCR.variableMincap()) + minCap;
mcr = uint112(previousMCR.getLastMCREther());
desiredMCR = mcr;
mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100());
maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100());
// set last updated time to now
lastUpdateTime = uint32(block.timestamp);
previousMCR = LegacyMCR(address(0));
}
/**
* @dev Gets total sum assured (in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns (uint) {
PriceFeedOracle priceFeed = pool.priceFeedOracle();
address daiAddress = priceFeed.daiAddress();
uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18);
uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18);
uint daiRate = priceFeed.getAssetToEthRate(daiAddress);
uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18);
return ethAmount.add(daiAmountInEth);
}
/*
* @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated
* and a new desiredMCR value to move towards is set.
*
*/
function updateMCR() public {
_updateMCR(pool.getPoolValueInEth(), false);
}
function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal {
_updateMCR(poolValueInEth, forceUpdate);
}
function _updateMCR(uint poolValueInEth, bool forceUpdate) internal {
// read with 1 SLOAD
uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold;
uint _maxMCRFloorIncrement = maxMCRFloorIncrement;
uint _gearingFactor = gearingFactor;
uint _minUpdateTime = minUpdateTime;
uint _mcrFloor = mcrFloor;
// read with 1 SLOAD
uint112 _mcr = mcr;
uint112 _desiredMCR = desiredMCR;
uint32 _lastUpdateTime = lastUpdateTime;
if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) {
return;
}
if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) {
// MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3
// MCR floor is monotonically increasing.
uint basisPointsAdjustment = min(
_maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days),
_maxMCRFloorIncrement
);
uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION);
require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow');
mcrFloor = uint112(newMCRFloor);
}
// sync the current virtual MCR value to storage
uint112 newMCR = uint112(getMCR());
if (newMCR != _mcr) {
mcr = newMCR;
}
// the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based
// on the changes in the totalSumAssured in the system.
uint totalSumAssured = getAllSumAssurance();
uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor);
uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor));
if (newDesiredMCR != _desiredMCR) {
desiredMCR = newDesiredMCR;
}
lastUpdateTime = uint32(block.timestamp);
emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured);
}
/**
* @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away
* from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime.
* The total change in virtual MCR cannot exceed 1% of stored mcr.
*
* This approach allows for the MCR to change smoothly across time without sudden jumps between values, while
* always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR
* so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa.
*
* @return mcr
*/
function getMCR() public view returns (uint) {
// read with 1 SLOAD
uint _mcr = mcr;
uint _desiredMCR = desiredMCR;
uint _lastUpdateTime = lastUpdateTime;
if (block.timestamp == _lastUpdateTime) {
return _mcr;
}
uint _maxMCRIncrement = maxMCRIncrement;
uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days);
basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT);
if (_desiredMCR > _mcr) {
return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR);
}
// in case desiredMCR <= mcr
return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR);
}
function getGearedMCR() external view returns (uint) {
return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor);
}
function min(uint x, uint y) pure internal returns (uint) {
return x < y ? x : y;
}
function max(uint x, uint y) pure internal returns (uint) {
return x > y ? x : y;
}
/**
* @dev Updates Uint Parameters
* @param code parameter code
* @param val new value
*/
function updateUintParameters(bytes8 code, uint val) public {
require(master.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
require(val <= UINT24_MAX, "MCR: value too large");
mcrFloorIncrementThreshold = uint24(val);
} else if (code == "DMCI") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRFloorIncrement = uint24(val);
} else if (code == "MMIC") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRIncrement = uint24(val);
} else if (code == "GEAR") {
require(val <= UINT24_MAX, "MCR: value too large");
gearingFactor = uint24(val);
} else if (code == "MUTI") {
require(val <= UINT24_MAX, "MCR: value too large");
minUpdateTime = uint24(val);
} else {
revert("Invalid param code");
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns (bool);
function isInternal(address _add) public view returns (bool);
function isPause() public view returns (bool check);
function isOwner(address _add) public view returns (bool);
function isMember(address _add) public view returns (bool);
function checkIsAuthToGoverned(address _add) public view returns (bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns (address _add);
function dAppToken() public view returns (address _add);
function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity ^0.5.0;
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../governance/Governance.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Claims.sol";
import "./ClaimsData.sol";
import "../capital/MCR.sol";
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool internal pool;
Governance internal gv;
IPooledStaking internal pooledStaking;
MemberRoles internal memberRoles;
MCR public mcr;
// assigned in constructor
address public DAI;
// constants
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint private constant DECIMAL1E18 = uint(10) ** 18;
constructor (address masterAddress, address _daiAddress) public {
changeMasterAddress(masterAddress);
DAI = _daiAddress;
}
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
memberRoles = MemberRoles(ms.getLatestAddress("MR"));
pool = Pool(ms.getLatestAddress("P1"));
mcr = MCR(ms.getLatestAddress("MC"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
(, uint coverid) = cd.getClaimCoverId(claimid);
(, uint status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) {// when current status is "Claim Accepted Payout Pending"
bool payoutSucceeded = attemptClaimPayout(coverid);
if (payoutSucceeded) {
c1.setClaimStatus(claimid, 14);
} else {
c1.setClaimStatus(claimid, 12);
}
}
}
function getCurrencyAssetAddress(bytes4 currency) public view returns (address) {
if (currency == "ETH") {
return ETH;
}
if (currency == "DAI") {
return DAI;
}
revert("ClaimsReward: unknown asset");
}
function attemptClaimPayout(uint coverId) internal returns (bool success) {
uint sumAssured = qd.getCoverSumAssured(coverId);
// TODO: when adding new cover currencies, fetch the correct decimals for this multiplication
uint sumAssuredWei = sumAssured.mul(1e18);
// get asset address
bytes4 coverCurrency = qd.getCurrencyOfCover(coverId);
address asset = getCurrencyAssetAddress(coverCurrency);
// get payout address
address payable coverHolder = qd.getCoverMemberAddress(coverId);
address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder);
// execute the payout
bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei);
if (payoutSucceeded) {
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = pool.getTokenPrice(asset);
// note: for new assets "18" needs to be replaced with target asset decimals
uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
// adjust total sum assured
(, address coverContract) = qd.getscAddressOfCover(coverId);
qd.subFromTotalSumAssured(coverCurrency, sumAssured);
qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured);
// update MCR since total sum assured and MCR% change
mcr.updateMCRInternal(pool.getPoolValueInEth(), true);
return true;
}
return false;
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenCA(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenMV(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns (uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
}
(reward,,,) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns (uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
// denied
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
tc.markCoverClaimClosed(coverid, false);
_burnCoverNoteDeposit(coverid);
// accepted
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
tc.markCoverClaimClosed(coverid, true);
_unlockCoverNote(coverid);
bool payoutSucceeded = attemptClaimPayout(coverid);
// 12 = payout pending, 14 = payout succeeded
uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
}
}
function _burnCoverNoteDeposit(uint coverId) internal {
address _of = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
uint lockedAmount = tc.tokensLocked(_of, reason);
(uint amount,) = td.depositedCN(coverId);
amount = amount.div(2);
// limit burn amount to actual amount locked
uint burnAmount = lockedAmount < amount ? lockedAmount : amount;
if (burnAmount != 0) {
tc.burnLockedTokens(_of, reason, amount);
}
}
function _unlockCoverNote(uint coverId) internal {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
uint lockedCN = tc.tokensLocked(coverHolder, reason);
if (lockedCN != 0) {
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, - 1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, - 1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex,) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc,,) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total = 0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); // solhint-disable-line
}
}
/* Copyright (C) 2021 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsData.sol";
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../governance/MemberRoles.sol";
import "../token/TokenController.sol";
import "../capital/MCR.sol";
contract Incidents is MasterAware {
using SafeERC20 for IERC20;
using SafeMath for uint;
struct Incident {
address productId;
uint32 date;
uint priceBefore;
}
// contract identifiers
enum ID {CD, CR, QD, TC, MR, P1, PS, MC}
mapping(uint => address payable) public internalContracts;
Incident[] public incidents;
// product id => underlying token (ex. yDAI -> DAI)
mapping(address => address) public underlyingToken;
// product id => covered token (ex. 0xc7ed.....1 -> yDAI)
mapping(address => address) public coveredToken;
// claim id => payout amount
mapping(uint => uint) public claimPayout;
// product id => accumulated burn amount
mapping(address => uint) public accumulatedBurn;
// burn ratio in bps, ex 2000 for 20%
uint public BURN_RATIO;
// burn ratio in bps
uint public DEDUCTIBLE_RATIO;
uint constant BASIS_PRECISION = 10000;
event ProductAdded(
address indexed productId,
address indexed coveredToken,
address indexed underlyingToken
);
event IncidentAdded(
address indexed productId,
uint incidentDate,
uint priceBefore
);
modifier onlyAdvisoryBoard {
uint abRole = uint(MemberRoles.Role.AdvisoryBoard);
require(
memberRoles().checkRole(msg.sender, abRole),
"Incidents: Caller is not an advisory board member"
);
_;
}
function initialize() external {
require(BURN_RATIO == 0, "Already initialized");
BURN_RATIO = 2000;
DEDUCTIBLE_RATIO = 9000;
}
function addProducts(
address[] calldata _productIds,
address[] calldata _coveredTokens,
address[] calldata _underlyingTokens
) external onlyAdvisoryBoard {
require(
_productIds.length == _coveredTokens.length,
"Incidents: Protocols and covered tokens lengths differ"
);
require(
_productIds.length == _underlyingTokens.length,
"Incidents: Protocols and underyling tokens lengths differ"
);
for (uint i = 0; i < _productIds.length; i++) {
address id = _productIds[i];
require(coveredToken[id] == address(0), "Incidents: covered token is already set");
require(underlyingToken[id] == address(0), "Incidents: underlying token is already set");
coveredToken[id] = _coveredTokens[i];
underlyingToken[id] = _underlyingTokens[i];
emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]);
}
}
function incidentCount() external view returns (uint) {
return incidents.length;
}
function addIncident(
address productId,
uint incidentDate,
uint priceBefore
) external onlyGovernance {
address underlying = underlyingToken[productId];
require(underlying != address(0), "Incidents: Unsupported product");
Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore);
incidents.push(incident);
emit IncidentAdded(productId, incidentDate, priceBefore);
}
function redeemPayoutForMember(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address member
) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member);
}
function redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount
) external returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender);
}
function _redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address coverOwner
) internal returns (uint claimId, uint payoutAmount, address coverAsset) {
QuotationData qd = quotationData();
Incident memory incident = incidents[incidentId];
uint sumAssured;
bytes4 currency;
{
address productId;
address _coverOwner;
(/* id */, _coverOwner, productId,
currency, sumAssured, /* premiumNXM */
) = qd.getCoverDetailsByCoverID1(coverId);
// check ownership and covered protocol
require(coverOwner == _coverOwner, "Incidents: Not cover owner");
require(productId == incident.productId, "Incidents: Bad incident id");
}
{
uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days);
uint coverExpirationDate = qd.getValidityOfCover(coverId);
uint coverStartDate = coverExpirationDate.sub(coverPeriod);
// check cover validity
require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident");
require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident");
// check grace period
uint gracePeriod = tokenController().claimSubmissionGracePeriod();
require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired");
}
{
// assumes 18 decimals (eth & dai)
uint decimalPrecision = 1e18;
uint maxAmount;
// sumAssured is currently stored without decimals
uint coverAmount = sumAssured.mul(decimalPrecision);
{
// max amount check
uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION);
maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore);
require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured");
}
// payoutAmount = coveredTokenAmount / maxAmount * coverAmount
// = coveredTokenAmount * coverAmount / maxAmount
payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount);
}
{
TokenController tc = tokenController();
// mark cover as having a successful claim
tc.markCoverClaimOpen(coverId);
tc.markCoverClaimClosed(coverId, true);
// create the claim
ClaimsData cd = claimsData();
claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
cd.setClaimStatus(claimId, 14);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted));
claimPayout[claimId] = payoutAmount;
}
coverAsset = claimsReward().getCurrencyAssetAddress(currency);
_sendPayoutAndPushBurn(
incident.productId,
address(uint160(coverOwner)),
coveredTokenAmount,
coverAsset,
payoutAmount
);
qd.subFromTotalSumAssured(currency, sumAssured);
qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured);
mcr().updateMCRInternal(pool().getPoolValueInEth(), true);
}
function pushBurns(address productId, uint maxIterations) external {
uint burnAmount = accumulatedBurn[productId];
delete accumulatedBurn[productId];
require(burnAmount > 0, "Incidents: No burns to push");
require(maxIterations >= 30, "Incidents: Pass at least 30 iterations");
IPooledStaking ps = pooledStaking();
ps.pushBurn(productId, burnAmount);
ps.processPendingActions(maxIterations);
}
function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance {
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferAmount);
}
function _sendPayoutAndPushBurn(
address productId,
address payable coverOwner,
uint coveredTokenAmount,
address coverAsset,
uint payoutAmount
) internal {
address _coveredToken = coveredToken[productId];
// pull depegged tokens
IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount);
Pool p1 = pool();
// send the payoutAmount
{
address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner);
bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount);
require(success, "Incidents: Payout failed");
}
{
// burn
uint decimalPrecision = 1e18;
uint assetPerNxm = p1.getTokenPrice(coverAsset);
uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm);
uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION);
accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount);
}
}
function claimsData() internal view returns (ClaimsData) {
return ClaimsData(internalContracts[uint(ID.CD)]);
}
function claimsReward() internal view returns (ClaimsReward) {
return ClaimsReward(internalContracts[uint(ID.CR)]);
}
function quotationData() internal view returns (QuotationData) {
return QuotationData(internalContracts[uint(ID.QD)]);
}
function tokenController() internal view returns (TokenController) {
return TokenController(internalContracts[uint(ID.TC)]);
}
function memberRoles() internal view returns (MemberRoles) {
return MemberRoles(internalContracts[uint(ID.MR)]);
}
function pool() internal view returns (Pool) {
return Pool(internalContracts[uint(ID.P1)]);
}
function pooledStaking() internal view returns (IPooledStaking) {
return IPooledStaking(internalContracts[uint(ID.PS)]);
}
function mcr() internal view returns (MCR) {
return MCR(internalContracts[uint(ID.MC)]);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "BURNRATE") {
require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000");
BURN_RATIO = value;
return;
}
if (code == "DEDUCTIB") {
require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000");
DEDUCTIBLE_RATIO = value;
return;
}
revert("Incidents: Invalid parameter");
}
function changeDependentContractAddress() external {
INXMMaster master = INXMMaster(master);
internalContracts[uint(ID.CD)] = master.getLatestAddress("CD");
internalContracts[uint(ID.CR)] = master.getLatestAddress("CR");
internalContracts[uint(ID.QD)] = master.getLatestAddress("QD");
internalContracts[uint(ID.TC)] = master.getLatestAddress("TC");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.PS)] = master.getLatestAddress("PS");
internalContracts[uint(ID.MC)] = master.getLatestAddress("MC");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {//solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns (uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns (bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover}
enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested}
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount);
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount);
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns (uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns (address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns (uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns (uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns (uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns (uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns (uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns (address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface OZIERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library OZSafeMath {
/**
* @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;
}
}
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
pragma solidity ^0.5.0;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function processPendingActions(uint maxIterations) external returns (bool finished);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt);
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns (
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns (
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns (uint voteCount) {
return allvotes.length.sub(1); // Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns (uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns (uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns (
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns (address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns (uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns (uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns (uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns (uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns (
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns (
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns (
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns (
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns (
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns (uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns (uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns (uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns (uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns (int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns (uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns (
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); // 0 Pending-Claim Assessor Vote
_pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); // 12 Claim Accepted Payout Pending
_pushStatus(0, 0); // 13 Claim Accepted No Payout
_pushStatus(0, 0); // 14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract LockHandler {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
}
pragma solidity ^0.5.0;
interface LegacyMCR {
function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external;
function addLastMCRData(uint64 date) external;
function changeDependentContractAddress() external;
function getAllSumAssurance() external view returns (uint amount);
function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice);
function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice);
function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp);
function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold);
function getMaxSellTokens() external view returns (uint maxTokens);
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val);
function updateUintParameters(bytes8 code, uint val) external;
function variableMincap() external view returns (uint);
function dynamicMincapThresholdx100() external view returns (uint);
function dynamicMincapIncrementx100() external view returns (uint);
function getLastMCREther() external view returns (uint);
}
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../token/TokenController.sol";
import "./MemberRoles.sol";
import "./ProposalCategory.sol";
import "./external/IGovernance.sol";
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint => uint) memberVoteValue;
mapping(uint => uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping(address => mapping(uint => uint)) public memberProposalVote;
mapping(address => uint) public followerDelegation;
mapping(address => uint) internal followerCount;
mapping(address => uint[]) internal leaderDelegation;
mapping(uint => VoteTally) public proposalVoteTally;
mapping(address => bool) public isOpenForDelegation;
mapping(address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns (uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return (
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) {
return (
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns (uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns (uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns (uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns (bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(,,,, mrAllowed,,) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns (bool delegated) {
for (uint i = 0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns (uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns (uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime,) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10 ** 18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10 ** 18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns (uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns (bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
// solhint-disable-next-line avoid-low-level-calls
(bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(,, _majorityVote,,,,) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/MasterAware.sol";
import "../cover/QuotationData.sol";
import "./NXMToken.sol";
import "./TokenController.sol";
import "./TokenData.sol";
contract TokenFunctions is MasterAware {
using SafeMath for uint;
TokenController public tc;
NXMToken public tk;
QuotationData public qd;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns (uint) {
uint[] memory coverIds = qd.getAllCoversOfUser(_of);
uint total;
for (uint i = 0; i < coverIds.length; i++) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i]));
uint coverNote = tc.tokensLocked(_of, reason);
total = total.add(coverNote);
}
return total;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tc = TokenController(master.getLatestAddress("TC"));
tk = NXMToken(master.tokenAddress());
qd = QuotationData(master.getLatestAddress("QD"));
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance {
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns (bool) {
return now < tk.isLockedForMV(_of);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "../token/TokenFunctions.sol";
import "./ClaimsData.sol";
import "./Incidents.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenController internal tc;
ClaimsReward internal cr;
Pool internal p1;
ClaimsData internal cd;
TokenData internal td;
QuotationData internal qd;
Incidents internal incidents;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns (uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool(ms.getLatestAddress("P1"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
incidents = Incidents(ms.getLatestAddress("IC"));
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) external {
_submitClaim(coverId, msg.sender);
}
function submitClaimForMember(uint coverId, address member) external onlyInternal {
_submitClaim(coverId, member);
}
function _submitClaim(uint coverId, address member) internal {
require(!ms.isPause(), "Claims: System is paused");
(/* id */, address contractAddress) = qd.getscAddressOfCover(coverId);
address token = incidents.coveredToken(contractAddress);
require(token == address(0), "Claims: Product type does not allow claims");
address coverOwner = qd.getCoverMemberAddress(coverId);
require(coverOwner == member, "Claims: Not cover owner");
uint expirationDate = qd.getValidityOfCover(coverId);
uint gracePeriod = tc.claimSubmissionGracePeriod();
require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired");
tc.markCoverClaimOpen(coverId);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
uint claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
}
// solhint-disable-next-line no-empty-blocks
function submitClaimAfterEPOff() external pure {}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
// solhint-disable-next-line no-empty-blocks
function pauseAllPendingClaimsVoting() external pure {}
// solhint-disable-next-line no-empty-blocks
function startAllPendingClaimsVoting() external pure {}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns (int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = - 1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
cd.setClaimdateUpd(claimId, now);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Governance.sol";
import "./external/Governed.sol";
contract MemberRoles is Governed, Iupgradable {
TokenController public tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
mapping (address => address payable) internal claimPayoutAddress;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember(
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner(
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0)) {
require(masterAddress == msg.sender);
}
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate(address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(//solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(//solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
tc.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
tc.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); // solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); // solhint-disable-line
}
}
/**
* @dev withdraws membership for msg.sender if currently a member.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(msg.sender);
tc.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
tc.removeFromWhitelist(msg.sender); // need clarification on whitelist
if (claimPayoutAddress[msg.sender] != address(0)) {
claimPayoutAddress[msg.sender] = address(0);
emit ClaimPayoutAddressSet(msg.sender, address(0));
}
}
/**
* @dev switches membership for msg.sender to the specified address.
* @param newAddress address of user to forward membership.
*/
function switchMembership(address newAddress) external {
_switchMembership(msg.sender, newAddress);
tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender));
}
function switchMembershipOf(address member, address newAddress) external onlyInternal {
_switchMembership(member, newAddress);
}
/**
* @dev switches membership for member to the specified address.
* @param newAddress address of user to forward membership.
*/
function _switchMembership(address member, address newAddress) internal {
require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress));
require(tc.totalLockedBalance(member) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(member);
tc.addToWhitelist(newAddress);
_updateRole(newAddress, uint(Role.Member), true);
_updateRole(member, uint(Role.Member), false);
tc.removeFromWhitelist(member);
address payable previousPayoutAddress = claimPayoutAddress[member];
if (previousPayoutAddress != address(0)) {
address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress;
claimPayoutAddress[member] = address(0);
claimPayoutAddress[newAddress] = storedAddress;
// emit event for old address reset
emit ClaimPayoutAddressSet(member, address(0));
if (storedAddress != address(0)) {
// emit event for setting the payout address on the new member address if it's non zero
emit ClaimPayoutAddressSet(newAddress, storedAddress);
}
}
emit switchedMembership(member, newAddress, now);
}
function getClaimPayoutAddress(address payable _member) external view returns (address payable) {
address payable payoutAddress = claimPayoutAddress[_member];
return payoutAddress != address(0) ? payoutAddress : _member;
}
function setClaimPayoutAddress(address payable _address) external {
require(!ms.isPause(), "system is paused");
require(ms.isMember(msg.sender), "sender is not a member");
require(_address != msg.sender, "should be different than the member address");
claimPayoutAddress[msg.sender] = _address;
emit ClaimPayoutAddressSet(msg.sender, _address);
}
/// @dev Return number of member roles
function totalRoles() public view returns (uint256) {//solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../../abstract/Iupgradable.sol";
import "./MemberRoles.sol";
import "./external/Governed.sol";
import "./external/IProposalCategory.sol";
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint => CategoryAction) internal categoryActionData;
mapping(uint => uint) public categoryABReq;
mapping(uint => uint) public isSpecialResolution;
mapping(uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
) external {}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) {
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) {
return (
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
) public {}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns (uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns (uint closeValue);
function allowedToCatgorize() public view returns (uint roleId);
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
interface IMaster {
function getLatestAddress(bytes2 _module) external view returns (address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns (bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns (
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns (
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns (uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
| Transfers all tokens held by contract to a new contract in case of upgrade. | function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
| 2,578,051 |
/*
Copyright (c) 2020 Fuel Labs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.1;
/*
Authors: DappHub
License: GNU
Modified by: FuelLabs
*/
contract DSMath {
function ds_add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function ds_sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function ds_mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
contract ERC20 {
// METHODS
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
// EVENTS
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract FuelConstants {
// CONSTANTS
uint256 constant public BOND_SIZE = .1 ether; // required for block commitment
uint256 constant public FINALIZATION_DELAY = 7 days / 12; // ~ 1 weeks at 12 second block times
uint256 constant public SUBMISSION_DELAY = uint256(2 days) / 12; // ~ 2 day (should be 2 days) in Ethereum Blocks
uint256 constant public CLOSING_DELAY = uint256(90 days) / 12; // (should be 2 months)
uint256 constant public MAX_TRANSACTIONS_SIZE = 58823;
uint256 constant public TRANSACTION_ROOTS_MAX = 256;
// ASSEMBLY ONLY FRAUD CODES
uint256 constant FraudCode_InvalidMetadataBlockHeight = 0;
uint256 constant FraudCode_TransactionHashZero = 1;
uint256 constant FraudCode_TransactionIndexOverflow = 2;
uint256 constant FraudCode_MetadataOutputIndexOverflow = 3;
uint256 constant FraudCode_InvalidUTXOHashReference = 4;
uint256 constant FraudCode_InvalidReturnWitnessNotSpender = 5;
uint256 constant FraudCode_InputDoubleSpend = 6;
uint256 constant FraudCode_InvalidMerkleTreeRoot = 7;
uint256 constant FraudCode_MetadataBlockHeightUnderflow = 8;
uint256 constant FraudCode_MetadataBlockHeightOverflow = 9;
uint256 constant FraudCode_InvalidHTLCDigest = 10;
uint256 constant FraudCode_TransactionLengthUnderflow = 11;
uint256 constant FraudCode_TransactionLengthOverflow = 12;
uint256 constant FraudCode_InvalidTransactionInputType = 13;
uint256 constant FraudCode_TransactionOutputWitnessReferenceOverflow = 14;
uint256 constant FraudCode_InvalidTransactionOutputType = 15;
uint256 constant FraudCode_TransactionSumMismatch = 16;
uint256 constant FraudCode_TransactionInputWitnessReferenceOverflow = 17;
uint256 constant FraudCode_TransactionInputDepositZero = 18;
uint256 constant FraudCode_TransactionInputDepositWitnessOverflow = 19;
uint256 constant FraudCode_TransactionHTLCWitnessOverflow = 20;
uint256 constant FraudCode_TransactionOutputAmountLengthUnderflow = 21;
uint256 constant FraudCode_TransactionOutputAmountLengthOverflow = 22;
uint256 constant FraudCode_TransactionOutputTokenIDOverflow = 23;
uint256 constant FraudCode_TransactionOutputHTLCDigestZero = 24;
uint256 constant FraudCode_TransactionOutputHTLCExpiryZero = 25;
uint256 constant FraudCode_InvalidTransactionWitnessSignature = 26;
uint256 constant FraudCode_TransactionWitnessesLengthUnderflow = 27;
uint256 constant FraudCode_TransactionWitnessesLengthOverflow = 28;
uint256 constant FraudCode_TransactionInputsLengthUnderflow = 29;
uint256 constant FraudCode_TransactionInputsLengthOverflow = 30;
uint256 constant FraudCode_TransactionOutputsLengthUnderflow = 31;
uint256 constant FraudCode_TransactionOutputsLengthOverflow = 32;
uint256 constant FraudCode_TransactionMetadataLengthOverflow = 33;
uint256 constant FraudCode_TransactionInputSelectorOverflow = 34;
uint256 constant FraudCode_TransactionOutputSelectorOverflow = 35;
uint256 constant FraudCode_TransactionWitnessSelectorOverflow = 37;
uint256 constant FraudCode_TransactionUTXOType = 38;
uint256 constant FraudCode_TransactionUTXOOutputIndexOverflow = 39;
uint256 constant FraudCode_InvalidTransactionsNetLength = 40;
uint256 constant FraudCode_MetadataTransactionsRootsLengthOverflow = 41;
uint256 constant FraudCode_ComputedTransactionLengthOverflow = 42;
uint256 constant FraudCode_ProvidedDataOverflow = 43;
uint256 constant FraudCode_MetadataReferenceOverflow = 44;
uint256 constant FraudCode_OutputHTLCExpiryUnderflow = 45;
uint256 constant FraudCode_InvalidInputWithdrawalSpend = 46;
uint256 constant FraudCode_InvalidTypeReferenceMismatch = 47;
uint256 constant FraudCode_InvalidChangeInputSpender = 48;
uint256 constant FraudCode_InvalidTransactionRootIndexOverflow = 49;
// ASSEMBLY ONLY ERROR CODES
uint256 constant ErrorCode_InvalidTypeDeposit = 0;
uint256 constant ErrorCode_InputReferencedNotProvided = 1;
uint256 constant ErrorCode_InvalidReturnWitnessSelected = 2;
uint256 constant ErrroCode_InvalidReturnWitnessAddressEmpty = 3;
uint256 constant ErrroCode_InvalidSpenderWitnessAddressEmpty = 4;
uint256 constant ErrorCode_InvalidTransactionComparison = 5;
uint256 constant ErrorCode_WithdrawalAlreadyHappened = 6;
uint256 constant ErrorCode_BlockProducerNotCaller = 7;
uint256 constant ErrorCode_BlockBondAlreadyWithdrawn = 8;
uint256 constant ErrorCode_InvalidProofType = 9;
uint256 constant ErrorCode_BlockHashNotFound = 10;
uint256 constant ErrorCode_BlockHeightOverflow = 11;
uint256 constant ErrorCode_BlockHeightUnderflow = 12;
uint256 constant ErrorCode_BlockNotFinalized = 13;
uint256 constant ErrorCode_BlockFinalized = 14;
uint256 constant ErrorCode_TransactionRootLengthUnderflow = 15;
uint256 constant ErrorCode_TransactionRootIndexOverflow = 16;
uint256 constant ErrorCode_TransactionRootHashNotInBlockHeader = 17;
uint256 constant ErrorCode_TransactionRootHashInvalid = 18;
uint256 constant ErrorCode_TransactionLeafHashInvalid = 19;
uint256 constant ErrorCode_MerkleTreeHeightOverflow = 20;
uint256 constant ErrorCode_MerkleTreeRootInvalid = 21;
uint256 constant ErrorCode_InputIndexSelectedOverflow = 22;
uint256 constant ErrorCode_OutputIndexSelectedOverflow = 23;
uint256 constant ErrorCode_WitnessIndexSelectedOverflow = 24;
uint256 constant ErrorCode_TransactionUTXOIDInvalid = 25;
uint256 constant ErrorCode_FraudBlockHeightUnderflow = 26;
uint256 constant ErrorCode_FraudBlockFinalized = 27;
uint256 constant ErrorCode_SafeMathAdditionOverflow = 28;
uint256 constant ErrorCode_SafeMathSubtractionUnderflow = 29;
uint256 constant ErrorCode_SafeMathMultiplyOverflow = 30;
uint256 constant ErrorCode_TransferAmountUnderflow = 31;
uint256 constant ErrorCode_TransferOwnerInvalid = 32;
uint256 constant ErrorCode_TransferTokenIDOverflow = 33;
uint256 constant ErrorCode_TransferEtherCallResult = 34;
uint256 constant ErrorCode_TransferERC20Result = 35;
uint256 constant ErrorCode_TransferTokenAddress = 36;
uint256 constant ErrorCode_InvalidPreviousBlockHash = 37;
uint256 constant ErrorCode_TransactionRootsLengthUnderflow = 38;
uint256 constant ErrorCode_TransactionRootsLengthOverflow = 39;
uint256 constant ErrorCode_InvalidWithdrawalOutputType = 40;
uint256 constant ErrorCode_InvalidWithdrawalOwner = 41;
uint256 constant ErrorCode_InvalidDepositProof = 42;
uint256 constant ErrorCode_InvalidTokenAddress = 43;
uint256 constant ErrorCode_InvalidBlockHeightReference = 44;
uint256 constant ErrorCode_InvalidOutputIndexReference = 45;
uint256 constant ErrorCode_InvalidTransactionRootReference = 46;
uint256 constant ErrorCode_InvalidTransactionIndexReference = 47;
uint256 constant ErrorCode_ProofLengthOverflow = 48;
uint256 constant ErrorCode_InvalidTransactionsABILengthOverflow = 49;
// ASSEMBLY ONLY CONSTANTS
// Memory Layout * 32
// 0 -> 12 Swap for hashing, ecrecover, events data etc]
// 12 -> 44 Virtual Stack Memory (stack and swap behind writeable calldata for safety)
// 44 -> calldatasize() Calldata
// 44 + calldatasize() Free Memory
// Calldata Memory Position
uint256 constant Swap_MemoryPosition = 0 * 32; // Swap -> 12
uint256 constant Stack_MemoryPosition = 12 * 32; // Virtual Stack -> 44
uint256 constant Calldata_MemoryPosition = 44 * 32; // Calldata
// Length and Index max/min for Inputs, Outputs, Witnesses, Metadata
uint256 constant TransactionLengthMax = 8;
uint256 constant TransactionLengthMin = 0;
// Metadata, Witness and UTXO Proof Byte Size, Types and Lengths etc..
uint256 constant MetadataSize = 8;
uint256 constant WitnessSize = 65;
uint256 constant UTXOProofSize = 9 * 32;
uint256 constant DepositProofSize = 96;
uint256 constant TypeSize = 1;
uint256 constant LengthSize = 1;
uint256 constant TransactionLengthSize = 2;
uint256 constant DigestSize = 32;
uint256 constant ExpirySize = 4;
uint256 constant IndexSize = 1;
// Booleans
uint256 constant True = 1;
uint256 constant False = 0;
// Minimum and Maximum transaction byte length
uint256 constant TransactionSizeMinimum = 100;
uint256 constant TransactionSizeMaximum = 800;
// Maximum Merkle Tree Height
uint256 constant MerkleTreeHeightMaximum = 256;
// Select maximum number of transactions that can be included in a Side Chain block
uint256 constant MaxTransactionsInBlock = 2048;
// Ether Token Address (u256 chunk for assembly usage == address(0))
uint256 constant EtherToken = 0;
// Genesis Block Height
uint256 constant GenesisBlockHeight = 0;
// 4 i.e. (1) Input / (2) Output / (3) Witness Selection / (4) Metadata Selection
uint256 constant SelectionStackOffsetSize = 4;
// Topic Hashes
uint256 constant WithdrawalEventTopic = 0x782748bc04673eff1ae34a02239afa5a53a83abdfa31d65d7eea2684c4b31fe4;
uint256 constant FraudEventTopic = 0x62a5229d18b497dceab57b82a66fb912a8139b88c6b7979ad25772dc9d28ddbd;
// ASSEMBLY ONLY ENUMS
// Method Enums
uint256 constant Not_Finalized = 0;
uint256 constant Is_Finalized = 1;
uint256 constant Include_UTXOProofs = 1;
uint256 constant No_UTXOProofs = 0;
uint256 constant FirstProof = 0;
uint256 constant SecondProof = 1;
uint256 constant OneProof = 1;
uint256 constant TwoProofs = 2;
// Input Types Enums
uint256 constant InputType_UTXO = 0;
uint256 constant InputType_Deposit = 1;
uint256 constant InputType_HTLC = 2;
uint256 constant InputType_Change = 3;
// Input Sizes
uint256 constant InputSizes_UTXO = 33;
uint256 constant InputSizes_Change = 33;
uint256 constant InputSizes_Deposit = 33;
uint256 constant InputSizes_HTLC = 65;
// Output Types Enums
uint256 constant OutputType_UTXO = 0;
uint256 constant OutputType_withdrawal = 1;
uint256 constant OutputType_HTLC = 2;
uint256 constant OutputType_Change = 3;
// ASSEMBLY ONLY MEMORY STACK POSITIONS
uint256 constant Stack_InputsSum = 0;
uint256 constant Stack_OutputsSum = 1;
uint256 constant Stack_Metadata = 2;
uint256 constant Stack_BlockTip = 3;
uint256 constant Stack_UTXOProofs = 4;
uint256 constant Stack_TransactionHashID = 5;
uint256 constant Stack_BlockHeader = 6;
uint256 constant Stack_RootHeader = 19;
uint256 constant Stack_SelectionOffset = 7;
uint256 constant Stack_Index = 28;
uint256 constant Stack_SummingTokenID = 29;
uint256 constant Stack_SummingToken = 30;
// Selection Stack Positions (Comparison Proof Selections)
uint256 constant Stack_MetadataSelected = 8;
uint256 constant Stack_SelectedInputLength = 9;
uint256 constant Stack_OutputSelected = 10;
uint256 constant Stack_WitnessSelected = 11;
uint256 constant Stack_MetadataSelected2 = 12;
uint256 constant Stack_SelectedInputLength2 = 13;
uint256 constant Stack_OutputSelected2 = 14;
uint256 constant Stack_WitnessSelected2 = 15;
uint256 constant Stack_RootProducer = 16;
uint256 constant Stack_Witnesses = 17;
uint256 constant Stack_MerkleProofLeftish = 23;
uint256 constant Stack_ProofNumber = 25;
uint256 constant Stack_FreshMemory = 26;
uint256 constant Stack_MetadataLength = 31;
// Storage Positions (based on Solidity compilation)
uint256 constant Storage_deposits = 0;
uint256 constant Storage_withdrawals = 1;
uint256 constant Storage_blockTransactionRoots = 2;
uint256 constant Storage_blockCommitments = 3;
uint256 constant Storage_tokens = 4;
uint256 constant Storage_numTokens = 5;
uint256 constant Storage_blockTip = 6;
uint256 constant Storage_blockProducer = 7;
}
contract Fuel is FuelConstants, DSMath {
// EVENTS
event DepositMade(address indexed account, address indexed token, uint256 amount);
event WithdrawalMade(address indexed account, address token, uint256 amount, uint256 indexed blockHeight, uint256 transactionRootIndex, bytes32 indexed transactionLeafHash, uint8 outputIndex, bytes32 transactionHashId);
event TransactionsSubmitted(bytes32 indexed transactionRoot, address producer, bytes32 indexed merkleTreeRoot, bytes32 indexed commitmentHash);
event BlockCommitted(address blockProducer, bytes32 indexed previousBlockHash, uint256 indexed blockHeight, bytes32[] transactionRoots);
event FraudCommitted(uint256 indexed previousTip, uint256 indexed currentTip, uint256 indexed fraudCode);
event TokenIndex(address indexed token, uint256 indexed index);
// STATE STORAGE
// depositHashID => amount [later clearable in deposit] sload(keccak256(0, 64) + 5)
mapping(bytes32 => uint256) public deposits; // STORAGE 0
// block height => withdrawal id => bool(has been withdrawn) [later clearable in withdraw]
// lets treat block withdrawals as tx hash bytes(0) output (0)
mapping(uint256 => mapping(bytes32 => bool)) public withdrawals; // STORAGE 1
// transactions hash => Ethereum block number included [later clearable in withdraw]
mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2
// blockNumber => blockHash all block commitment hash headers Mapping actually better than array IMO, use tip as len
mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3
// tokens address => token ID number
mapping(address => uint256) public tokens; // STORAGE 4
// number of tokens (1 for Ether ID 0)
uint256 public numTokens = 1; // STORAGE 5
// the current side-chain block height/tip [changed in commitBlock / submitFraudProof]
uint256 public blockTip; // STORAGE 6
// block producer (set to zero for permissionless, must be account) [changed in constructor / submitFraudProof]
address public blockProducer; // STORAGE 7
// CONSTRUCTOR
constructor(address producer) public {
// compute genesis block hash
address genesisProducer = address(0);
// TODO low-priority set a clever previous block hash
bytes32 previousBlockHash = bytes32(0);
uint256 blockHeight = uint256(0);
bytes32[] memory transactionRoots;
bytes32 genesisBlockHash = keccak256(abi.encode(genesisProducer, previousBlockHash, blockHeight, GenesisBlockHeight, transactionRoots));
// STORAGE commit the genesis block hash header to storage as Zero block..
blockCommitments[GenesisBlockHeight] = genesisBlockHash;
// STORAGE setup block producer
blockProducer = producer;
// Setup Ether token index
emit TokenIndex(address(0), 1);
// LOG emit all pertinent details of the Genesis block
emit BlockCommitted(genesisProducer, previousBlockHash, blockHeight, transactionRoots);
}
// STATE Changing Methods
function deposit(address account, address token, uint256 amount) external payable {
// Compute deposit hash Identifier
bytes32 depositHashId = keccak256(abi.encode(account, token, block.number));
// Assert amount is greater than Zero
assert(amount > 0);
// Handle transfer details
if (token != address(0)) {
assert(ERC20(token).allowance(msg.sender, address(this)) >= amount); // check allowance
assert(ERC20(token).transferFrom(msg.sender, address(this), amount)); // transferFrom
} else {
assert(msg.value == amount); // commit ether transfer
}
// register token with an index if it isn't already
if (token != address(0) && tokens[token] == 0) {
// STORAGE register token with index
tokens[token] = numTokens;
// STORAGE MOD increase token index
numTokens = ds_add(numTokens, 1);
// LOG emit token registry index
emit TokenIndex(token, numTokens);
}
// STORAGE notate deposit in storage
deposits[depositHashId] = ds_add(deposits[depositHashId], amount);
// Log essential deposit details
emit DepositMade(account, token, amount);
}
function submitTransactions(bytes32 merkleTreeRoot, bytes calldata transactions) external {
// require the sender is not a contract
assembly {
// Require if caller/msg.sender is a contract
if gt(extcodesize(caller()), 0) { revert(0, 0) }
// Calldata Max size enforcement (4m / 68)
if gt(calldatasize(), MAX_TRANSACTIONS_SIZE) { revert(0, 0) }
}
// Commitment hash
bytes32 commitmentHash = keccak256(transactions);
// Construct Transaction Root Hash
bytes32 transactionRoot = keccak256(abi.encode(msg.sender, merkleTreeRoot, commitmentHash));
// Assert this transactions blob cannot already exist
assert(blockTransactionRoots[transactionRoot] == 0);
// STORAGE notate transaction root in storage at a specified Ethereum block
blockTransactionRoots[transactionRoot] = block.number;
// LOG Transaction submitted, the original data
emit TransactionsSubmitted(transactionRoot, msg.sender, merkleTreeRoot, commitmentHash);
}
function commitBlock(uint256 blockHeight, bytes32[] calldata transactionRoots) external payable {
bytes32 previousBlockHash = blockCommitments[blockTip];
bytes32 blockHash = keccak256(abi.encode(msg.sender, previousBlockHash, blockHeight, block.number, transactionRoots));
// Assert require value be bond size
assert(msg.value == BOND_SIZE);
// Assert at least one root submission
assert(transactionRoots.length > 0);
// Assert at least one root submission
assert(transactionRoots.length < TRANSACTION_ROOTS_MAX);
// Assert the transaction roots exists
for (uint256 transactionRootIndex = 0;
transactionRootIndex < transactionRoots.length;
transactionRootIndex = ds_add(transactionRootIndex, 1)) {
// Transaction Root must Exist in State
assert(blockTransactionRoots[transactionRoots[transactionRootIndex]] > 0);
// add root expiry here..
// Assert transaction root is younger than 3 days, and block producer set, than only block producer can make the block
if (block.number < ds_add(blockTransactionRoots[transactionRoots[transactionRootIndex]], SUBMISSION_DELAY) && blockProducer != address(0)) {
assert(msg.sender == blockProducer);
}
}
// Require block height must be 1 ahead of tip REVERT nicely (be forgiving)
require(blockHeight == ds_add(blockTip, 1));
// STORAGE write block hash commitment to storage
blockCommitments[blockHeight] = blockHash;
// STORAGE set new block tip
blockTip = blockHeight;
// LOG emit all pertinant details in Log Data
emit BlockCommitted(msg.sender, previousBlockHash, blockHeight, transactionRoots);
}
// Submit Fraud or withdrawal proofs (i.e. Implied Consensus Rule Enforcement)
function submitProof(bytes calldata) external payable {
assembly {
// Assign all calldata into free memory, remove 4 byte signature and 64 bytes size/length data (68 bytes)
// Note, We only write data to memory once, than reuse it for almost every function for better computational efficiency
calldatacopy(Calldata_MemoryPosition, 68, calldatasize())
// Assign fresh memory pointer to Virtual Stack
mpush(Stack_FreshMemory, add3(Calldata_MemoryPosition, calldatasize(), mul32(2)))
// Handle Proof Type
switch selectProofType()
case 0 { // ProofType_MalformedBlock
verifyBlockProof()
}
case 1 { // ProofType_MalformedTransaction
// Check proof lengths for overflow
verifyTransactionProofLengths(OneProof)
// Verify Malformed Transaction Proof
verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized)
}
case 2 { // ProofType_InvalidTransaction
// Check proof lengths for overflow
verifyTransactionProofLengths(OneProof)
// Check for Invalid Transaction Sum Amount Totals
// Check for HTLC Data Construction / Witness Signature Specification
verifyTransactionProof(FirstProof, Include_UTXOProofs, Not_Finalized)
}
case 3 { // ProofType_InvalidTransactionInput
// Check proof lengths for overflow
verifyTransactionProofLengths(TwoProofs)
// Check for Invalid UTXO Reference (i.e. Reference a UTXO that does not exist or is Invalid!)
verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Fraud Tx
verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx
// Select Input Type
let firstInputType := selectInputType(selectInputSelected(FirstProof))
// Assert fraud input is not a Deposit Type (deposits are checked in verifyTransactionProof)
assertOrInvalidProof(iszero(eq(firstInputType, InputType_Deposit)),
ErrorCode_InvalidTypeDeposit)
// Fraud Tx 0 Proof: Block Height, Root Index, Tx Index Selected by Metadata
let firstMetadataBlockHeight, firstMetadataTransactionRootIndex,
firstMetadataTransactionIndex, firstMetadataOutputIndex := selectMetadata(
selectMetadataSelected(FirstProof))
// Ensure block heights are the same Metadata Block Height = Second Proof Block Height
assertOrInvalidProof(eq(firstMetadataBlockHeight,
selectBlockHeight(selectBlockHeader(SecondProof))),
ErrorCode_InvalidBlockHeightReference)
// Check transaction root index overflow Metadata Roots Index < Second Proof Block Roots Length
assertOrFraud(lt(firstMetadataTransactionRootIndex,
selectTransactionRootsLength(selectBlockHeader(SecondProof))),
FraudCode_InvalidTransactionRootIndexOverflow)
// Check transaction roots
assertOrInvalidProof(eq(firstMetadataTransactionRootIndex,
selectTransactionRootIndex(selectTransactionRoot(SecondProof))),
ErrorCode_InvalidTransactionRootReference)
// Check transaction index overflow
// Second Proof is Leftish (false if Rightmost Leaf in Merkle Tree!)
let secondProofIsLeftish := mstack(Stack_MerkleProofLeftish)
// Enforce transactionIndexOverflow
assertOrFraud(or(
secondProofIsLeftish,
lte(firstMetadataTransactionIndex, selectTransactionIndex(selectTransactionData(SecondProof))) // Or is most right!
), FraudCode_TransactionIndexOverflow)
// Check transaction index
assertOrInvalidProof(eq(firstMetadataTransactionIndex,
selectTransactionIndex(selectTransactionData(SecondProof))),
ErrorCode_InvalidTransactionIndexReference)
// Check that second transaction isn't empty
assertOrFraud(gt(constructTransactionLeafHash(selectTransactionData(SecondProof)), 0),
FraudCode_TransactionHashZero)
// Select Lengths and Use Them as Indexes (let Index = Length; lt; Index--)
let transactionLeafData, inputsLength,
secondOutputsLength, witnessesLength := selectAndVerifyTransactionDetails(selectTransactionData(SecondProof))
// Check output selection overflow
assertOrFraud(lt(firstMetadataOutputIndex, secondOutputsLength),
FraudCode_MetadataOutputIndexOverflow)
// Second output index
let secondOutputIndex := selectOutputIndex(selectTransactionData(SecondProof))
// Check outputs are the same
assertOrInvalidProof(eq(firstMetadataOutputIndex, secondOutputIndex),
ErrorCode_InvalidOutputIndexReference)
// Select second output
let secondOutput := selectOutputSelected(SecondProof)
let secondOutputType := selectOutputType(secondOutput)
// Check output is not spending withdrawal
assertOrFraud(iszero(eq(secondOutputType, OutputType_withdrawal)),
FraudCode_InvalidInputWithdrawalSpend)
// Invalid Type Spend
assertOrFraud(eq(firstInputType, secondOutputType),
FraudCode_InvalidTypeReferenceMismatch)
// Construct second transaction hash id
let secondTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof))
// Construct Second UTXO ID Proof
let secondUTXOProof := constructUTXOProof(secondTransactionHashID,
selectOutputIndex(selectTransactionData(SecondProof)),
selectOutputSelected(SecondProof))
let secondUTXOID := constructUTXOID(secondUTXOProof)
// Select first UTXO ID
let firstUTXOID := selectUTXOID(selectInputSelected(FirstProof))
// Check UTXOs are the same
assertOrFraud(eq(firstUTXOID, secondUTXOID),
FraudCode_InvalidUTXOHashReference)
// Handle Change Input Enforcement
if eq(selectOutputType(secondOutput), OutputType_Change) {
// Output HTLC
let length, amount, ownerAsWitnessIndex,
tokenID := selectAndVerifyOutput(secondOutput, True)
// Return Witness Recovery
// Return Witness Signature
let outputWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)),
ownerAsWitnessIndex)
// Construct Second Transaction Hash ID
let outputTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof))
// Get Witness Signature
let outputWitnessAddress := ecrecoverPacked(outputTransactionHashID,
outputWitnessSignature)
// Spender Witness Recovery
// Select First Proof Witness Index from Input
let unused1, unused2, spenderWitnessIndex := selectAndVerifyInputUTXO(selectInputSelected(FirstProof),
TransactionLengthMax)
// Spender Witness Signature
let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)),
spenderWitnessIndex)
// Construct First Tx ID
let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof))
// Spender Witness Address
let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID,
spenderWitnessSignature)
// Assert Spender must be Output Witness
assertOrFraud(eq(spenderWitnessAddress, outputWitnessAddress),
FraudCode_InvalidChangeInputSpender)
}
// Handle HTLC Input Enforcement
if eq(selectOutputType(secondOutput), OutputType_HTLC) {
// Output HTLC
let length, amount, owner, tokenID,
digest, expiry, returnWitnessIndex := selectAndVerifyOutputHTLC(secondOutput,
TransactionLengthMax)
// Handle Is HTLC Expired, must be returnWitness
if gte(selectBlockHeight(selectBlockHeader(FirstProof)), expiry) {
// Return Witness Recovery
// Return Witness Signature
let returnWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)),
returnWitnessIndex)
// Construct Second Transaction Hash ID
let returnTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof))
// Get Witness Signature
let returnWitnessAddress := ecrecoverPacked(returnTransactionHashID,
returnWitnessSignature)
// Spender Witness Recovery
// Select First Proof Witness Index from Input
let unused1, unused2, inputWitnessIndex, preImage := selectAndVerifyInputHTLC(selectInputSelected(FirstProof),
TransactionLengthMax)
// Spender Witness Signature
let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)),
inputWitnessIndex)
// Construct First Tx ID
let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof))
// Spender Witness Address
let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID,
spenderWitnessSignature)
// Assert Spender must be Return Witness!
assertOrFraud(eq(spenderWitnessAddress, returnWitnessAddress),
FraudCode_InvalidReturnWitnessNotSpender)
}
}
}
case 4 { // ProofType_InvalidTransactionDoubleSpend
// Check proof lengths for overflow
verifyTransactionProofLengths(TwoProofs)
// Check for Invalid Transaction Double Spend (Same Input Twice)
verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Accused Fraud Tx
verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx
// Get transaction data zero and 1
let transaction0 := selectTransactionData(FirstProof)
let transaction1 := selectTransactionData(SecondProof)
// Block Height Difference
let blockHeightDifference := iszero(eq(selectBlockHeight(selectBlockHeader(FirstProof)),
selectBlockHeight(selectBlockHeader(SecondProof))))
// Transaction Root Difference
let transactionRootIndexDifference := iszero(eq(selectTransactionRootIndex(selectTransactionRoot(FirstProof)),
selectTransactionRootIndex(selectTransactionRoot(SecondProof))))
// Transaction Index Difference
let transactionIndexDifference := iszero(eq(selectTransactionIndex(transaction0),
selectTransactionIndex(transaction1)))
// Transaction Input Index Difference
let transactionInputIndexDifference := iszero(eq(selectInputIndex(transaction0),
selectInputIndex(transaction1)))
// Check that the transactions are different
assertOrInvalidProof(or(
or(blockHeightDifference, transactionRootIndexDifference),
or(transactionIndexDifference, transactionInputIndexDifference) // Input Index is Different
), ErrorCode_InvalidTransactionComparison)
// Assert Inputs are Different OR FRAUD Double Spend!
assertOrFraud(iszero(eq(selectInputSelectedHash(FirstProof),
selectInputSelectedHash(SecondProof))),
FraudCode_InputDoubleSpend)
}
case 5 { // ProofType_UserWithdrawal
// Check proof lengths for overflow
verifyTransactionProofLengths(OneProof)
// Verify transaction proof
verifyTransactionProof(FirstProof, No_UTXOProofs, Is_Finalized)
// Run the withdrawal Sequence
let output := selectOutputSelected(FirstProof)
let length, outputAmount, outputOwner, outputTokenID := selectAndVerifyOutput(output, False)
// Check Proof Type is Correct
assertOrInvalidProof(eq(selectOutputType(output), 1), ErrorCode_InvalidWithdrawalOutputType)
// Check Proof Type is Correct
assertOrInvalidProof(eq(outputOwner, caller()), ErrorCode_InvalidWithdrawalOwner)
// Get transaction details
let transactionRootIndex := selectTransactionRootIndex(selectTransactionRoot(FirstProof))
let transactionLeafHash := constructTransactionLeafHash(selectTransactionData(FirstProof))
let outputIndex := selectOutputIndex(selectTransactionData(FirstProof))
let blockHeight := selectBlockHeight(selectBlockHeader(FirstProof))
// Construct withdrawal hash id
let withdrawalHashID := constructWithdrawalHashID(transactionRootIndex,
transactionLeafHash, outputIndex)
// This output has not been withdrawn yet!
assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False),
ErrorCode_WithdrawalAlreadyHappened)
// withdrawal Token
let withdrawalToken := selectWithdrawalToken(FirstProof)
// Transfer amount out
transfer(outputAmount, outputTokenID, withdrawalToken, outputOwner)
// Set withdrawals
setWithdrawals(blockHeight, withdrawalHashID, True)
// Construct Log Data for withdrawal
mstore(mul32(1), withdrawalToken)
mstore(mul32(2), outputAmount)
mstore(mul32(3), transactionRootIndex)
mstore(mul32(4), outputIndex)
mstore(mul32(5), constructTransactionHashID(selectTransactionData(FirstProof)))
// add transactionHash
// Log withdrawal data and topics
log4(mul32(1), mul32(5), WithdrawalEventTopic, outputOwner,
blockHeight, transactionLeafHash)
}
case 6 { // ProofType_BondWithdrawal
// Select proof block header
let blockHeader := selectBlockHeader(FirstProof)
// Setup block producer withdrawal hash ID (i.e. Zero)
let withdrawalHashID := 0
// Transaction Leaf Hash (bond withdrawal hash is zero)
let transactionLeafHash := 0
// Block Producer
let blockProducer := caller()
// block height
let blockHeight := selectBlockHeight(blockHeader)
// Verify block header proof is finalized!
verifyBlockHeader(blockHeader, Is_Finalized)
// Assert Caller is Block Producer
assertOrInvalidProof(eq(selectBlockProducer(blockHeader), blockProducer),
ErrorCode_BlockProducerNotCaller)
// Assert Block Bond withdrawal has not been Made!
assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False),
ErrorCode_BlockBondAlreadyWithdrawn)
// Transfer Bond Amount back to Block Producer
transfer(BOND_SIZE, EtherToken, EtherToken, blockProducer)
// Set withdrawal
setWithdrawals(blockHeight, withdrawalHashID, True)
// Construct Log Data for withdrawal
mstore(mul32(1), EtherToken)
mstore(mul32(2), BOND_SIZE)
mstore(mul32(3), 0)
mstore(mul32(4), 0)
// Log withdrawal data and topics
log4(mul32(1), mul32(4), WithdrawalEventTopic, blockProducer,
blockHeight,
transactionLeafHash)
}
// Invalid Proof Type
default { assertOrInvalidProof(0, ErrorCode_InvalidProofType) }
// Ensure Execution Stop
stop()
//
// VERIFICATION METHODS
// For verifying proof data and determine fraud or validate withdrawals
//
// Verify Invalid Block Proof
function verifyBlockProof() {
/*
Block Construction Proof:
- Type
- Lengths
- BlockHeader
- TransactionRootHeader
- TransactionRootData
*/
// Start Proof Position past Proof Type
let proofMemoryPosition := safeAdd(Calldata_MemoryPosition, mul32(1))
// Select Proof Lengths
let blockHeaderLength := load32(proofMemoryPosition, 0)
let transactionRootLength := load32(proofMemoryPosition, 1)
let transactionsLength := load32(proofMemoryPosition, 2)
// Verify the Lengths add up to calldata size
verifyProofLength(add4(mul32(3), blockHeaderLength,
transactionRootLength, transactionsLength))
// Select Proof Memory Positions
let blockHeader := selectBlockHeader(FirstProof)
let transactionRoot := selectTransactionRoot(FirstProof)
// Transactions are After Transaction Root, Plus 64 Bytes (for bytes type metadata from ABI Encoding)
let transactions := safeAdd(transactionRoot, transactionRootLength)
// Verify Block Header
verifyBlockHeader(blockHeader, Not_Finalized)
// Verify Transaction Root Header
verifyTransactionRootHeader(blockHeader, transactionRoot)
// Get solidity abi encoded length for transactions blob
let transactionABILength := selectTransactionABILength(transactions)
// Check for overflow
assertOrInvalidProof(lt(transactionABILength, transactionsLength),
ErrorCode_InvalidTransactionsABILengthOverflow)
// Verify Transaction Hash Commitment
verifyTransactionRootData(transactionRoot,
selectTransactionABIData(transactions),
transactionABILength)
}
// Verify proof length for overflows
function verifyProofLength(proofLengthWithoutType) {
let calldataMetadataSize := 68
let typeSize := mul32(1)
let computedCalldataSize := add3(calldataMetadataSize, typeSize, proofLengthWithoutType)
// Check for overflow
assertOrInvalidProof(eq(computedCalldataSize, calldatasize()),
ErrorCode_ProofLengthOverflow)
}
// Verify Block Header
function verifyBlockHeader(blockHeader, assertFinalized) {
/*
- Block Header:
- blockProducer [32 bytes] -- padded address
- previousBlockHash [32 bytes]
- blockHeight [32 bytes]
- ethereumBlockNumber [32 bytes]
- transactionRoots [64 + dynamic bytes]
*/
// Construct blockHash from Block Header
let blockHash := constructBlockHash(blockHeader)
// Select BlockHeight from Memory
let blockHeight := selectBlockHeight(blockHeader)
// Previous block hash
let previousBlockHash := selectPreviousBlockHash(blockHeader)
// Transaction Roots Length
let transactionRootsLength := selectTransactionRootsLength(blockHeader)
// Assert Block is not Genesis
assertOrInvalidProof(gt(blockHeight, GenesisBlockHeight), ErrorCode_BlockHeightUnderflow)
// Assert Block Height is Valid (i.e. before tip)
assertOrInvalidProof(lte(blockHeight, getBlockTip()), ErrorCode_BlockHeightOverflow)
// Assert Previous Block Hash
assertOrInvalidProof(eq(getBlockCommitments(safeSub(blockHeight, 1)), previousBlockHash), ErrorCode_InvalidPreviousBlockHash)
// Transactions roots length underflow
assertOrInvalidProof(gt(transactionRootsLength, 0), ErrorCode_TransactionRootsLengthUnderflow)
// Assert Block Commitment Exists
assertOrInvalidProof(eq(getBlockCommitments(blockHeight), blockHash), ErrorCode_BlockHashNotFound)
// If requested, Assert Block is Finalized
if eq(assertFinalized, 1) {
assertOrInvalidProof(gte(
number(),
safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // ethBlock + delay
), ErrorCode_BlockNotFinalized)
}
// If requested, Assert Block is Not Finalized
if iszero(assertFinalized) { // underflow protected!
assertOrInvalidProof(lt(
number(), // ethereumBlockNumber
safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // finalization delay
), ErrorCode_BlockFinalized)
}
}
// Verify Transaction Root Header (Assume Block Header is Valid)
function verifyTransactionRootHeader(blockHeader, transactionRoot) {
/*
- Block Header:
- blockProducer [32 bytes] -- padded address
- previousBlockHash [32 bytes]
- blockHeight [32 bytes]
- ethereumBlockNumber [32 bytes]
- transactionRoots [64 + dynamic bytes]
- Transaction Root Header:
- transactionRootProducer [32 bytes] -- padded address
- transactionRootMerkleTreeRoot [32 bytes]
- transactionRootCommitmentHash [32 bytes]
- transactionRootIndex [32 bytes]
*/
// Get number of transaction roots
let transactionRootsLength := selectTransactionRootsLength(blockHeader)
// Get transaction root index
let transactionRootIndex := selectTransactionRootIndex(transactionRoot)
// Assert root index is not overflowing
assertOrInvalidProof(lt(transactionRootIndex, transactionRootsLength), ErrorCode_TransactionRootIndexOverflow)
// Assert root invalid overflow
assertOrInvalidProof(lt(transactionRootsLength, TRANSACTION_ROOTS_MAX), ErrorCode_TransactionRootsLengthOverflow)
// Construct transaction root
let transactionRootHash := keccak256(transactionRoot, mul32(3))
// Assert transaction root index is correct!
assertOrInvalidProof(eq(
transactionRootHash,
load32(blockHeader, safeAdd(6, transactionRootIndex)) // blockHeader transaction root
), ErrorCode_TransactionRootHashNotInBlockHeader)
}
// Construct commitment hash
function constructCommitmentHash(transactions, transactionsLength) -> commitmentHash {
commitmentHash := keccak256(transactions, transactionsLength)
}
function selectTransactionABIData(transactionsABIEncoded) -> transactions {
transactions := safeAdd(transactionsABIEncoded, mul32(2))
}
function selectTransactionABILength(transactionsABIEncoded) -> transactionsLength {
transactionsLength := load32(transactionsABIEncoded, 1)
}
// Verify Transaction Root Data is Valid (Assuming Transaction Root Valid)
function verifyTransactionRootData(transactionRoot, transactions, transactionsLength) {
// Select Transaction Data Root
let commitmentHash := selectCommitmentHash(transactionRoot)
// Check provided transactions data! THIS HASH POSITION MIGHT BE WRONG due to Keccak Encoding
let constructedCommitmentHash := constructCommitmentHash(transactions, transactionsLength)
// Assert or Invalid Data Provided
assertOrInvalidProof(eq(
commitmentHash,
constructedCommitmentHash
), ErrorCode_TransactionRootHashInvalid)
// Select Merkle Tree Root Provided
let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot)
// Assert committed root must be the same as computed root! // THIS HASH MIGHT BE WRONG (hash POS check)
assertOrFraud(eq(
merkleTreeRoot,
constructMerkleTreeRoot(transactions, transactionsLength)
), FraudCode_InvalidMerkleTreeRoot)
}
// Verify Transaction Proof
function verifyTransactionProof(proofIndex, includeUTXOProofs, assertFinalized) {
/*
Transaction Proof:
- Lengths
- BlockHeader
- TransactionRootHeader
- TransactionMerkleProof
- TransactionData
- TransactionUTXOProofs
*/
// we are on proof 1
if gt(proofIndex, 0) {
// Notate across global stack we are on proof 1 validation
mpush(Stack_ProofNumber, proofIndex)
}
// Select Memory Positions
let blockHeader := selectBlockHeader(proofIndex)
let transactionRoot := selectTransactionRoot(proofIndex)
let transactionMerkleProof := selectTransactionMerkleProof(proofIndex)
let transactionData := selectTransactionData(proofIndex)
// Verify Block Header
verifyBlockHeader(blockHeader, assertFinalized)
// Verify Transaction Root Header
verifyTransactionRootHeader(blockHeader, transactionRoot)
// Verify Transaction Leaf
verifyTransactionLeaf(transactionRoot, transactionData, transactionMerkleProof)
// Construct Transaction Leaf Hash (Again :(
let transactionLeafHash := constructTransactionLeafHash(transactionData)
// If transaction hash is not zero hash, than go and verify it!
if gt(transactionLeafHash, 0) {
// Transaction UTXO Proofs
let transactionUTXOProofs := 0
// Include UTXO Proofs
if gt(includeUTXOProofs, 0) {
transactionUTXOProofs := selectTransactionUTXOProofs(proofIndex)
}
// Verify Transaction Data
verifyTransactionData(transactionData, transactionUTXOProofs)
}
// Ensure We are now validating proof 0 again
mpop(Stack_ProofNumber)
}
// Verify Transaction Leaf (Assume Transaction Root Header is Valid)
function verifyTransactionLeaf(transactionRoot, transactionData, merkleProof) {
/*
- Transaction Root Header:
- transactionRootProducer [32 bytes] -- padded address
- transactionRootMerkleTreeRoot [32 bytes]
- transactionRootCommitmentHash [32 bytes]
- transactionRootIndex [32 bytes]
- Transaction Data:
- input index [32 bytes] -- padded uint8
- output index [32 bytes] -- padded uint8
- witness index [32 bytes] -- padded uint8
- transactionInputsLength [32 bytes] -- padded uint8
- transactionIndex [32 bytes] -- padded uint32
- transactionLeafData [dynamic bytes]
- Transaction Merkle Proof:
- oppositeTransactionLeaf [32 bytes]
- merkleProof [64 + dynamic bytes]
*/
// Select Merkle Tree Root
let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot)
// Select Merkle Proof Height
let treeHeight := selectMerkleTreeHeight(merkleProof)
// Select Tree (ahead of Array length)
let treeMemoryPosition := selectMerkleTree(merkleProof)
// Select Transaction Index
let transactionIndex := selectTransactionIndex(transactionData)
// Assert Valid Merkle Tree Height (i.e. below Maximum)
assertOrInvalidProof(lt(treeHeight, MerkleTreeHeightMaximum),
ErrorCode_MerkleTreeHeightOverflow)
// Select computed hash, initialize with opposite leaf hash
let computedHash := selectOppositeTransactionLeaf(merkleProof)
// Assert Leaf Hash is base of Merkle Proof
assertOrInvalidProof(eq(
constructTransactionLeafHash(transactionData), // constructed
computedHash // proof provided
), ErrorCode_TransactionLeafHashInvalid)
// Clean Rightmost (leftishness) Detection Var (i.e. any previous use of this Stack Position)
mpop(Stack_MerkleProofLeftish)
// Iterate Through Merkle Proof Depths
// https://crypto.stackexchange.com/questions/31871/what-is-the-canonical-way-of-creating-merkle-tree-branches
for { let depth := 0 } lt(depth, treeHeight) { depth := safeAdd(depth, 1) } {
// get the leaf hash
let proofLeafHash := load32(treeMemoryPosition, depth)
// Determine Proof Direction the merkle brand left: tx index % 2 == 0
switch eq(smod(transactionIndex, 2), 0)
// Direction is left branch
case 1 {
mstore(mul32(1), computedHash)
mstore(mul32(2), proofLeafHash)
// Leftishness Detected in Proof, This is not Rightmost
mpush(Stack_MerkleProofLeftish, True)
}
// Direction is right branch
case 0 {
mstore(mul32(1), proofLeafHash)
mstore(mul32(2), computedHash)
}
default { revert(0, 0) } // Direction is Invalid, Ensure no other cases!
// Construct Depth Hash
computedHash := keccak256(mul32(1), mul32(2))
// Shift transaction index right by 1
transactionIndex := shr(1, transactionIndex)
}
// Assert constructed merkle tree root is provided merkle tree root, or else, Invalid Inclusion!
assertOrInvalidProof(eq(computedHash, merkleTreeRoot), ErrorCode_MerkleTreeRootInvalid)
}
// Verify Transaction Input Metadata
function verifyTransactionInputMetadata(blockHeader, rootHeader, metadata, blockTip, inputIndex) {
// Block Height
let metadataBlockHeight, metadataTransactionRootIndex,
metadataTransactionIndex, metadataOutputIndex := selectMetadata(metadata)
// Select Transaction Block Height
let blockHeight := selectBlockHeight(blockHeader)
let transactionRootIndex := selectTransactionRootIndex(rootHeader)
// Assert input index overflow (i.e. metadata does not exist)
assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)),
FraudCode_MetadataReferenceOverflow)
// Assert Valid Metadata Block height
assertOrFraud(gt(metadataBlockHeight, 0), FraudCode_MetadataBlockHeightUnderflow)
// Assert Valid Metadata Block height
assertOrFraud(lt(metadataTransactionRootIndex, TRANSACTION_ROOTS_MAX),
FraudCode_InvalidTransactionRootIndexOverflow)
// Cannot spend past it's own root index (i.e. tx 1 cant spend tx 2 at root index + 1)
// Can't be past block tip or past it's own block (can't reference the future)
assertOrFraud(lte(metadataBlockHeight, blockTip),
FraudCode_MetadataBlockHeightOverflow)
// Check overflow of current block height
assertOrFraud(lte(metadataBlockHeight, blockHeight),
FraudCode_MetadataBlockHeightOverflow)
// Can't reference in the future!!
// If Meta is Ref. Block Height of Itself, and Ref. Root Index > Itself, that's Fraud!
assertOrFraud(or(iszero(eq(metadataBlockHeight, blockHeight)), // block height is different
lte(metadataTransactionRootIndex, transactionRootIndex)), // metadata root index <= self root index
FraudCode_InvalidTransactionRootIndexOverflow)
// Need to cover referencing a transaction index in the same block, but past this tx
// txs must always reference txs behind it, or else it's fraud
// Check Output Index
assertOrFraud(lt(metadataOutputIndex, TransactionLengthMax),
FraudCode_MetadataOutputIndexOverflow)
}
// Verify HTLC Usage
function verifyHTLCData(blockHeader, input, utxoProof) {
/*
- Transaction UTXO Data:
- transactionHashId [32 bytes]
- outputIndex [32 bytes] -- padded uint8
- type [32 bytes] -- padded uint8
- amount [32 bytes]
- owner [32 bytes] -- padded address or unit8
- tokenID [32 bytes] -- padded uint32
- [HTLC Data]:
- digest [32 bytes]
- expiry [32 bytes] -- padded 4 bytes
- return witness index [32 bytes] -- padded 1 bytes
*/
// Select Transaction Input data
let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC(input,
TransactionLengthMax)
// Select Transaction Block Height
let blockHeight := selectBlockHeight(blockHeader)
// Select Digest and Expiry from UTXO Proof (Assumed to be Valid)
let digest := load32(utxoProof, 6)
let expiry := load32(utxoProof, 7)
// If not expired, and digest correct, expired case gets handled in Comparison proofs
if lt(blockHeight, expiry) {
// Assert Digest is Valid
assertOrFraud(eq(digest, constructHTLCDigest(preImage)),
FraudCode_InvalidHTLCDigest)
}
}
// Verify Transaction Length (minimum and maximum)
function verifyTransactionLength(transactionLength) {
// Assert transaction length is not too short
assertOrFraud(gt(transactionLength, TransactionSizeMinimum),
FraudCode_TransactionLengthUnderflow)
// Assert transaction length is not too long
assertOrFraud(lte(transactionLength, TransactionSizeMaximum),
FraudCode_TransactionLengthOverflow)
}
// Verify Transaction Data (Metadata, Inputs, Outputs, Witnesses)
function verifyTransactionData(transactionData, utxoProofs) {
// Verify Transaction Length
verifyTransactionLength(selectTransactionLength(transactionData))
// Select and Verify Lengths and Use Them as Indexes (let Index = Length; lt; Index--)
let memoryPosition, inputsLength,
outputsLength, witnessesLength := selectAndVerifyTransactionDetails(transactionData)
// Memory Stack so we don't blow the stack!
mpush(Stack_InputsSum, 0) // Total Transaction Input Sum
mpush(Stack_OutputsSum, 0) // Total Transaction Output Sum
mpush(Stack_Metadata, selectTransactionMetadata(transactionData)) // Metadata Memory Position
mpush(Stack_Witnesses, selectTransactionWitnesses(transactionData)) // Witnesses Memory Position
mpush(Stack_BlockTip, getBlockTip()) // GET blockTip() from Storage
mpush(Stack_UTXOProofs, safeAdd(utxoProofs, mul32(1))) // UTXO Proofs Memory Position
mpush(Stack_TransactionHashID, constructTransactionHashID(transactionData)) // Construct Transaction Hash ID
mpush(Stack_MetadataLength, selectTransactionMetadataLength(transactionData))
// Push summing tokens
if gt(utxoProofs, 0) {
mpush(Stack_SummingToken, mload(utxoProofs)) // load summing token
mpush(Stack_SummingTokenID, getTokens(mload(utxoProofs))) // load summing token
}
// Set Block Header Position (on First Proof)
if iszero(mstack(Stack_ProofNumber)) {
// Proof 0 Block Header Position
mpush(Stack_BlockHeader, selectBlockHeader(FirstProof))
// Proof 0 Block Header Position
mpush(Stack_RootHeader, selectTransactionRoot(FirstProof))
// Return Stack Offset: (No Offset) First Transaction
mpush(Stack_SelectionOffset, 0)
// Proof 0 Transaction Root Producer
mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(FirstProof)))
}
// If Second Transaction Processed, Set Block Header Position (On Second Proof)
if gt(mstack(Stack_ProofNumber), 0) {
// Proof 1 Block Header Position
mpush(Stack_BlockHeader, selectBlockHeader(SecondProof))
// Proof 0 Block Header Position
mpush(Stack_RootHeader, selectTransactionRoot(SecondProof))
// Return Stack Offset: Offset Memory Stack for Second Proof
mpush(Stack_SelectionOffset, SelectionStackOffsetSize) // 4 => Metadata, Input, Output, Witness Position
// Proof 1 Transaction Root Position
mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(SecondProof)))
}
// Increase memory position past length Specifiers
memoryPosition := safeAdd(memoryPosition, TransactionLengthSize)
// Transaction Proof Stack Return
// 8) Metadata Tx 1, 9) Input Tx 1, 10) Output, 11) Witness Memory Position
// 12) Metadata Tx 2, 13) Input Tx 2, 14) Output, 15) Witness Memory Position
// VALIDATE Inputs Index from Inputs Length -> 0
for { mpush(Stack_Index, 0) }
lt(mstack(Stack_Index), inputsLength)
{ mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } {
// Check if This is Input Requested
if eq(mstack(Stack_Index), selectInputSelectionIndex(transactionData)) {
// Store Metadata Position in Stack
mpush(safeAdd(Stack_MetadataSelected, mstack(Stack_SelectionOffset)),
combineUint32(mstack(Stack_Metadata), memoryPosition, mstack(Stack_Index), 0))
}
// Select Input Type
switch selectInputType(memoryPosition)
case 0 { // InputType UTXO
// Increase Memory pointer
let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition,
witnessesLength)
// If UTXO/Deposit Proofs provided
if gt(utxoProofs, 0) {
let outputAmount, outputOwner,
tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs), 0, utxoID)
// Increase input sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount))
}
// Increase UTXO proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize))
// Verify transaction witness
verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference),
mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer))
}
// cannot select metadata that does not exist
// assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)),
// FraudCode_TransactionInputMetadataOverflow)
// Verify metadata for this input (metadata position, block tip)
verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader),
mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index))
// Increase metadata memory position
mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize))
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
case 1 { // InputType DEPOSIT (verify deposit owner / details witnesses etc)
// Select Input Deposit (Asserts Deposit > 0)
let length, depositHashID,
witnessReference := selectAndVerifyInputDeposit(memoryPosition, witnessesLength)
// If UTXO Proofs provided
if gt(utxoProofs, 0) {
// Owner
let depositOwner := selectInputDepositOwner(mstack(Stack_UTXOProofs))
// Constructed Deposit hash
let constructedDepositHashID := constructDepositHashID(mstack(Stack_UTXOProofs))
// Check Deposit Hash ID against proof
assertOrInvalidProof(eq(depositHashID, constructedDepositHashID),
ErrorCode_InvalidDepositProof)
// Verify transaction witness
verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference),
mstack(Stack_TransactionHashID), depositOwner, mstack(Stack_RootProducer))
// Deposit Token
let depositToken := selectInputDepositToken(mstack(Stack_UTXOProofs))
// Increase Input Amount
if eq(depositToken, mstack(Stack_SummingToken)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), getDeposits(depositHashID)))
}
// Increase UTXO/Deposit proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), DepositProofSize))
}
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// Increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
case 2 { // InputType HTLC
// Select HTLC Input
let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC(
memoryPosition, witnessesLength)
// If UTXO Proofs provided
if gt(utxoProofs, 0) {
let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner(
mstack(Stack_UTXOProofs), 2, utxoID)
// Verify HTLC Data
verifyHTLCData(mstack(Stack_BlockHeader), memoryPosition, mstack(Stack_UTXOProofs))
// Verify transaction witness
verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference),
mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer))
// Increase input sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount))
}
// Increase UTXO proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize))
}
// Verify metadata for this input (metadata position, block tip)
verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader),
mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index))
// Increase metadata memory position
mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize))
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// Increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
case 3 { // InputType CHANGE UNSPENT
// HTLC input
let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition, witnessesLength)
// If UTXO Proofs provided
if gt(utxoProofs, 0) {
let outputAmount, outputOwner,
tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs),
OutputType_Change, utxoID)
// witness signatures get enforced in invalidTransactionInput
// Increase input sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount))
}
// Increase UTXO proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize))
}
// Verify metadata for this input (metadata position, block tip)
verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader),
mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index))
// Increase metadata memory position
mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize))
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// Increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
// Assert fraud Invalid Input Type
default { assertOrFraud(0, FraudCode_InvalidTransactionInputType) }
// Increase Memory Pointer for 1 byte Type
memoryPosition := safeAdd(memoryPosition, TypeSize)
}
// Index from Outputs Length -> 0
for { mpush(Stack_Index, 0) }
lt(mstack(Stack_Index), outputsLength)
{ mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } {
// Check if input is requested
if eq(mstack(Stack_Index), selectOutputSelectionIndex(transactionData)) {
// Store Output Memory Position in Stack
mpush(safeAdd(Stack_OutputSelected, mstack(Stack_SelectionOffset)), memoryPosition)
}
// Select Output Type
switch selectOutputType(memoryPosition)
case 0 { // OutputType UTXO
// Increase Memory pointer
let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
case 1 { // OutputType withdrawal
// Increase Memory pointer
let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
case 2 { // OutputType HTLC
// Increase Memory pointer
let length, amount, owner, tokenID,
digest, expiry, returnWitness := selectAndVerifyOutputHTLC(memoryPosition,
witnessesLength)
// Check expiry is greater than its own block header
assertOrFraud(gt(expiry, selectBlockHeight(mstack(Stack_BlockHeader))),
FraudCode_OutputHTLCExpiryUnderflow)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
case 3 { // OutputType CHANGE UNSPENT
// Increase Memory pointer
let length, amount, witnessReference,
tokenID := selectAndVerifyOutput(memoryPosition, True)
// Invalid Witness Reference out of bounds
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionOutputWitnessReferenceOverflow)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
// Assert fraud Invalid Input Type
default { assertOrFraud(0, FraudCode_InvalidTransactionOutputType) }
// Increase Memory Pointer for 1 byte Type
memoryPosition := safeAdd(memoryPosition, TypeSize)
}
// Assert Transaction Total Output Sum <= Total Input Sum
if gt(utxoProofs, 0) { assertOrFraud(eq(mstack(Stack_OutputsSum), mstack(Stack_InputsSum)),
FraudCode_TransactionSumMismatch) }
// Iterate from Witnesses Length -> 0
for { mpush(Stack_Index, 0) }
lt(mstack(Stack_Index), witnessesLength)
{ mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } {
// check if input is requested
if eq(mstack(Stack_Index), selectWitnessSelectionIndex(transactionData)) {
// Store Witness Memory Position in Stack
mpush(safeAdd(Stack_WitnessSelected, mstack(Stack_SelectionOffset)),
mstack(Stack_Witnesses))
}
// Increase witness memory position
mpush(Stack_Witnesses, safeAdd(mstack(Stack_Witnesses), WitnessSize))
}
// Check Transaction Length for Validity based on Computed Lengths
// Get Leaf Size details
let unsignedTransactionData, metadataSize,
witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData)
// Select Transaction Length
let transactionLength := selectTransactionLength(transactionData)
// Metadata size
let providedDataSize := add3(TransactionLengthSize, metadataSize, witnessesSize)
// We should never hit this, but we will add in the protection anyway..
assertOrFraud(lt(providedDataSize, transactionLength),
FraudCode_ProvidedDataOverflow)
// Memory size difference
let unsignedTransactionLength := safeSub(transactionLength, providedDataSize)
// We should never hit this, but we will add in the protection anyway..
assertOrFraud(lt(unsignedTransactionData, memoryPosition),
FraudCode_ProvidedDataOverflow)
// Computed unsigned transaction length
// Should never underflow
let computedUnsignedTransactionLength := safeSub(memoryPosition, unsignedTransactionData)
// Invalid transaction length
assertOrFraud(eq(unsignedTransactionLength, computedUnsignedTransactionLength),
FraudCode_ComputedTransactionLengthOverflow)
// Pop Memory Stack
mpop(Stack_InputsSum)
mpop(Stack_OutputsSum)
mpop(Stack_Metadata)
mpop(Stack_Witnesses)
mpop(Stack_BlockTip)
mpop(Stack_UTXOProofs)
mpop(Stack_TransactionHashID)
mpop(Stack_MetadataLength)
mpush(Stack_SummingToken, 0) // load summing token
mpush(Stack_SummingTokenID, 0) // load summing token
mpop(Stack_Index)
// We leave Memory Stack 6 for Secondary Transaction Proof Validation
// We don't clear 7 - 15 (those are the returns from transaction processing)
// Warning: CHECK Transaction Leaf Length here for Computed Length!!
}
mpop(Stack_Index)
//
// SELECTOR METHODS
// For selecting, parsing and enforcing side-chain abstractions, rules and data across runtime memory
//
// Select the UTXO ID for an Input
function selectUTXOID(input) -> utxoID {
// Past 1 (input type)
utxoID := mload(safeAdd(input, TypeSize))
}
// Select Metadata
function selectMetadata(metadata) -> blockHeight, transactionRootIndex,
transactionIndex, outputIndex {
blockHeight := slice(metadata, 4)
transactionRootIndex := slice(safeAdd(metadata, 4), IndexSize)
transactionIndex := slice(safeAdd(metadata, 5), 2)
outputIndex := slice(safeAdd(metadata, 7), IndexSize)
}
// Select Metadata Selected (Used after verifyTransactionData)
function selectInputSelectedHash(proofIndex) -> inputHash {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Input Hash Length (Type 1 Byte + Input Length Provided)
let inputHashLength := 0
// Input Memory Position
let input := selectInputSelected(proofIndex)
// Get lenght
switch selectInputType(input)
case 0 {
inputHashLength := 33
}
case 1 {
inputHashLength := 33
}
case 2 {
inputHashLength := 65
}
case 3 {
inputHashLength := 33
}
default { assertOrInvalidProof(0, 0) }
// Set metadata
inputHash := keccak256(input, inputHashLength)
}
// Select Metadata Selected (Used after verifyTransactionData)
function selectMetadataSelected(proofIndex) -> metadata {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Return metadata memory position
let metadataInput, input, unused,
unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset)))
// Set metadata
metadata := metadataInput
}
// Select Input Selected (Used after verifyTransactionData)
function selectInputSelected(proofIndex) -> input {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Get values
let metadata, inputPosition, unused,
unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset)))
// Input position
input := inputPosition
}
// Select Output Selected (Used after verifyTransactionData)
function selectOutputSelected(proofIndex) -> output {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Return metadata memory position
output := mstack(safeAdd(Stack_OutputSelected, offset))
}
// Select Witness Selected (Used after verifyTransactionData)
function selectWitnessSelected(proofIndex) -> witness {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Return metadata memory position
witness := mstack(safeAdd(Stack_WitnessSelected, offset))
}
function selectBlockHeaderLength(transactionProof) -> blockHeaderLength {
blockHeaderLength := load32(transactionProof, 0)
}
function selectTransactionRootLength(transactionProof) -> transactionRootLength {
transactionRootLength := load32(transactionProof, 1)
}
function selectMerkleProofLength(transactionProof) -> merkleProofLength {
merkleProofLength := load32(transactionProof, 2)
}
// Select Transaction Proof Lengths
function selectTransactionProofLengths(transactionProof) ->
lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength {
// Compute Proof Length or Lengths
lengthsLength := mul32(5)
// If malformed block proof
if iszero(selectProofType()) {
lengthsLength := mul32(3)
}
// Select Proof Lengths
blockHeaderLength := load32(transactionProof, 0)
transactionRootHeaderLength := load32(transactionProof, 1)
transactionMerkleLength := load32(transactionProof, 2)
transactionDataLength := load32(transactionProof, 3)
transactionUTXOLength := load32(transactionProof, 4)
}
// Select Transaction Proof Memory Position
function selectTransactionProof(proofIndex) -> transactionProof {
// Increase proof memory position for proof type (32 bytes)
transactionProof := safeAdd(Calldata_MemoryPosition, mul32(1))
// Select second proof instead!
if gt(proofIndex, 0) {
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(transactionProof)
// Secondary position
transactionProof := add4(
transactionProof, lengthsLength, blockHeaderLength,
add4(transactionRootHeaderLength, transactionMerkleLength,
transactionDataLength, transactionUTXOLength))
}
}
// Select Transaction Proof Block Header
function selectBlockHeader(proofIndex) -> blockHeader {
// Select Proof Memory Position
blockHeader := selectTransactionProof(proofIndex)
// If it's not the bond withdrawal
if lt(selectProofType(), 6) {
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(blockHeader)
// Block header (always after lengths)
blockHeader := safeAdd(blockHeader, lengthsLength)
}
}
function selectBlockProducer(blockHeader) -> blockProducer {
blockProducer := load32(blockHeader, 0)
}
function selectBlockHeight(blockHeader) -> blockHeight {
blockHeight := load32(blockHeader, 2)
}
function selectPreviousBlockHash(blockHeader) -> previousBlockHash {
previousBlockHash := load32(blockHeader, 1)
}
function selectTransactionRootsLength(blockHeader) -> transactionRootsLength {
transactionRootsLength := load32(blockHeader, 5)
}
function selectEthereumBlockNumber(blockHeader) -> ethereumBlockNumber {
ethereumBlockNumber := load32(blockHeader, 3)
}
// Select Transaction Root from Proof
function selectTransactionRoot(proofIndex) -> transactionRoot {
// Select Proof Memory Position
let transactionProof := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(transactionProof)
// Select Transaction Root Position
transactionRoot := add3(transactionProof, lengthsLength, blockHeaderLength)
}
// Select Root Producer
function selectRootProducer(transactionRoot) -> rootProducer {
rootProducer := load32(transactionRoot, 0)
}
// Select Merkle Tree Root
function selectMerkleTreeRoot(transactionRoot) -> merkleTreeRoot {
merkleTreeRoot := load32(transactionRoot, 1)
}
// Select commitment hash from root
function selectCommitmentHash(transactionRoot) -> commitmentHash {
commitmentHash := load32(transactionRoot, 2)
}
// Select Transaction Root Index
function selectTransactionRootIndex(transactionRoot) -> transactionRootIndex {
transactionRootIndex := load32(transactionRoot, 3)
}
// Select Transaction Root from Proof
function selectTransactionMerkleProof(proofIndex) -> merkleProof {
// Select Proof Memory Position
merkleProof := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(merkleProof)
// Select Transaction Root Position
merkleProof := add4(merkleProof, lengthsLength,
blockHeaderLength, transactionRootHeaderLength)
}
// Select First Merkle Proof
function selectMerkleTreeBaseLeaf(merkleProof) -> leaf {
leaf := load32(merkleProof, 3)
}
// Select Opposite Transaction Leaf in Merkle Proof
function selectOppositeTransactionLeaf(merkleProof) -> oppositeTransactionLeaf {
oppositeTransactionLeaf := mload(merkleProof)
}
// Select Merkle Tree Height
function selectMerkleTreeHeight(merkleProof) -> merkleTreeHeight {
merkleTreeHeight := load32(merkleProof, 2)
}
// Select Merkle Tree Height
function selectMerkleTree(merkleProof) -> merkleTree {
merkleTree := safeAdd(merkleProof, mul32(3))
}
// Select Transaction Data from Proof
function selectTransactionData(proofIndex) -> transactionData {
// Select Proof Memory Position
let proofMemoryPosition := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition)
// Select Transaction Data Position
transactionData := add4(proofMemoryPosition, lengthsLength,
blockHeaderLength, safeAdd(transactionRootHeaderLength, transactionMerkleLength))
}
function selectTransactionIndex(transactionData) -> transactionIndex {
transactionIndex := load32(transactionData, 3)
}
function selectInputIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 0)
}
function selectOutputIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 1)
}
function selectWitnessIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 2)
}
// Verify Transaction Lengths
function verifyTransactionProofLengths(proofCount) {
// Total Proof Length
let proofLengthWithoutType := 0
// Iterate and Compute Maximum length
for { let proofIndex := 0 }
and(lt(proofIndex, 2), lt(proofIndex, proofCount))
{ proofIndex := safeAdd(proofIndex, 1) } {
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(selectTransactionProof(proofIndex))
// Add total proof length
proofLengthWithoutType := add4(add4(proofLengthWithoutType,
lengthsLength,
blockHeaderLength,
transactionRootHeaderLength),
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength)
}
// Verify Proof Length Overflow
verifyProofLength(proofLengthWithoutType)
}
// Select Transaction Data from Proof
function selectTransactionUTXOProofs(proofIndex) -> utxoProofs {
// Select Proof Memory Position
let proofMemoryPosition := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition)
// Select Transaction Data Position
utxoProofs := safeAdd(selectTransactionData(proofIndex), transactionDataLength)
}
function selectWithdrawalToken(proofIndex) -> withdrawalToken {
withdrawalToken := load32(selectTransactionUTXOProofs(proofIndex), 0)
}
// select proof type
function selectProofType() -> proofType {
proofType := load32(Calldata_MemoryPosition, 0) // 32 byte chunk
}
// Select input
function selectInputType(input) -> result {
result := slice(input, 1) // [1 bytes]
}
// Select utxoID (length includes type)
function selectAndVerifyInputUTXO(input, witnessesLength) -> length, utxoID, witnessReference {
utxoID := mload(safeAdd(1, input))
witnessReference := slice(add3(TypeSize, 32, input), IndexSize)
length := 33 // UTXO + Witness Reference
// Assert Witness Index is Valid
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionInputWitnessReferenceOverflow)
}
// Select Input Deposit Proof
function selectInputDepositOwner(depositProof) -> owner {
// Load owner
owner := load32(depositProof, 0)
}
// Select Input Deposit Proof
function selectInputDepositToken(depositProof) -> token {
// Load owner
token := load32(depositProof, 1)
}
// Select deposit information (length includes type)
function selectAndVerifyInputDeposit(input, witnessesLength) -> length,
depositHashID, witnessReference {
depositHashID := mload(safeAdd(input, TypeSize))
witnessReference := slice(add3(input, TypeSize, 32), IndexSize)
length := 33
// Assert deposit is not zero
assertOrFraud(gt(getDeposits(depositHashID), 0), FraudCode_TransactionInputDepositZero)
// Assert Witness Index is Valid
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionInputDepositWitnessOverflow)
}
// Select HTLC information (length includes type)
function selectAndVerifyInputHTLC(input, witnessesLength) -> length, utxoID,
witnessReference, preImage {
utxoID := mload(safeAdd(input, TypeSize))
witnessReference := slice(add3(input, TypeSize, 32), IndexSize)
preImage := mload(add4(input, TypeSize, 32, IndexSize))
length := 65
// Assert valid Witness Reference (could be changed to generic witness ref overflow later..)
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionHTLCWitnessOverflow)
}
// Select output type
function selectOutputType(output) -> result {
result := slice(output, TypeSize) // [1 bytes]
}
// Select output amounts length (length includes type)
function selectAndVerifyOutputAmountLength(output) -> length {
// Select amounts length past Input Type
length := slice(safeAdd(TypeSize, output), 1)
// Assert amounts length greater than zero
assertOrFraud(gt(length, 0), FraudCode_TransactionOutputAmountLengthUnderflow)
// Assert amounts length less than 33 (i.e 1 <> 32)
assertOrFraud(lte(length, 32), FraudCode_TransactionOutputAmountLengthOverflow)
}
// Select output utxo (length includes type)
function selectAndVerifyOutput(output, isChangeOutput) -> length, amount, owner, tokenID {
let amountLength := selectAndVerifyOutputAmountLength(output)
// Push amount
amount := slice(add3(TypeSize, 1, output), amountLength) // 1 for Type, 1 for Amount Length
// owner dynamic length
let ownerLength := 20
// is Change output, than owner is witness reference
if eq(isChangeOutput, 1) {
ownerLength := 1
}
// Push owner
owner := slice(add4(TypeSize, 1, amountLength, output), ownerLength)
// Select Token ID
tokenID := slice(add4(TypeSize, 1, amountLength, safeAdd(ownerLength, output)), 4)
// Assert Token ID is Valid
assertOrFraud(lt(tokenID, getNumTokens()), FraudCode_TransactionOutputTokenIDOverflow)
// Push Output Length (don't include type size)
length := add4(TypeSize, amountLength, ownerLength, 4)
}
// Select output HTLC
function selectAndVerifyOutputHTLC(output, witnessesLength) -> length, amount, owner,
tokenID, digest, expiry, returnWitness {
// Select amount length
let amountLength := selectAndVerifyOutputAmountLength(output)
// Select Output Details
length, amount, owner, tokenID := selectAndVerifyOutput(output, False)
// htlc
let htlc := add3(TypeSize, output, length)
// Select Digest from Output
digest := mload(htlc)
// Assert Token ID is Valid
assertOrFraud(gt(digest, 0), FraudCode_TransactionOutputHTLCDigestZero)
// Select Expiry
expiry := slice(safeAdd(htlc, DigestSize), ExpirySize)
// Assert Expiry is Valid
assertOrFraud(gt(expiry, 0), FraudCode_TransactionOutputHTLCExpiryZero)
// Set expiry, digest, witness
returnWitness := slice(add3(htlc, DigestSize, ExpirySize), IndexSize)
// Assert Valid Return Witness
assertOrFraud(lt(returnWitness, witnessesLength),
FraudCode_TransactionOutputWitnessReferenceOverflow)
// Determine output length (don't include type size)
length := add4(length, DigestSize, ExpirySize, IndexSize)
}
// Select the Transaction Leaf from Data
function selectTransactionLeaf(transactionData) -> leaf {
/*
- Transaction Data:
- inputSelector [32 bytes]
- outputSelector [32 bytes]
- witnessSelector [32 bytes]
- transactionIndex [32 bytes]
- transactionLeafData [dynamic bytes]
*/
// Increase memory past the 3 selectors and 1 Index
leaf := safeAdd(transactionData, mul32(6))
}
// Select transaction length
function selectTransactionLength(transactionData) -> transactionLength {
// Select transaction length
transactionLength := slice(selectTransactionLeaf(transactionData), 2)
}
// Select Metadata Length
function selectTransactionMetadataLength(transactionData) -> metadataLength {
// Select metadata length 1 bytes
metadataLength := slice(safeAdd(selectTransactionLeaf(transactionData), 2), 1)
}
// Select Witnesses (past witness length)
function selectTransactionWitnesses(transactionData) -> witnessesMemoryPosition {
// Compute metadata size
let metadataLength := selectTransactionMetadataLength(transactionData)
// Compute Metadata Size
let metadataSize := safeAdd(TypeSize, safeMul(MetadataSize, metadataLength)) // Length + metadata size
// Leaf + Size 2 + metadata size and witness size
witnessesMemoryPosition := add4(selectTransactionLeaf(transactionData), 2,
metadataSize, 1)
}
function selectWitnessSignature(witnesses, witnessIndex) -> signature {
// Compute witness offset
let witnessMemoryOffset := safeMul(witnessIndex, WitnessSize)
// Compute signature
signature := safeAdd(witnesses, witnessMemoryOffset)
}
// Note, we allow the transactionRootProducer to be a witness, witnesses length must be 1, zero fill 65 for witness data..
// Select Witnesses Signature
function verifyTransactionWitness(signature, transactionHashID, outputOwner, rootProducer) {
// Check if the witness is not the transaction root producer (i.e. a contract possibly)
if iszero(eq(rootProducer, outputOwner)) {
// Assert if witness signature is invalid!
assertOrFraud(eq(outputOwner, ecrecoverPacked(transactionHashID, signature)),
FraudCode_InvalidTransactionWitnessSignature)
}
}
// Select Transaction Leaf Data
function selectAndVerifyTransactionLeafData(transactionData) ->
transactionHashData, // transaction hash data (unsigned transaction data)
metadataSize, // total metadata chunk size (length + metadata)
witnessesSize, // total witness size (length + witnesses)
witnessesLength { // total witnesses length
// Compute metadata size
let metadataLength := selectTransactionMetadataLength(transactionData)
// Assert metadata length correctness (metadata length can be zero)
assertOrFraud(lte(metadataLength, TransactionLengthMax),
FraudCode_TransactionMetadataLengthOverflow)
// Compute Metadata Size
metadataSize := safeAdd(1, safeMul(MetadataSize, metadataLength)) // Length + metadata size
// Leaf + Size 2 + metadata size and witness size
transactionHashData := add3(selectTransactionLeaf(transactionData), 2, metadataSize)
// get witnesses length
witnessesLength := slice(transactionHashData, 1) // Witness Length
witnessesSize := safeAdd(1, safeMul(WitnessSize, witnessesLength)) // Length + witness size
// Leaf + Size 2 + metadata size and witness size
transactionHashData := safeAdd(transactionHashData, witnessesSize)
}
// Select Transaction Details
function selectAndVerifyTransactionDetails(transactionData) ->
memoryPosition, inputsLength, outputsLength, witnessesLength {
let unsignedTransactionData, metadataSize,
witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData)
// Setup length (push to new name)
witnessesLength := witnessLength
// Set Transaction Data Memory Position
memoryPosition := unsignedTransactionData
// Assert witness length
assertOrFraud(gt(witnessesLength, TransactionLengthMin),
FraudCode_TransactionWitnessesLengthUnderflow)
assertOrFraud(lte(witnessesLength, TransactionLengthMax),
FraudCode_TransactionWitnessesLengthOverflow)
// Select lengths
inputsLength := slice(memoryPosition, 1) // Inputs Length
outputsLength := slice(safeAdd(1, memoryPosition), 1) // Outputs Length
// Assert inputsLength and outputsLength minimum
assertOrFraud(gt(inputsLength, TransactionLengthMin),
FraudCode_TransactionInputsLengthUnderflow)
assertOrFraud(gt(outputsLength, TransactionLengthMin),
FraudCode_TransactionOutputsLengthUnderflow)
// Assert Length overflow checks
assertOrFraud(lte(inputsLength, TransactionLengthMax),
FraudCode_TransactionInputsLengthOverflow)
assertOrFraud(lte(outputsLength, TransactionLengthMax),
FraudCode_TransactionOutputsLengthOverflow)
// Assert metadata length correctness (metadata length can be zero)
assertOrFraud(lte(selectTransactionMetadataLength(transactionData), inputsLength),
FraudCode_TransactionMetadataLengthOverflow)
// Assert selections are valid against lengths
assertOrInvalidProof(lt(selectInputSelectionIndex(transactionData), inputsLength),
ErrorCode_InputIndexSelectedOverflow)
assertOrInvalidProof(lt(selectOutputSelectionIndex(transactionData), outputsLength),
ErrorCode_OutputIndexSelectedOverflow)
assertOrInvalidProof(lt(selectWitnessSelectionIndex(transactionData), witnessesLength),
ErrorCode_WitnessIndexSelectedOverflow)
}
// Select Transaction Metadata (Past Length)
function selectTransactionMetadata(transactionData) -> transactionMetadata {
// Increase memory position past lengths
transactionMetadata := safeAdd(selectTransactionLeaf(transactionData), 3)
}
// Select UTXO proof
function selectAndVerifyUTXOAmountOwner(utxoProof, requestedOutputType, providedUTXOID) ->
outputAmount, outputOwner, tokenID {
/*
- Transaction UTXO Proof(s): -- 288 bytes (same order as inputs, skip Deposit index with zero fill)
- transactionHashId [32 bytes] -- bytes32
- outputIndex [32 bytes] -- padded uint8
- type [32 bytes] -- padded uint8
- amount [32 bytes] -- uint256
- owner [32 bytes] -- padded address or witness reference index uint8
- tokenID [32 bytes] -- padded uint32
- [HTLC Data]:
- digest [32 bytes] -- bytes32 (or zero pad 32 bytes)
- expiry [32 bytes] -- padded uint32 (or zero pad 32 bytes)
- return witness index [32 bytes] -- padded uint8] (or zero pad 32 bytes)
*/
// Assert computed utxo id correct
assertOrInvalidProof(eq(providedUTXOID, constructUTXOID(utxoProof)),
ErrorCode_TransactionUTXOIDInvalid)
// Compute output amount
let outputType := load32(utxoProof, 2)
// Assert output type is correct
assertOrFraud(eq(requestedOutputType, outputType),
FraudCode_TransactionUTXOType)
// Assert index correctness
assertOrFraud(lt(load32(utxoProof, 1), TransactionLengthMax),
FraudCode_TransactionUTXOOutputIndexOverflow)
// Compute output amount
outputAmount := load32(utxoProof, 3)
// Compute output amount
outputOwner := load32(utxoProof, 4)
// Compute output amount
tokenID := load32(utxoProof, 5)
}
//
// CONSTRUCTION METHODS
// For the construction of cryptographic side-chain hashes
//
// produce block hash from block header
function constructBlockHash(blockHeader) -> blockHash {
/*
- Block Header:
- blockProducer [32 bytes] -- padded address
- previousBlockHash [32 bytes]
- blockHeight [32 bytes]
- ethereumBlockNumber [32 bytes]
- transactionRoots [64 + bytes32 array]
*/
// Select Transaction root Length
let transactionRootsLength := load32(blockHeader, 5)
// Construct Block Hash
blockHash := keccak256(blockHeader, mul32(safeAdd(6, transactionRootsLength)))
}
// produce a transaction hash id from a proof (subtract metadata and inputs length from hash data)
function constructTransactionHashID(transactionData) -> transactionHashID {
/*
- Transaction Data:
- inputSelector [32 bytes]
- outputSelector [32 bytes]
- witnessSelector [32 bytes]
- transactionIndex [32 bytes]
- transactionLeafData [dynamic bytes]
- Transaction Leaf Data:
- transactionByteLength [2 bytes] (max 2048)
- metadata length [1 bytes] (min 1 - max 8)
- input metadata [dynamic -- 8 bytes per]:
- blockHeight [4 bytes]
- transactionRootIndex [1 byte]
- transactionIndex [2 bytes]
- output index [1 byte]
- witnessLength [1 bytes]
- witnesses [dynamic]:
- signature [65 bytes]
*/
// Get entire tx length, and metadata sizes / positions
let transactionLength := selectTransactionLength(transactionData) // length is first 2
if gt(transactionLength, 0) {
let transactionLeaf, metadataSize,
witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData)
// setup hash keccak256(start, length)
let transactionHashDataLength := safeSub(safeSub(transactionLength, TransactionLengthSize),
safeAdd(metadataSize, witnessesSize))
// create transaction ID
transactionHashID := keccak256(transactionLeaf, transactionHashDataLength)
}
}
// Construct Deposit Hash ID
function constructDepositHashID(depositProof) -> depositHashID {
depositHashID := keccak256(depositProof, mul32(3))
}
// Construct a UTXO Proof from a Transaction Output
function constructUTXOProof(transactionHashID, outputIndex, output) -> utxoProof {
let isChangeOutput := False
// Output Change
if eq(selectOutputType(output), OutputType_Change) {
isChangeOutput := True
}
// Select and Verify output
let length, amount, owner, tokenID := selectAndVerifyOutput(output, isChangeOutput)
// Encode Pack Transaction Output Data
mstore(mul32(1), transactionHashID)
mstore(mul32(2), outputIndex)
mstore(mul32(3), selectOutputType(output))
mstore(mul32(4), amount)
mstore(mul32(5), owner) // address or witness index
mstore(mul32(6), tokenID)
mstore(mul32(7), 0)
mstore(mul32(8), 0)
mstore(mul32(9), 0)
// Include HTLC Data here
if eq(selectOutputType(output), 2) {
let unused0, unused1, unused2,
unused3, digest, expiry, returnWitness := selectAndVerifyOutputHTLC(output,
TransactionLengthMax)
mstore(mul32(7), digest)
mstore(mul32(8), expiry)
mstore(mul32(9), returnWitness)
}
// Return UTXO Memory Position
utxoProof := mul32(1)
}
// Construct a UTXO ID
function constructUTXOID(utxoProof) -> utxoID {
/*
- Transaction UTXO Data:
- transactionHashId [32 bytes]
- outputIndex [32 bytes] -- padded uint8
- type [32 bytes] -- padded uint8
- amount [32 bytes]
- owner [32 bytes] -- padded address or unit8
- tokenID [32 bytes] -- padded uint32
- [HTLC Data]: -- padded with zeros
- digest [32 bytes]
- expiry [32 bytes] -- padded 4 bytes
- return witness index [32 bytes] -- padded 1 bytes
*/
// Construct UTXO ID
utxoID := keccak256(utxoProof, UTXOProofSize)
}
// Construct the Transaction Leaf Hash
function constructTransactionLeafHash(transactionData) -> transactionLeafHash {
/*
- Transaction Data:
- inputSelector [32 bytes]
- outputSelector [32 bytes]
- witnessSelector [32 bytes]
- transactionIndex [32 bytes]
- transactionLeafData [dynamic bytes]
*/
// Get first two transaction length bytes
let transactionLength := selectTransactionLength(transactionData)
// Check if length is Zero, than don't hash!
switch eq(transactionLength, 0)
// Return Zero leaf hash
case 1 {
transactionLeafHash := 0
}
// Hash as Normal Transaction
default {
// Start Hash Past Selections (3) and Index (1)
let hashStart := selectTransactionLeaf(transactionData)
// Return the transaction leaf hash
transactionLeafHash := keccak256(hashStart, transactionLength)
}
}
// Select input index
function selectInputSelectionIndex(transactionData) -> inputIndex {
inputIndex := load32(transactionData, 0)
}
// Select output index
function selectOutputSelectionIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 1)
}
// Select witness index
function selectWitnessSelectionIndex(transactionData) -> witnessIndex {
witnessIndex := load32(transactionData, 2)
}
// This function Must Select Block of Current Proof Being Validated!! NOT DONE YET!
// Assert True or Fraud, Set Side-chain to Valid block and Stop Execution
function assertOrFraud(assertion, fraudCode) {
// Assert or Begin Fraud State Change Sequence
if lt(assertion, 1) {
// proof index
let proofIndex := 0
// We are validating proof 2
if gt(mstack(Stack_ProofNumber), 0) {
proofIndex := 1
}
// Fraud block details
let fraudBlockHeight := selectBlockHeight(selectBlockHeader(proofIndex))
let fraudBlockProducer := selectBlockProducer(selectBlockHeader(proofIndex))
let ethereumBlockNumber := selectEthereumBlockNumber(selectBlockHeader(proofIndex))
// Assert Fraud block cannot be the genesis block
assertOrInvalidProof(gt(fraudBlockHeight, GenesisBlockHeight),
ErrorCode_FraudBlockHeightUnderflow)
// Assert fraud block cannot be finalized
assertOrInvalidProof(lt(number(), safeAdd(ethereumBlockNumber, FINALIZATION_DELAY)),
ErrorCode_FraudBlockFinalized)
// Push old block tip
let previousBlockTip := getBlockTip()
// Set new block tip to before fraud block
setBlockTip(safeSub(fraudBlockHeight, 1))
// Release Block Producer, If it's Permissioned
// (i.e. block producer committed fraud so get them out!)
// if eq(fraudBlockProducer, getBlockProducer()) {
// setBlockProducer(0)
// }
// Log block tips (old / new)
log4(0, 0, FraudEventTopic, previousBlockTip, getBlockTip(),
fraudCode)
// Transfer Half The Bond for this Block
transfer(div(BOND_SIZE, 2), EtherToken, EtherToken, caller())
// stop execution from here
stop()
}
}
// Construct withdrawal Hash ID
function constructWithdrawalHashID(transactionRootIndex,
transactionLeafHash, outputIndex) -> withdrawalHashID {
// Construct withdrawal Hash
mstore(mul32(1), transactionRootIndex)
mstore(mul32(2), transactionLeafHash)
mstore(mul32(3), outputIndex)
// Hash Leaf and Output Together
withdrawalHashID := keccak256(mul32(1), mul32(3))
}
// Construct Transactions Merkle Tree Root
function constructMerkleTreeRoot(transactions, transactionsLength) -> merkleTreeRoot {
// Start Memory Position at Transactions Data
let memoryPosition := transactions
let nodesLength := 0
let netLength := 0
let freshMemoryPosition := mstack(Stack_FreshMemory)
// create base hashes and notate node count
for { let transactionIndex := 0 }
lt(transactionIndex, MaxTransactionsInBlock)
{ transactionIndex := safeAdd(transactionIndex, 1) } {
// get the transaction length
let transactionLength := slice(memoryPosition, TransactionLengthSize)
// If Transaction length is zero and we are past first tx, stop (we are at the end)
if and(gt(transactionIndex, 0), iszero(transactionLength)) { break }
// if transaction length is below minimum transaction length, stop
verifyTransactionLength(transactionLength)
// add net length together
netLength := safeAdd(netLength, transactionLength)
// computed length greater than provided payload
assertOrFraud(lte(netLength, transactionsLength),
FraudCode_InvalidTransactionsNetLength)
// store the base leaf hash (add 2 removed from here..)
mstore(freshMemoryPosition, keccak256(memoryPosition, transactionLength))
// increase the memory length
memoryPosition := safeAdd(memoryPosition, transactionLength)
// increase fresh memory by 32 bytes
freshMemoryPosition := safeAdd(freshMemoryPosition, 32)
// increase number of nodes
nodesLength := safeAdd(nodesLength, 1)
}
// computed length greater than provided payload
assertOrFraud(eq(netLength, transactionsLength), FraudCode_InvalidTransactionsNetLength)
// Merkleize nodes into a binary merkle tree
memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 32)) // setup new memory position
// Create Binary Merkle Tree / Master Root Hash
for {} gt(nodesLength, 0) {} { // loop through tree Heights (starting at base)
if gt(mod(nodesLength, 2), 0) { // fix uneven leaf count (i.e. add a zero hash)
mstore(safeAdd(memoryPosition, safeMul(nodesLength, 32)), 0) // add 0x00...000 hash leaf
nodesLength := safeAdd(nodesLength, 1) // increase count for zero hash leaf
freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new leaf
}
for { let i := 0 } lt(i, nodesLength) { i := safeAdd(i, 2) } { // loop through Leaf hashes at this height
mstore(freshMemoryPosition, keccak256(safeAdd(memoryPosition, safeMul(i, 32)), 64)) // hash two leafs together
freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new hash leaf
}
memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 16)) // set new memory position
nodesLength := div(nodesLength, 2) // half nodes (i.e. next height)
// shim 1 to zero (stop), i.e. top height end..
if lt(nodesLength, 2) { nodesLength := 0 }
}
// merkle root has been produced
merkleTreeRoot := mload(memoryPosition)
// write new fresh memory position
mpush(Stack_FreshMemory, safeAdd(freshMemoryPosition, mul32(2)))
}
// Construct HTLC Digest Hash
function constructHTLCDigest(preImage) -> digest {
// Store PreImage in Memory
mstore(mul32(1), preImage)
// Construct Digest Hash
digest := keccak256(mul32(1), mul32(1))
}
//
// LOW LEVEL METHODS
//
// Safe Math Add
function safeAdd(x, y) -> z {
z := add(x, y)
assertOrInvalidProof(or(eq(z, x), gt(z, x)), ErrorCode_SafeMathAdditionOverflow) // require((z = x + y) >= x, "ds-math-add-overflow");
}
// Safe Math Subtract
function safeSub(x, y) -> z {
z := sub(x, y)
assertOrInvalidProof(or(eq(z, x), lt(z, x)), ErrorCode_SafeMathSubtractionUnderflow) // require((z = x - y) <= x, "ds-math-sub-underflow");
}
// Safe Math Multiply
function safeMul(x, y) -> z {
if gt(y, 0) {
z := mul(x, y)
assertOrInvalidProof(eq(div(z, y), x), ErrorCode_SafeMathMultiplyOverflow) // require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
// Safe Math Add3, Add4 Shorthand
function add3(x, y, z) -> result {
result := safeAdd(x, safeAdd(y, z))
}
function add4(x, y, z, k) -> result {
result := safeAdd(x, safeAdd(y, safeAdd(z, k)))
}
// Common <= and >=
function lte(v1, v2) -> result {
result := or(lt(v1, v2), eq(v1, v2))
}
function gte(v1, v2) -> result {
result := or(gt(v1, v2), eq(v1, v2))
}
// Safe Multiply by 32
function mul32(length) -> result {
result := safeMul(32, length)
}
// function combine 3 unit32 values together into one 32 byte combined value
function combineUint32(val1, val2, val3, val4) -> combinedValue {
mstore(safeAdd(mul32(2), 8), val4) // 2 bytes
mstore(safeAdd(mul32(2), 6), val3) // 2 bytes
mstore(safeAdd(mul32(2), 4), val2) // 2 bytes
mstore(safeAdd(mul32(2), 2), val1) // 2 bytes
// Grab combined value
combinedValue := mload(mul32(3))
}
// split a combined value into three original chunks
function splitCombinedUint32(combinedValue) -> val1, val2, val3, val4 {
mstore(mul32(2), combinedValue)
// grab values
val1 := slice(safeAdd(mul32(2), 0), 2) // 2 byte slice
val2 := slice(safeAdd(mul32(2), 2), 2) // 2 byte slice
val3 := slice(safeAdd(mul32(2), 4), 2) // 2 byte slice
val3 := slice(safeAdd(mul32(2), 6), 2) // 2 byte slice
}
// Transfer method helper
function transfer(amount, tokenID, token, owner) {
// Assert value owner / amount
assertOrInvalidProof(gt(amount, 0), ErrorCode_TransferAmountUnderflow)
assertOrInvalidProof(gt(owner, 0), ErrorCode_TransferOwnerInvalid)
// Assert valid token ID
assertOrInvalidProof(lt(tokenID, getNumTokens()), ErrorCode_TransferTokenIDOverflow)
// Assert address is properly registered token
assertOrInvalidProof(eq(tokenID, getTokens(token)), ErrorCode_TransferTokenAddress)
// Ether Token
if eq(token, EtherToken) {
let result := call(owner, 21000, amount, 0, 0, 0, 0)
assertOrInvalidProof(result, ErrorCode_TransferEtherCallResult)
}
// ERC20 "a9059cbb": "transfer(address,uint256)",
if gt(token, 0) {
// Construct ERC20 Transfer
mstore(mul32(1), 0xa9059cbb)
mstore(mul32(2), owner)
mstore(mul32(3), amount)
// Input Details
let inputStart := safeAdd(mul32(1), 28)
let inputLength := 68
// ERC20 Call
let result := call(token, 400000, 0, inputStart, inputLength, 0, 0)
assertOrInvalidProof(result, ErrorCode_TransferERC20Result)
}
}
// Virtual Memory Stack Push (for an additional 32 stack positions)
function mpush(pos, val) { // Memory Push
mstore(add(Stack_MemoryPosition, mul32(pos)), val)
}
// Virtual Memory Stack Get
function mstack(pos) -> result { // Memory Stack
result := mload(add(Stack_MemoryPosition, mul32(pos)))
}
// Virtual Stack Pop
function mpop(pos) { // Memory Pop
mstore(add(Stack_MemoryPosition, mul32(pos)), 0)
}
// Memory Slice (within a 32 byte chunk)
function slice(position, length) -> result {
if gt(length, 32) { revert(0, 0) } // protect against overflow
result := div(mload(position), exp(2, safeSub(256, safeMul(length, 8))))
}
// Solidity Storage Key: mapping(bytes32 => bytes32)
function mappingStorageKey(key, storageIndex) -> storageKey {
mstore(32, key)
mstore(64, storageIndex)
storageKey := keccak256(32, 64)
}
// Solidity Storage Key: mapping(bytes32 => mapping(bytes32 => bytes32)
function mappingStorageKey2(key, key2, storageIndex) -> storageKey {
mstore(32, key)
mstore(64, storageIndex)
mstore(96, key2)
mstore(128, keccak256(32, 64))
storageKey := keccak256(96, 64)
}
// load a 32 byte chunk with a 32 byte offset chunk from position
function load32(memoryPosition, chunkOffset) -> result {
result := mload(add(memoryPosition, safeMul(32, chunkOffset)))
}
// Assert True or Invalid Proof
function assertOrInvalidProof(arg, errorCode) {
if lt(arg, 1) {
// Set Error Code In memory
mstore(mul32(1), errorCode)
// Revert and Return Error Code
revert(mul32(1), mul32(1))
// Just incase we add a stop
stop()
}
}
// ECRecover Helper: hashPosition (32 bytes), signaturePosition (65 bytes) tight packing VRS
function ecrecoverPacked(digestHash, signatureMemoryPosition) -> account {
mstore(32, digestHash) // load in hash
mstore(64, 0) // zero pas
mstore(95, mload(signatureMemoryPosition))
mstore(96, mload(safeAdd(signatureMemoryPosition, 1)))
mstore(128, mload(safeAdd(signatureMemoryPosition, 33)))
let result := call(3000, 1, 0, 32, 128, 128, 32) // 4 chunks, return at 128
if eq(result, 0) { revert(0, 0) }
account := mload(128) // set account
}
//
// SETTERS & GETTER METHODS
// Solidity setters and getters for side-chain state storage
//
// GET mapping(bytes32 => uint256) public deposits; // STORAGE 0
function getDeposits(depositHashId) -> result {
result := sload(mappingStorageKey(depositHashId, Storage_deposits))
}
// GET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1
function getWithdrawals(blockHeight, withdrawalHashID) -> result {
result := sload(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals))
}
// SET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1
function setWithdrawals(blockHeight, withdrawalHashID, hasWithdrawn) {
sstore(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals), hasWithdrawn)
}
// GET mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2
function getBlockTransactionRoots(transactionRoot) -> result {
result := sload(mappingStorageKey(transactionRoot, Storage_blockTransactionRoots))
}
// GET mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3
function getBlockCommitments(blockHeight) -> result {
result := sload(mappingStorageKey(blockHeight, Storage_blockCommitments))
}
// GET mapping(address => uint256) public tokens; // STORAGE 4
function getTokens(tokenAddress) -> result {
result := sload(mappingStorageKey(tokenAddress, Storage_tokens))
// Ether token should always be zero
if eq(tokenAddress, 0) {
assertOrInvalidProof(eq(result, 0), ErrorCode_InvalidTokenAddress)
}
// ERC20 should always be above zero
if gt(tokenAddress, 0) {
assertOrInvalidProof(gt(result, 0), ErrorCode_InvalidTokenAddress)
}
}
// GET uint256 public numTokens; // STORAGE 5
function getNumTokens() -> result {
result := sload(Storage_numTokens)
}
// SET uint256 public blockTip; // STORAGE 6
function getBlockTip() -> result {
result := sload(Storage_blockTip)
}
// SET blockTip() // STORAGE 6
function setBlockTip(tip) {
sstore(Storage_blockTip, tip)
}
// GET address public blockProducer; // STORAGE 7
function getBlockProducer() -> result {
result := sload(Storage_blockProducer)
}
// SET address public blockProducer // STORAGE 7
function setBlockProducer(producer) {
sstore(Storage_blockProducer, producer)
}
}
}
}
| Select Transaction Data from Proof Select Proof Memory Position Get lengths Select Transaction Data Position | function selectTransactionData(proofIndex) -> transactionData {
let proofMemoryPosition := selectTransactionProof(proofIndex)
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition)
transactionData := add4(proofMemoryPosition, lengthsLength,
blockHeaderLength, safeAdd(transactionRootHeaderLength, transactionMerkleLength))
}
| 12,672,907 |
/******************************************************************************\
file: Math.sol
ver: 0.5.0
updated:25-10-2017
author: Darryl Morris (o0ragman0o)
email: o0ragman0o AT gmail.com
unit256 and uint64 Safe maths libraries.
---
pragma solidity ^0.4.13;
import "Math.sol"
contract K{
using MathU for uint;
uint num;
function foo(uint x) {
...
num = num.add(x);
...
}
}
---
This software 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 MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
Release Notes
-------------
* set all functions to `pure`
* Added safe uint casting for common uint sub types
* removed Math64 library
\******************************************************************************/
pragma solidity ^0.4.13;
library Math
{
int8 constant LT = -1;
int8 constant EQ = 0;
int8 constant GT = 1;
// a add to b
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
assert(c >= a);
}
// a subtract b
function sub(uint a, uint b) internal pure returns (uint c) {
c = a - b;
assert(c <= a);
}
// a multiplied by b
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
assert(a == 0 || c / a == b);
}
// a divided by b
function div(uint a, uint b) internal pure returns (uint c) {
require (b != 0);
c = a / b;
}
// Increment
function inc(uint a) internal pure returns (uint c) {
c = a + 1;
assert(c > a);
}
// Decrement
function dec(uint a) internal pure returns (uint c) {
c = a - 1;
assert(c < a);
}
// Raise a to power of b
function pow(uint a, uint8 b) internal pure returns (uint c) {
c = a**b;
// Not a sufficient test as overflowed result may still be larger
assert(c > a);
}
// Equal to
function eq(uint a, uint b) internal pure returns (bool) {
return a == b;
}
// Less than
function lt(uint a, uint b) internal pure returns (bool) {
return a < b;
}
// Greater than
function gt(uint a, uint b) internal pure returns (bool) {
return a > b;
}
// Less than or equal to.
function lteq(uint a, uint b) internal pure returns (bool) {
return a <= b;
}
// Greater than or equal to.
function gteq(uint a, uint b) internal pure returns (bool) {
return a >= b;
}
// Zero value test
function isZero(uint a) internal pure returns (bool) {
return a == 0;
}
// Parametric comparitor for > or <
// !_sym returns a < b
// _sym returns a > b
function cmp(uint a, uint b, bool sym) internal pure returns (bool)
{
return (a!=b) && ((a < b) != sym);
}
// Parametric comparitor for >= or <=
// !_sym returns a <= b
// _sym returns a >= b
function cmpEq(uint a, uint b, bool sym) internal pure returns (bool)
{
return (a==b) || ((a < b) != sym);
}
// Trinary comparitor returning int -1, 0, 1 for LT, EQ, GT
function cmpTri(uint a, uint b) internal pure returns (int8) {
return a < b ? LT : a > b ? GT : EQ;
}
// Safe cast from uint to uint8
function to8(uint a) internal pure returns (uint8 b) {
b = uint8(a);
assert(uint(b) == a);
}
// Safecast from uint to uint16
function to16(uint a) internal pure returns (uint16 b) {
b = uint16(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint32
function to32(uint a) internal pure returns (uint32 b) {
b = uint32(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint40
function to40(uint a) internal pure returns (uint40 b) {
b = uint40(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint48
function to48(uint a) internal pure returns (uint48 b) {
b = uint48(a);
assert(uint(b) == a);
}
// Safecast from uint to uint56
function to56(uint a) internal pure returns (uint56 b) {
b = uint56(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint64
function to64(uint a) internal pure returns (uint64 b) {
b = uint64(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint72
function to72(uint a) internal pure returns (uint72 b) {
b = uint72(a);
assert(uint(b) == a);
}
// Safecast from uint to uint80
function to80(uint a) internal pure returns (uint80 b) {
b = uint80(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint96
function to96(uint a) internal pure returns (uint96 b) {
b = uint96(a);
assert(uint(b) == a);
}
// Safecast from uint to uint128
function to128(uint a) internal pure returns (uint128 b) {
b = uint128(a);
assert(uint(b) == a);
}
// Safecast from uint to uint192
function to192(uint a) internal pure returns (uint192 b) {
b = uint192(a);
assert(uint(b) == a);
}
} | Safecast from uint to uint192 | function to192(uint a) internal pure returns (uint192 b) {
b = uint192(a);
assert(uint(b) == a);
}
| 12,755,861 |
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);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/*
* @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;
}
}
/**
* @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);
}
}
/**
* @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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
interface LootInterface {
function ownerOf(uint256 tokenId) external view returns (address owner);
}
contract Loot is ERC721Enumerable, ReentrancyGuard, Ownable {
uint256 public publicPrice = 10000000000000000; //0.01 ETH
//Loot Contract
address public lootAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
LootInterface public lootContract = LootInterface(lootAddress);
string[] private adjectives = [
"Surprising",
"Predictable",
"Agreeable",
"Mysterious",
"Colossal",
"Great",
"Huge",
"Lazy",
"Miniature",
"Microscopic",
"Massive",
"Puny",
"Immense",
"Large",
"Little",
"Scrawny",
"Short",
"Small",
"Tiny",
"Gigantic",
"Mammoth",
"Gentle",
"Lively",
"Ambitious",
"Delightful",
"Eager",
"Happy",
"Jolly",
"Polite",
"Victorious",
"Witty",
"Wonderful",
"Zealous",
"Attractive",
"Dazzling",
"Magnificent",
"Plain",
"Scruffy",
"Unsightly",
"Legendary",
"Sneaky",
"Fit",
"Drab",
"Elegant",
"Glamorous",
"Truthful",
"Pitiful",
"Angry",
"Fierce",
"Embarrassed",
"Scary",
"Terrifying",
"Panicky",
"Thoughtless",
"Worried",
"Foolish",
"Frantic",
"Perfect",
"Timely",
"Dashing",
"Dangerous",
"Icy",
"Dull",
"Cloudy",
"Enchanting"
];
string[] private toots = [
"Butt ghost",
"Fart",
"Wind",
"Air biscuit",
"Bark",
"Blast",
"Bomber",
"Boom-boom",
"Bubbler",
"Burner",
"Butt Bazooka",
"Butt Bongo",
"Butt Sneeze",
"Butt Trumpet",
"Butt Tuba",
"Butt Yodeling",
"Cheek Squeak",
"Cheeser",
"Drifter",
"Fizzler",
"Flatus",
"Floater",
"Fluffy",
"Frump",
"Gas",
"Grunt",
"Gurgler",
"Hisser",
"Honker",
"Hot wind",
"Nasty cough",
"One-man salute",
"Bottom burp",
"Peter",
"Pewie",
"Poof",
"Pootsa",
"Pop tart",
"Power puff",
"Puffer",
"Putt-Putt",
"Quack",
"Quaker",
"Raspberry",
"Rattler",
"Rump Ripper",
"Rump Roar",
"Slider",
"Spitter",
"Squeaker",
"Steamer",
"Stinker",
"Stinky",
"Tootsie",
"Trouser Cough",
"Trouser Trumpet",
"Trunk Bunk",
"Turtle Burp",
"Tushy Tickler",
"Under Thunder",
"Wallop",
"Whiff",
"Whoopee",
"Whopper",
"Vapor Loaf"
];
string[] private suffixes = [
"of Might",
"of Tang",
"of Death",
"of Life",
"of Pollution",
"of Power",
"of Giants",
"of Titans",
"of Skill",
"of Perfection",
"of Brilliance",
"of Enlightenment",
"of Protection",
"of Anger",
"of Rage",
"of Fury",
"of Vitriol",
"of the Fox",
"of Detection",
"of Reflection",
"of the Twins",
"of the Smog",
"of the Dragon"
];
string[] private namePrefixes = [
"Agony", "Apocalypse", "Armageddon", "Beast", "Behemoth", "Blight", "Blood", "Bramble",
"Brimstone", "Brood", "Carrion", "Cataclysm", "Chimeric", "Corpse", "Corruption", "Damnation",
"Death", "Demon", "Dire", "Dragon", "Dread", "Doom", "Dusk", "Eagle", "Empyrean", "Fate", "Foe",
"Gale", "Ghoul", "Gloom", "Glyph", "Golem", "Grim", "Hate", "Havoc", "Honour", "Horror", "Hypnotic",
"Kraken", "Loath", "Maelstrom", "Mind", "Miracle", "Morbid", "Oblivion", "Onslaught", "Pain",
"Pandemonium", "Phoenix", "Plague", "Rage", "Rapture", "Rune", "Skull", "Sol", "Soul", "Sorrow",
"Spirit", "Storm", "Tempest", "Torment", "Vengeance", "Victory", "Viper", "Vortex", "Woe", "Wrath",
"Light's", "Shimmering"
];
string[] private nameSuffixes = [
"Bane",
"Root",
"Bite",
"Song",
"Roar",
"Grasp",
"Instrument",
"Glow",
"Bender",
"Shadow",
"Whisper",
"Shout",
"Growl",
"Tear",
"Peak",
"Form",
"Sun",
"Moon"
];
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function getToot(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "TOOT", toots);
}
function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId))));
string memory output = sourceArray[rand % sourceArray.length];
output = string(abi.encodePacked(adjectives[rand % adjectives.length], " ", output));
uint256 greatness = rand % 21;
if (greatness > 14) {
output = string(abi.encodePacked(output, " ", suffixes[rand % suffixes.length]));
}
if (greatness >= 18) {
string[2] memory name;
name[0] = namePrefixes[rand % namePrefixes.length];
name[1] = nameSuffixes[rand % nameSuffixes.length];
if (greatness == 18) {
output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output));
} else {
output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +1"));
}
}
return output;
}
function tokenURI(uint256 tokenId) override public view returns (string memory) {
string[17] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
parts[1] = getToot(tokenId);
parts[3] = '</text><text x="10" y="40" class="base">';
parts[4] = '</text></svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4]));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Toot #', toString(tokenId), '", "description": "Toots are randomized adventurer farts generated and stored on chain. Smells, Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Toots in any way you want. Compatible with Loot (for Adventurers)", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
function mint(uint256 tokenId) public payable{
require(tokenId > 8000 && tokenId < 16000, "Token ID invalid");
require(publicPrice <= msg.value, "Ether value sent is not correct");
_safeMint(_msgSender(), tokenId);
}
function multiMint(uint256[] memory tokenIds) public payable nonReentrant {
require((publicPrice * tokenIds.length) <= msg.value, "Ether value sent is not correct");
for (uint256 i = 0; i < tokenIds.length; i++) {
require(tokenIds[i] > 8000 && tokenIds[i] < 16000, "Token ID invalid");
_safeMint(msg.sender, tokenIds[i]);
}
}
function mintWithLoot(uint256 lootId) public payable nonReentrant {
require(lootId > 0 && lootId <= 8000, "Token ID invalid");
require(lootContract.ownerOf(lootId) == msg.sender, "Not the owner of this loot");
_safeMint(_msgSender(), lootId);
}
function multiMintWithLoot(uint256[] memory lootIds) public payable nonReentrant {
for (uint256 i = 0; i < lootIds.length; i++) {
require(lootContract.ownerOf(lootIds[i]) == msg.sender, "Not the owner of this loot");
_safeMint(_msgSender(), lootIds[i]);
}
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function withdrawAll() public payable onlyOwner {
require(payable(_msgSender()).send(address(this).balance));
}
constructor() ERC721("Toot", "TOOT") Ownable() {}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
} | See {IERC721Metadata-tokenURI}./ | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
| 1,635,110 |
pragma solidity ^0.4.24;
contract ERC20Interface {
function name() public view returns(bytes32);
function symbol() public view returns(bytes32);
function balanceOf (address _owner) public view returns(uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (uint);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract AppCoins is ERC20Interface{
// Public variables of the token
address public owner;
bytes32 private token_name;
bytes32 private token_symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function AppCoins() public {
owner = msg.sender;
token_name = "AppCoins";
token_symbol = "APPC";
uint256 _totalSupply = 1000000;
totalSupply = _totalSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balances[owner] = totalSupply; // Give the creator all initial tokens
}
function name() public view returns(bytes32) {
return token_name;
}
function symbol() public view returns(bytes32) {
return token_symbol;
}
function balanceOf (address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal returns (bool) {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
}
// /**
// * Transfer tokens
// *
// * Send `_value` tokens to `_to` from your account
// *
// * @param _to The address of the recipient
// * @param _value the amount to send
// */
// function transfer(address _to, uint256 _value) public {
// _transfer(msg.sender, _to, _value);
// }
function transfer (address _to, uint256 _amount) public returns (bool success) {
if( balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
emit Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (uint) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return allowance[_from][msg.sender];
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balances[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
library CampaignLibrary {
struct Campaign {
bytes32 bidId;
uint price;
uint budget;
uint startDate;
uint endDate;
bool valid;
address owner;
}
/**
@notice Set campaign id
@param _bidId Id of the campaign
*/
function setBidId(Campaign storage _campaign, bytes32 _bidId) internal {
_campaign.bidId = _bidId;
}
/**
@notice Get campaign id
@return {'_bidId' : 'Id of the campaign'}
*/
function getBidId(Campaign storage _campaign) internal view returns(bytes32 _bidId){
return _campaign.bidId;
}
/**
@notice Set campaing price per proof of attention
@param _price Price of the campaign
*/
function setPrice(Campaign storage _campaign, uint _price) internal {
_campaign.price = _price;
}
/**
@notice Get campaign price per proof of attention
@return {'_price' : 'Price of the campaign'}
*/
function getPrice(Campaign storage _campaign) internal view returns(uint _price){
return _campaign.price;
}
/**
@notice Set campaign total budget
@param _budget Total budget of the campaign
*/
function setBudget(Campaign storage _campaign, uint _budget) internal {
_campaign.budget = _budget;
}
/**
@notice Get campaign total budget
@return {'_budget' : 'Total budget of the campaign'}
*/
function getBudget(Campaign storage _campaign) internal view returns(uint _budget){
return _campaign.budget;
}
/**
@notice Set campaign start date
@param _startDate Start date of the campaign (in milisecounds)
*/
function setStartDate(Campaign storage _campaign, uint _startDate) internal{
_campaign.startDate = _startDate;
}
/**
@notice Get campaign start date
@return {'_startDate' : 'Start date of the campaign (in milisecounds)'}
*/
function getStartDate(Campaign storage _campaign) internal view returns(uint _startDate){
return _campaign.startDate;
}
/**
@notice Set campaign end date
@param _endDate End date of the campaign (in milisecounds)
*/
function setEndDate(Campaign storage _campaign, uint _endDate) internal {
_campaign.endDate = _endDate;
}
/**
@notice Get campaign end date
@return {'_endDate' : 'End date of the campaign (in milisecounds)'}
*/
function getEndDate(Campaign storage _campaign) internal view returns(uint _endDate){
return _campaign.endDate;
}
/**
@notice Set campaign validity
@param _valid Validity of the campaign
*/
function setValidity(Campaign storage _campaign, bool _valid) internal {
_campaign.valid = _valid;
}
/**
@notice Get campaign validity
@return {'_valid' : 'Boolean stating campaign validity'}
*/
function getValidity(Campaign storage _campaign) internal view returns(bool _valid){
return _campaign.valid;
}
/**
@notice Set campaign owner
@param _owner Owner of the campaign
*/
function setOwner(Campaign storage _campaign, address _owner) internal {
_campaign.owner = _owner;
}
/**
@notice Get campaign owner
@return {'_owner' : 'Address of the owner of the campaign'}
*/
function getOwner(Campaign storage _campaign) internal view returns(address _owner){
return _campaign.owner;
}
/**
@notice Converts country index list into 3 uints
Expects a list of country indexes such that the 2 digit country code is converted to an
index. Countries are expected to be indexed so a "AA" country code is mapped to index 0 and
"ZZ" country is mapped to index 675.
@param countries List of country indexes
@return {
"countries1" : "First third of the byte array converted in a 256 bytes uint",
"countries2" : "Second third of the byte array converted in a 256 bytes uint",
"countries3" : "Third third of the byte array converted in a 256 bytes uint"
}
*/
function convertCountryIndexToBytes(uint[] countries) public pure
returns (uint countries1,uint countries2,uint countries3){
countries1 = 0;
countries2 = 0;
countries3 = 0;
for(uint i = 0; i < countries.length; i++){
uint index = countries[i];
if(index<256){
countries1 = countries1 | uint(1) << index;
} else if (index<512) {
countries2 = countries2 | uint(1) << (index - 256);
} else {
countries3 = countries3 | uint(1) << (index - 512);
}
}
return (countries1,countries2,countries3);
}
}
interface StorageUser {
function getStorageAddress() external view returns(address _storage);
}
interface ErrorThrower {
event Error(string func, string message);
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
contract Ownable is ErrorThrower {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
modifier onlyOwner(string _funcName) {
if(msg.sender != owner){
emit Error(_funcName,"Operation can only be performed by contract owner");
return;
}
_;
}
/**
* 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("renounceOwnership") {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* 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") {
_transferOwnership(_newOwner);
}
/**
* Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
if(_newOwner == address(0)){
emit Error("transferOwnership","New owner's address needs to be different than 0x0");
return;
}
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract SingleAllowance is Ownable {
address allowedAddress;
modifier onlyAllowed() {
require(allowedAddress == msg.sender);
_;
}
modifier onlyOwnerOrAllowed() {
require(owner == msg.sender || allowedAddress == msg.sender);
_;
}
function setAllowedAddress(address _addr) public onlyOwner("setAllowedAddress"){
allowedAddress = _addr;
}
}
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* Throws Error event if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(string _funcname, address _operator) {
if(!hasRole(_operator, ROLE_WHITELISTED)){
emit Error(_funcname, "Operation can only be performed by Whitelisted Addresses");
return;
}
_;
}
/**
* add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner("addAddressToWhitelist")
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* add addresses to the whitelist
* @param _operators 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[] _operators)
public
onlyOwner("addAddressesToWhitelist")
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* remove an address from the whitelist
* @param _operator 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 _operator)
public
onlyOwner("removeAddressFromWhitelist")
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* remove addresses from the whitelist
* @param _operators 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[] _operators)
public
onlyOwner("removeAddressesFromWhitelist")
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
contract BaseAdvertisementStorage is Whitelist {
using CampaignLibrary for CampaignLibrary.Campaign;
mapping (bytes32 => CampaignLibrary.Campaign) campaigns;
bytes32 lastBidId = 0x0;
modifier onlyIfCampaignExists(string _funcName, bytes32 _bidId) {
if(campaigns[_bidId].owner == 0x0){
emit Error(_funcName,"Campaign does not exist");
return;
}
_;
}
event CampaignCreated
(
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
);
event CampaignUpdated
(
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
);
/**
@notice Get a Campaign information
Based on a camapaign Id (bidId), returns all stored information for that campaign.
@param campaignId Id of the campaign
@return {
"bidId" : "Id of the campaign",
"price" : "Value to pay for each proof-of-attention",
"budget" : "Total value avaliable to be spent on the campaign",
"startDate" : "Start date of the campaign (in miliseconds)",
"endDate" : "End date of the campaign (in miliseconds)"
"valid" : "Boolean informing if the campaign is valid",
"campOwner" : "Address of the campaing's owner"
}
*/
function _getCampaign(bytes32 campaignId)
internal
returns (CampaignLibrary.Campaign storage _campaign) {
return campaigns[campaignId];
}
/**
@notice Add or update a campaign information
Based on a campaign Id (bidId), a campaign can be created (if non existent) or updated.
This function can only be called by the set of allowed addresses registered earlier.
An event will be emited during this function's execution, a CampaignCreated event if the
campaign does not exist yet or a CampaignUpdated if the campaign id is already registered.
@param bidId Id of the campaign
@param price Value to pay for each proof-of-attention
@param budget Total value avaliable to be spent on the campaign
@param startDate Start date of the campaign (in miliseconds)
@param endDate End date of the campaign (in miliseconds)
@param valid Boolean informing if the campaign is valid
@param owner Address of the campaing's owner
*/
function _setCampaign (
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
)
public
onlyIfWhitelisted("setCampaign",msg.sender) {
CampaignLibrary.Campaign storage campaign = campaigns[bidId];
campaign.setBidId(bidId);
campaign.setPrice(price);
campaign.setBudget(budget);
campaign.setStartDate(startDate);
campaign.setEndDate(endDate);
campaign.setValidity(valid);
bool newCampaign = (campaigns[bidId].getOwner() == 0x0);
campaign.setOwner(owner);
if(newCampaign){
emitCampaignCreated(campaign);
setLastBidId(bidId);
} else {
emitCampaignUpdated(campaign);
}
}
/**
@notice Constructor function
Initializes contract and updates allowed addresses to interact with contract functions.
*/
constructor() public {
addAddressToWhitelist(msg.sender);
}
/**
@notice Get the price of a campaign
Based on the Campaign id, return the value paid for each proof of attention registered.
@param bidId Campaign id to which the query refers
@return { "price" : "Reward (in wei) for each proof of attention registered"}
*/
function getCampaignPriceById(bytes32 bidId)
public
view
returns (uint price) {
return campaigns[bidId].getPrice();
}
/**
@notice Set a new price for a campaign
Based on the Campaign id, updates the value paid for each proof of attention registered.
This function can only be executed by allowed addresses and emits a CampaingUpdate event.
@param bidId Campaing id to which the update refers
@param price New price for each proof of attention
*/
function setCampaignPriceById(bytes32 bidId, uint price)
public
onlyIfWhitelisted("setCampaignPriceById",msg.sender)
onlyIfCampaignExists("setCampaignPriceById",bidId)
{
campaigns[bidId].setPrice(price);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the budget avaliable of a campaign
Based on the Campaign id, return the total value avaliable to pay for proofs of attention.
@param bidId Campaign id to which the query refers
@return { "budget" : "Total value (in wei) spendable in proof of attention rewards"}
*/
function getCampaignBudgetById(bytes32 bidId)
public
view
returns (uint budget) {
return campaigns[bidId].getBudget();
}
/**
@notice Set a new campaign budget
Based on the Campaign id, updates the total value avaliable for proof of attention
registrations. This function can only be executed by allowed addresses and emits a
CampaignUpdated event. This function does not transfer any funds as this contract only works
as a data repository, every logic needed will be processed in the Advertisement contract.
@param bidId Campaign id to which the query refers
@param newBudget New value for the total budget of the campaign
*/
function setCampaignBudgetById(bytes32 bidId, uint newBudget)
public
onlyIfCampaignExists("setCampaignBudgetById",bidId)
onlyIfWhitelisted("setCampaignBudgetById",msg.sender)
{
campaigns[bidId].setBudget(newBudget);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the start date of a campaign
Based on the Campaign id, return the value (in miliseconds) corresponding to the start Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "startDate" : "Start date (in miliseconds) of the campaign"}
*/
function getCampaignStartDateById(bytes32 bidId)
public
view
returns (uint startDate) {
return campaigns[bidId].getStartDate();
}
/**
@notice Set a new start date for a campaign
Based of the Campaign id, updates the start date of a campaign. This function can only be
executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param newStartDate New value (in miliseconds) for the start date of the campaign
*/
function setCampaignStartDateById(bytes32 bidId, uint newStartDate)
public
onlyIfCampaignExists("setCampaignStartDateById",bidId)
onlyIfWhitelisted("setCampaignStartDateById",msg.sender)
{
campaigns[bidId].setStartDate(newStartDate);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the end date of a campaign
Based on the Campaign id, return the value (in miliseconds) corresponding to the end Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "endDate" : "End date (in miliseconds) of the campaign"}
*/
function getCampaignEndDateById(bytes32 bidId)
public
view
returns (uint endDate) {
return campaigns[bidId].getEndDate();
}
/**
@notice Set a new end date for a campaign
Based of the Campaign id, updates the end date of a campaign. This function can only be
executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param newEndDate New value (in miliseconds) for the end date of the campaign
*/
function setCampaignEndDateById(bytes32 bidId, uint newEndDate)
public
onlyIfCampaignExists("setCampaignEndDateById",bidId)
onlyIfWhitelisted("setCampaignEndDateById",msg.sender)
{
campaigns[bidId].setEndDate(newEndDate);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get information regarding validity of a campaign.
Based on the Campaign id, return a boolean which represents a valid campaign if it has
the value of True else has the value of False.
@param bidId Campaign id to which the query refers
@return { "valid" : "Validity of the campaign"}
*/
function getCampaignValidById(bytes32 bidId)
public
view
returns (bool valid) {
return campaigns[bidId].getValidity();
}
/**
@notice Set a new campaign validity state.
Updates the validity of a campaign based on a campaign Id. This function can only be
executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param isValid New value for the campaign validity
*/
function setCampaignValidById(bytes32 bidId, bool isValid)
public
onlyIfCampaignExists("setCampaignValidById",bidId)
onlyIfWhitelisted("setCampaignValidById",msg.sender)
{
campaigns[bidId].setValidity(isValid);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the owner of a campaign
Based on the Campaign id, return the address of the campaign owner.
@param bidId Campaign id to which the query refers
@return { "campOwner" : "Address of the campaign owner" }
*/
function getCampaignOwnerById(bytes32 bidId)
public
view
returns (address campOwner) {
return campaigns[bidId].getOwner();
}
/**
@notice Set a new campaign owner
Based on the Campaign id, update the owner of the refered campaign. This function can only
be executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param newOwner New address to be the owner of the campaign
*/
function setCampaignOwnerById(bytes32 bidId, address newOwner)
public
onlyIfCampaignExists("setCampaignOwnerById",bidId)
onlyIfWhitelisted("setCampaignOwnerById",msg.sender)
{
campaigns[bidId].setOwner(newOwner);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Function to emit campaign updates
It emits a CampaignUpdated event with the new campaign information.
*/
function emitCampaignUpdated(CampaignLibrary.Campaign storage campaign) private {
emit CampaignUpdated(
campaign.getBidId(),
campaign.getPrice(),
campaign.getBudget(),
campaign.getStartDate(),
campaign.getEndDate(),
campaign.getValidity(),
campaign.getOwner()
);
}
/**
@notice Function to emit campaign creations
It emits a CampaignCreated event with the new campaign created.
*/
function emitCampaignCreated(CampaignLibrary.Campaign storage campaign) private {
emit CampaignCreated(
campaign.getBidId(),
campaign.getPrice(),
campaign.getBudget(),
campaign.getStartDate(),
campaign.getEndDate(),
campaign.getValidity(),
campaign.getOwner()
);
}
/**
@notice Internal function to set most recent bidId
This value is stored to avoid conflicts between
Advertisement contract upgrades.
@param _newBidId Newer bidId
*/
function setLastBidId(bytes32 _newBidId) internal {
lastBidId = _newBidId;
}
/**
@notice Returns the greatest BidId ever registered to the contract
@return { '_lastBidId' : 'Greatest bidId registered to the contract'}
*/
function getLastBidId()
external
returns (bytes32 _lastBidId){
return lastBidId;
}
}
contract ExtendedAdvertisementStorage is BaseAdvertisementStorage {
mapping (bytes32 => string) campaignEndPoints;
event ExtendedCampaignEndPointCreated(
bytes32 bidId,
string endPoint
);
event ExtendedCampaignEndPointUpdated(
bytes32 bidId,
string endPoint
);
/**
@notice Get a Campaign information
Based on a camapaign Id (bidId), returns all stored information for that campaign.
@param _campaignId Id of the campaign
@return {
"_bidId" : "Id of the campaign",
"_price" : "Value to pay for each proof-of-attention",
"_budget" : "Total value avaliable to be spent on the campaign",
"_startDate" : "Start date of the campaign (in miliseconds)",
"_endDate" : "End date of the campaign (in miliseconds)"
"_valid" : "Boolean informing if the campaign is valid",
"_campOwner" : "Address of the campaing's owner",
}
*/
function getCampaign(bytes32 _campaignId)
public
view
returns (
bytes32 _bidId,
uint _price,
uint _budget,
uint _startDate,
uint _endDate,
bool _valid,
address _campOwner
) {
CampaignLibrary.Campaign storage campaign = _getCampaign(_campaignId);
return (
campaign.getBidId(),
campaign.getPrice(),
campaign.getBudget(),
campaign.getStartDate(),
campaign.getEndDate(),
campaign.getValidity(),
campaign.getOwner()
);
}
/**
@notice Add or update a campaign information
Based on a campaign Id (bidId), a campaign can be created (if non existent) or updated.
This function can only be called by the set of allowed addresses registered earlier.
An event will be emited during this function's execution, a CampaignCreated and a
ExtendedCampaignEndPointCreated event if the campaign does not exist yet or a
CampaignUpdated and a ExtendedCampaignEndPointUpdated event if the campaign id is already
registered.
@param _bidId Id of the campaign
@param _price Value to pay for each proof-of-attention
@param _budget Total value avaliable to be spent on the campaign
@param _startDate Start date of the campaign (in miliseconds)
@param _endDate End date of the campaign (in miliseconds)
@param _valid Boolean informing if the campaign is valid
@param _owner Address of the campaing's owner
@param _endPoint URL of the signing serivce
*/
function setCampaign (
bytes32 _bidId,
uint _price,
uint _budget,
uint _startDate,
uint _endDate,
bool _valid,
address _owner,
string _endPoint
)
public
onlyIfWhitelisted("setCampaign",msg.sender) {
bool newCampaign = (getCampaignOwnerById(_bidId) == 0x0);
_setCampaign(_bidId, _price, _budget, _startDate, _endDate, _valid, _owner);
campaignEndPoints[_bidId] = _endPoint;
if(newCampaign){
emit ExtendedCampaignEndPointCreated(_bidId,_endPoint);
} else {
emit ExtendedCampaignEndPointUpdated(_bidId,_endPoint);
}
}
/**
@notice Get campaign signing web service endpoint
Get the end point to which the user should submit the proof of attention to be signed
@param _bidId Id of the campaign
@return { "_endPoint": "URL for the signing web service"}
*/
function getCampaignEndPointById(bytes32 _bidId) public returns (string _endPoint){
return campaignEndPoints[_bidId];
}
/**
@notice Set campaign signing web service endpoint
Sets the webservice's endpoint to which the user should submit the proof of attention
@param _bidId Id of the campaign
@param _endPoint URL for the signing web service
*/
function setCampaignEndPointById(bytes32 _bidId, string _endPoint)
public
onlyIfCampaignExists("setCampaignEndPointById",_bidId)
onlyIfWhitelisted("setCampaignEndPointById",msg.sender)
{
campaignEndPoints[_bidId] = _endPoint;
emit ExtendedCampaignEndPointUpdated(_bidId,_endPoint);
}
}
contract BaseAdvertisement is StorageUser,Ownable {
AppCoins appc;
BaseFinance advertisementFinance;
BaseAdvertisementStorage advertisementStorage;
mapping( bytes32 => mapping(address => uint256)) userAttributions;
bytes32[] bidIdList;
bytes32 lastBidId = 0x0;
/**
@notice Constructor function
Initializes contract with default validation rules
@param _addrAppc Address of the AppCoins (ERC-20) contract
@param _addrAdverStorage Address of the Advertisement Storage contract to be used
@param _addrAdverFinance Address of the Advertisement Finance contract to be used
*/
constructor(address _addrAppc, address _addrAdverStorage, address _addrAdverFinance) public {
appc = AppCoins(_addrAppc);
advertisementStorage = BaseAdvertisementStorage(_addrAdverStorage);
advertisementFinance = BaseFinance(_addrAdverFinance);
lastBidId = advertisementStorage.getLastBidId();
}
/**
@notice Upgrade finance contract used by this contract
This function is part of the upgrade mechanism avaliable to the advertisement contracts.
Using this function it is possible to update to a new Advertisement Finance contract without
the need to cancel avaliable campaigns.
Upgrade finance function can only be called by the Advertisement contract owner.
@param addrAdverFinance Address of the new Advertisement Finance contract
*/
function upgradeFinance (address addrAdverFinance) public onlyOwner("upgradeFinance") {
BaseFinance newAdvFinance = BaseFinance(addrAdverFinance);
address[] memory devList = advertisementFinance.getUserList();
for(uint i = 0; i < devList.length; i++){
uint balance = advertisementFinance.getUserBalance(devList[i]);
newAdvFinance.increaseBalance(devList[i],balance);
}
uint256 initBalance = appc.balanceOf(address(advertisementFinance));
advertisementFinance.transferAllFunds(address(newAdvFinance));
uint256 oldBalance = appc.balanceOf(address(advertisementFinance));
uint256 newBalance = appc.balanceOf(address(newAdvFinance));
require(initBalance == newBalance);
require(oldBalance == 0);
advertisementFinance = newAdvFinance;
}
/**
@notice Upgrade storage contract used by this contract
Upgrades Advertisement Storage contract addres with no need to redeploy
Advertisement contract. However every campaign in the old contract will
be canceled.
This function can only be called by the Advertisement contract owner.
@param addrAdverStorage Address of the new Advertisement Storage contract
*/
function upgradeStorage (address addrAdverStorage) public onlyOwner("upgradeStorage") {
for(uint i = 0; i < bidIdList.length; i++) {
cancelCampaign(bidIdList[i]);
}
delete bidIdList;
lastBidId = advertisementStorage.getLastBidId();
advertisementFinance.setAdsStorageAddress(addrAdverStorage);
advertisementStorage = BaseAdvertisementStorage(addrAdverStorage);
}
/**
@notice Get Advertisement Storage Address used by this contract
This function is required to upgrade Advertisement contract address on Advertisement
Finance contract. This function can only be called by the Advertisement Finance
contract registered in this contract.
@return {
"storageContract" : "Address of the Advertisement Storage contract used by this contract"
}
*/
function getStorageAddress() public view returns(address storageContract) {
require (msg.sender == address(advertisementFinance));
return address(advertisementStorage);
}
/**
@notice Creates a campaign
Method to create a campaign of user aquisition for a certain application.
This method will emit a Campaign Information event with every information
provided in the arguments of this method.
@param packageName Package name of the appication subject to the user aquisition campaign
@param countries Encoded list of 3 integers intended to include every
county where this campaign will be avaliable.
For more detain on this encoding refer to wiki documentation.
@param vercodes List of version codes to which the user aquisition campaign is applied.
@param price Value (in wei) the campaign owner pays for each proof-of-attention.
@param budget Total budget (in wei) the campaign owner will deposit
to pay for the proof-of-attention.
@param startDate Date (in miliseconds) on which the campaign will start to be
avaliable to users.
@param endDate Date (in miliseconds) on which the campaign will no longer be avaliable to users.
*/
function _generateCampaign (
string packageName,
uint[3] countries,
uint[] vercodes,
uint price,
uint budget,
uint startDate,
uint endDate)
internal returns (CampaignLibrary.Campaign memory) {
require(budget >= price);
require(endDate >= startDate);
//Transfers the budget to contract address
if(appc.allowance(msg.sender, address(this)) >= budget){
appc.transferFrom(msg.sender, address(advertisementFinance), budget);
advertisementFinance.increaseBalance(msg.sender,budget);
uint newBidId = bytesToUint(lastBidId);
lastBidId = uintToBytes(++newBidId);
CampaignLibrary.Campaign memory newCampaign;
newCampaign.price = price;
newCampaign.startDate = startDate;
newCampaign.endDate = endDate;
newCampaign.budget = budget;
newCampaign.owner = msg.sender;
newCampaign.valid = true;
newCampaign.bidId = lastBidId;
} else {
emit Error("createCampaign","Not enough allowance");
}
return newCampaign;
}
function _getStorage() internal returns (BaseAdvertisementStorage) {
return advertisementStorage;
}
function _getFinance() internal returns (BaseFinance) {
return advertisementFinance;
}
function _setUserAttribution(bytes32 _bidId,address _user,uint256 _attributions) internal{
userAttributions[_bidId][_user] = _attributions;
}
function getUserAttribution(bytes32 _bidId,address _user) internal returns (uint256) {
return userAttributions[_bidId][_user];
}
/**
@notice Cancel a campaign and give the remaining budget to the campaign owner
When a campaing owner wants to cancel a campaign, the campaign owner needs
to call this function. This function can only be called either by the campaign owner or by
the Advertisement contract owner. This function results in campaign cancelation and
retreival of the remaining budget to the respective campaign owner.
@param bidId Campaign id to which the cancelation referes to
*/
function cancelCampaign (bytes32 bidId) public {
address campaignOwner = getOwnerOfCampaign(bidId);
// Only contract owner or campaign owner can cancel a campaign
require(owner == msg.sender || campaignOwner == msg.sender);
uint budget = getBudgetOfCampaign(bidId);
advertisementFinance.withdraw(campaignOwner, budget);
advertisementStorage.setCampaignBudgetById(bidId, 0);
advertisementStorage.setCampaignValidById(bidId, false);
}
/**
@notice Get a campaign validity state
@param bidId Campaign id to which the query refers
@return { "state" : "Validity of the campaign"}
*/
function getCampaignValidity(bytes32 bidId) public view returns(bool state){
return advertisementStorage.getCampaignValidById(bidId);
}
/**
@notice Get the price of a campaign
Based on the Campaign id return the value paid for each proof of attention registered.
@param bidId Campaign id to which the query refers
@return { "price" : "Reward (in wei) for each proof of attention registered"}
*/
function getPriceOfCampaign (bytes32 bidId) public view returns(uint price) {
return advertisementStorage.getCampaignPriceById(bidId);
}
/**
@notice Get the start date of a campaign
Based on the Campaign id return the value (in miliseconds) corresponding to the start Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "startDate" : "Start date (in miliseconds) of the campaign"}
*/
function getStartDateOfCampaign (bytes32 bidId) public view returns(uint startDate) {
return advertisementStorage.getCampaignStartDateById(bidId);
}
/**
@notice Get the end date of a campaign
Based on the Campaign id return the value (in miliseconds) corresponding to the end Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "endDate" : "End date (in miliseconds) of the campaign"}
*/
function getEndDateOfCampaign (bytes32 bidId) public view returns(uint endDate) {
return advertisementStorage.getCampaignEndDateById(bidId);
}
/**
@notice Get the budget avaliable of a campaign
Based on the Campaign id return the total value avaliable to pay for proofs of attention.
@param bidId Campaign id to which the query refers
@return { "budget" : "Total value (in wei) spendable in proof of attention rewards"}
*/
function getBudgetOfCampaign (bytes32 bidId) public view returns(uint budget) {
return advertisementStorage.getCampaignBudgetById(bidId);
}
/**
@notice Get the owner of a campaign
Based on the Campaign id return the address of the campaign owner
@param bidId Campaign id to which the query refers
@return { "campaignOwner" : "Address of the campaign owner" }
*/
function getOwnerOfCampaign (bytes32 bidId) public view returns(address campaignOwner) {
return advertisementStorage.getCampaignOwnerById(bidId);
}
/**
@notice Get the list of Campaign BidIds registered in the contract
Returns the list of BidIds of the campaigns ever registered in the contract
@return { "bidIds" : "List of BidIds registered in the contract" }
*/
function getBidIdList() public view returns(bytes32[] bidIds) {
return bidIdList;
}
function _getBidIdList() internal returns(bytes32[] storage bidIds){
return bidIdList;
}
/**
@notice Check if a certain campaign is still valid
Returns a boolean representing the validity of the campaign
Has value of True if the campaign is still valid else has value of False
@param bidId Campaign id to which the query refers
@return { "valid" : "validity of the campaign" }
*/
function isCampaignValid(bytes32 bidId) public view returns(bool valid) {
uint startDate = advertisementStorage.getCampaignStartDateById(bidId);
uint endDate = advertisementStorage.getCampaignEndDateById(bidId);
bool validity = advertisementStorage.getCampaignValidById(bidId);
uint nowInMilliseconds = now * 1000;
return validity && startDate < nowInMilliseconds && endDate > nowInMilliseconds;
}
/**
@notice Returns the division of two numbers
Function used for division operations inside the smartcontract
@param numerator Numerator part of the division
@param denominator Denominator part of the division
@return { "result" : "Result of the division"}
*/
function division(uint numerator, uint denominator) public view returns (uint result) {
uint _quotient = numerator / denominator;
return _quotient;
}
/**
@notice Converts a uint256 type variable to a byte32 type variable
Mostly used internaly
@param i number to be converted
@return { "b" : "Input number converted to bytes"}
*/
function uintToBytes (uint256 i) public view returns(bytes32 b) {
b = bytes32(i);
}
function bytesToUint(bytes32 b) public view returns (uint)
{
return uint(b) & 0xfff;
}
}
contract Signature {
/**
@notice splitSignature
Based on a signature Sig (bytes32), returns the r, s, v
@param sig Signature
@return {
"uint8" : "recover Id",
"bytes32" : "Output of the ECDSA signature",
"bytes32" : "Output of the ECDSA signature",
}
*/
function splitSignature(bytes 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);
}
/**
@notice recoverSigner
Based on a message and signature returns the address
@param message Message
@param sig Signature
@return {
"address" : "Address of the private key that signed",
}
*/
function recoverSigner(bytes32 message, bytes sig)
public
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
}
contract BaseFinance is SingleAllowance {
mapping (address => uint256) balanceUsers;
mapping (address => bool) userExists;
address[] users;
address advStorageContract;
AppCoins appc;
/**
@notice Constructor function
Initializes contract with the AppCoins contract address
@param _addrAppc Address of the AppCoins (ERC-20) contract
*/
constructor (address _addrAppc)
public {
appc = AppCoins(_addrAppc);
advStorageContract = 0x0;
}
/**
@notice Sets the Storage contract address used by the allowed contract
The Storage contract address is mostly used as part of a failsafe mechanism to
ensure contract upgrades are executed using the same Storage
contract. This function returns every value of AppCoins stored in this contract to their
owners. This function can only be called by the
Finance contract owner or by the allowed contract registered earlier in
this contract.
@param _addrStorage Address of the new Storage contract
*/
function setAdsStorageAddress (address _addrStorage) external onlyOwnerOrAllowed {
reset();
advStorageContract = _addrStorage;
}
/**
@notice Sets the Advertisement contract address to allow calls from Advertisement contract
This function is used for upgrading the Advertisement contract without need to redeploy
Advertisement Finance and Advertisement Storage contracts. The function can only be called
by this contract's owner. During the update of the Advertisement contract address, the
contract for Advertisement Storage used by the new Advertisement contract is checked.
This function reverts if the new Advertisement contract does not use the same Advertisement
Storage contract earlier registered in this Advertisement Finance contract.
@param _addr Address of the newly allowed contract
*/
function setAllowedAddress (address _addr) public onlyOwner("setAllowedAddress") {
// Verify if the new Ads contract is using the same storage as before
if (allowedAddress != 0x0){
StorageUser storageUser = StorageUser(_addr);
address storageContract = storageUser.getStorageAddress();
require (storageContract == advStorageContract);
}
//Update contract
super.setAllowedAddress(_addr);
}
/**
@notice Increases balance of a user
This function can only be called by the registered Advertisement contract and increases the
balance of a specific user on this contract. This function does not transfer funds,
this step need to be done earlier by the Advertisement contract. This function can only be
called by the registered Advertisement contract.
@param _user Address of the user who will receive a balance increase
@param _value Value of coins to increase the user's balance
*/
function increaseBalance(address _user, uint256 _value)
public onlyAllowed{
if(userExists[_user] == false){
users.push(_user);
userExists[_user] = true;
}
balanceUsers[_user] += _value;
}
/**
@notice Transfers coins from a certain user to a destination address
Used to release a certain value of coins from a certain user to a destination address.
This function updates the user's balance in the contract. It can only be called by the
Advertisement contract registered.
@param _user Address of the user from which the value will be subtracted
@param _destination Address receiving the value transfered
@param _value Value to be transfered in AppCoins
*/
function pay(address _user, address _destination, uint256 _value) public onlyAllowed;
/**
@notice Withdraws a certain value from a user's balance back to the user's account
Can be called from the Advertisement contract registered or by this contract's owner.
@param _user Address of the user
@param _value Value to be transfered in AppCoins
*/
function withdraw(address _user, uint256 _value) public onlyOwnerOrAllowed;
/**
@notice Resets this contract and returns every amount deposited to each user registered
This function is used in case a contract reset is needed or the contract needs to be
deactivated. Thus returns every fund deposited to it's respective owner.
*/
function reset() public onlyOwnerOrAllowed {
for(uint i = 0; i < users.length; i++){
withdraw(users[i],balanceUsers[users[i]]);
}
}
/**
@notice Transfers all funds of the contract to a single address
This function is used for finance contract upgrades in order to be more cost efficient.
@param _destination Address receiving the funds
*/
function transferAllFunds(address _destination) public onlyAllowed {
uint256 balance = appc.balanceOf(address(this));
appc.transfer(_destination,balance);
}
/**
@notice Get balance of coins stored in the contract by a specific user
This function can only be called by the Advertisement contract
@param _user Developer's address
@return { '_balance' : 'Balance of coins deposited in the contract by the address' }
*/
function getUserBalance(address _user) public view onlyAllowed returns(uint256 _balance){
return balanceUsers[_user];
}
/**
@notice Get list of users with coins stored in the contract
This function can only be called by the Advertisement contract
@return { '_userList' : ' List of users registered in the contract'}
*/
function getUserList() public view onlyAllowed returns(address[] _userList){
return users;
}
}
contract ExtendedFinance is BaseFinance {
mapping ( address => uint256 ) rewardedBalance;
constructor(address _appc) public BaseFinance(_appc){
}
function pay(address _user, address _destination, uint256 _value)
public onlyAllowed{
require(balanceUsers[_user] >= _value);
balanceUsers[_user] -= _value;
rewardedBalance[_destination] += _value;
}
function withdraw(address _user, uint256 _value) public onlyOwnerOrAllowed {
require(balanceUsers[_user] >= _value);
balanceUsers[_user] -= _value;
appc.transfer(_user, _value);
}
/**
@notice Withdraws user's rewards
Function to transfer a certain user's rewards to his address
@param _user Address who's rewards will be withdrawn
@param _value Value of the withdraws which will be transfered to the user
*/
function withdrawRewards(address _user, uint256 _value) public onlyOwnerOrAllowed {
require(rewardedBalance[_user] >= _value);
rewardedBalance[_user] -= _value;
appc.transfer(_user, _value);
}
/**
@notice Get user's rewards balance
Function returning a user's rewards balance not yet withdrawn
@param _user Address of the user
@return { "_balance" : "Rewards balance of the user" }
*/
function getRewardsBalance(address _user) public onlyOwnerOrAllowed returns (uint256 _balance) {
return rewardedBalance[_user];
}
}
contract ExtendedAdvertisement is BaseAdvertisement, Whitelist, Signature {
event BulkPoARegistered(bytes32 bidId, bytes32 rootHash, bytes signedrootHash, uint256 newPoAs, uint256 convertedPoAs);
event CampaignInformation
(
bytes32 bidId,
address owner,
string ipValidator,
string packageName,
uint[3] countries,
uint[] vercodes,
string endpoint
);
constructor(address _addrAppc, address _addrAdverStorage, address _addrAdverFinance) public
BaseAdvertisement(_addrAppc,_addrAdverStorage,_addrAdverFinance) {
addAddressToWhitelist(msg.sender);
}
/**
@notice Creates an extebded campaign
Method to create an extended campaign of user aquisition for a certain application.
This method will emit a Campaign Information event with every information
provided in the arguments of this method.
@param packageName Package name of the appication subject to the user aquisition campaign
@param countries Encoded list of 3 integers intended to include every
county where this campaign will be avaliable.
For more detain on this encoding refer to wiki documentation.
@param vercodes List of version codes to which the user aquisition campaign is applied.
@param price Value (in wei) the campaign owner pays for each proof-of-attention.
@param budget Total budget (in wei) the campaign owner will deposit
to pay for the proof-of-attention.
@param startDate Date (in miliseconds) on which the campaign will start to be
avaliable to users.
@param endDate Date (in miliseconds) on which the campaign will no longer be avaliable to users.
@param endPoint URL of the signing serivce
*/
function createCampaign (
string packageName,
uint[3] countries,
uint[] vercodes,
uint price,
uint budget,
uint startDate,
uint endDate,
string endPoint)
external
{
CampaignLibrary.Campaign memory newCampaign = _generateCampaign(packageName, countries, vercodes, price, budget, startDate, endDate);
if(newCampaign.owner == 0x0){
// campaign was not generated correctly (revert)
return;
}
_getBidIdList().push(newCampaign.bidId);
ExtendedAdvertisementStorage(address(_getStorage())).setCampaign(
newCampaign.bidId,
newCampaign.price,
newCampaign.budget,
newCampaign.startDate,
newCampaign.endDate,
newCampaign.valid,
newCampaign.owner,
endPoint);
emit CampaignInformation(
newCampaign.bidId,
newCampaign.owner,
"", // ipValidator field
packageName,
countries,
vercodes,
endPoint);
}
/**
@notice Function to submit in bulk PoAs
This function can only be called by whitelisted addresses and provides a cost efficient
method to submit a batch of validates PoAs at once. This function emits a PoaRegistered
event containing the campaign id, root hash, signed root hash, number of new hashes since
the last submission and the effective number of conversions.
@param bidId Campaign id for which the Proof of attention root hash refferes to
@param rootHash Root hash of all submitted proof of attention to a given campaign
@param signedRootHash Root hash signed by the signing service of the campaign
@param newHashes Number of new proof of attention hashes since last submission
*/
function bulkRegisterPoA(bytes32 bidId, bytes32 rootHash, bytes signedRootHash, uint256 newHashes)
public
onlyIfWhitelisted("createCampaign",msg.sender)
{
address addressSig = recoverSigner(rootHash, signedRootHash);
if (msg.sender != addressSig) {
emit Error("bulkRegisterPoA","Invalid signature");
return;
}
uint price = _getStorage().getCampaignPriceById(bidId);
uint budget = _getStorage().getCampaignBudgetById(bidId);
address owner = _getStorage().getCampaignOwnerById(bidId);
uint maxConversions = division(budget,price);
uint effectiveConversions;
uint totalPay;
uint newBudget;
if (maxConversions >= newHashes){
effectiveConversions = newHashes;
} else {
effectiveConversions = maxConversions;
}
totalPay = price*effectiveConversions;
newBudget = budget - totalPay;
_getFinance().pay(owner,msg.sender,totalPay);
_getStorage().setCampaignBudgetById(bidId,newBudget);
if(newBudget < price){
_getStorage().setCampaignValidById(bidId,false);
}
emit BulkPoARegistered(bidId,rootHash,signedRootHash,newHashes,effectiveConversions);
}
/**
@notice Function to withdraw PoA convertions
This function is restricted to addresses allowed to submit bulk PoAs and enable those
addresses to withdraw funds previously collected by bulk PoA submissions
*/
function withdraw()
public
onlyIfWhitelisted("withdraw",msg.sender)
{
uint256 balance = ExtendedFinance(address(_getFinance())).getRewardsBalance(msg.sender);
ExtendedFinance(address(_getFinance())).withdrawRewards(msg.sender,balance);
}
/**
@notice Get user's balance of funds obtainded by rewards
Anyone can call this function and get the rewards balance of a certain user.
@param _user Address from which the balance refers to
@return { "_balance" : "" } */
function getRewardsBalance(address _user) public view returns (uint256 _balance) {
return ExtendedFinance(address(_getFinance())).getRewardsBalance(_user);
}
/**
@notice Returns the signing Endpoint of a camapign
Function returning the Webservice URL responsible for validating and signing a PoA
@param bidId Campaign id to which the Endpoint is associated
@return { "url" : "Validation and signature endpoint"}
*/
function getEndPointOfCampaign (bytes32 bidId) public view returns (string url){
return ExtendedAdvertisementStorage(address(_getStorage())).getCampaignEndPointById(bidId);
}
} | Transfers control of the contract to a newOwner. _newOwner The address to transfer ownership to./ | function _transferOwnership(address _newOwner) internal {
if(_newOwner == address(0)){
emit Error("transferOwnership","New owner's address needs to be different than 0x0");
return;
}
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
| 5,522,961 |
./partial_match/1/0xb00381dCAf378664b32596a612c2C83de4A81DC0/sources/FlamingFarm.sol | reward prediction at specific block | function getRewardPerBlock(uint blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return FFARMPerBlock;
}
return 0;
}
}
| 4,034,533 |
./partial_match/1/0x49c590F6a2dfB0f809E82B9e2BF788C0Dd1c31f9/sources/@mean-finance/swappers/solidity/contracts/extensions/GetBalances.sol | Returns the balance of each of the given tokens Meant to be used for off-chain queries _tokens The tokens to check the balance for, can be ERC20s or the protocol token return _balances The balances for the given tokens/ | function getBalances(address[] calldata _tokens) external view returns (TokenBalance[] memory _balances) {
_balances = new TokenBalance[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ) {
uint256 _balance = _tokens[i] == PROTOCOL_TOKEN ? address(this).balance : IERC20(_tokens[i]).balanceOf(address(this));
unchecked {
i++;
}
}
}
| 2,852,572 |
./full_match/4/0xa04ceD180D092D025A89c097F67eEA4106E0b970/sources/demoNtf/Maket.sol | Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./ | function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
| 681,251 |
./full_match/97/0xe22532F5EFF02CBBEb4598Af702B3FA1720a2075/sources/project_/contracts/factory.sol | Returns proxy address of a particular user's deal./ | function escrowProxyAddress(string memory _userId, string memory _dealId)
public
view
returns (address)
{
return userIdToDealIdToEscrowProxyAddr[_userId][_dealId];
}
| 3,274,542 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./UpgradeabilityProxy.sol";
/**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(
address _logic,
address _admin,
bytes memory _data
) public payable UpgradeabilityProxy(_logic, _data) {
assert(
ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)
);
_setAdmin(_admin);
}
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
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
internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(
newAdmin != address(0),
"Cannot change the admin of a proxy to the zero address"
);
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(
msg.sender != _admin(),
"Cannot call fallback function from the proxy admin"
);
super._willFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './Proxy.sol';
import '@openzeppelin/contracts/utils/Address.sol';
/**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
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 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
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 Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
// SPDX-License-Identifier: MIT
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) {
// 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.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
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.
*/
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
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
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) {
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;
/**
* @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;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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: MIT
pragma solidity ^0.6.0;
import "./ERC721.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC721 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 ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/Context.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.
*/
contract Pausable is Context {
/**
* @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.
*/
constructor () internal {
_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());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC1155.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC1155 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.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../GSN/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri) public {
_setURI(uri);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC1155.sol";
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(address account, uint256 id, uint256 value) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC1155/ERC1155.sol";
import "../token/ERC1155/ERC1155Burnable.sol";
import "../token/ERC1155/ERC1155Pausable.sol";
/**
* @dev {ERC1155} 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 other accounts.
*/
contract ERC1155PresetMinterPauser is Context, AccessControl, ERC1155Burnable, ERC1155Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
constructor(string memory uri) public ERC1155(uri) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual override(ERC1155, ERC1155Pausable)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/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;
/**
* @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.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../utils/Counters.sol";
import "../token/ERC721/ERC721.sol";
import "../token/ERC721/ERC721Burnable.sol";
import "../token/ERC721/ERC721Pausable.sol";
/**
* @dev {ERC721} 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
* - token ID and URI autogeneration
*
* 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 other accounts.
*/
contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnable, ERC721Pausable {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
Counters.Counter private _tokenIdTracker;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}.
*/
constructor(string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
_setBaseURI(baseURI);
}
/**
* @dev Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint");
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
_mint(to, _tokenIdTracker.current());
_tokenIdTracker.increment();
}
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC721.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Burnable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
contract TokenRecover is Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param tokenAddress The token contract address
* @param tokenAmount Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount)
public
onlyOwner
{
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
// Interface for our erc20 token
interface IMuseToken {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
external
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function mintingFinished() external view returns (bool);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
/*
* Deployment checklist::
* 1. Deploy all contracts
* 2. Give minter role to the claiming contract
* 3. Add objects (most basic cost 5 and give 1 day and 1 score)
* 4.
*/
// ERC721,
contract VNFT is
Ownable,
ERC721PresetMinterPauserAutoId,
TokenRecover,
ERC1155Holder
{
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
IMuseToken public muse;
struct VNFTObj {
address token;
uint256 id;
uint256 standard; //the type
}
// Mapping from token ID to NFT struct details
mapping(uint256 => VNFTObj) public vnftDetails;
// max dev allocation is 10% of total supply
uint256 public maxDevAllocation = 100000 * 10**18;
uint256 public devAllocation = 0;
// External NFTs
struct NFTInfo {
address token; // Address of LP token contract.
bool active;
uint256 standard; //the nft standard ERC721 || ERC1155
}
NFTInfo[] public supportedNfts;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
Counters.Counter private _itemIds;
// how many tokens to burn every time the VNFT is given an accessory, the remaining goes to the community and devs
uint256 public burnPercentage = 90;
uint256 public giveLifePrice = 5 * 10**18;
uint256 public fatalityPct = 60;
bool public gameStopped = false;
// mining tokens
mapping(uint256 => uint256) public lastTimeMined;
// VNFT properties
mapping(uint256 => uint256) public timeUntilStarving;
mapping(uint256 => uint256) public vnftScore;
mapping(uint256 => uint256) public timeVnftBorn;
// items/benefits for the VNFT could be anything in the future.
mapping(uint256 => uint256) public itemPrice;
mapping(uint256 => uint256) public itemPoints;
mapping(uint256 => string) public itemName;
mapping(uint256 => uint256) public itemTimeExtension;
// mapping(uint256 => address) public careTaker;
mapping(uint256 => mapping(address => address)) public careTaker;
event BurnPercentageChanged(uint256 percentage);
event ClaimedMiningRewards(uint256 who, address owner, uint256 amount);
event VnftConsumed(uint256 nftId, address giver, uint256 itemId);
event VnftMinted(address to);
event VnftFatalized(uint256 nftId, address killer);
event ItemCreated(uint256 id, string name, uint256 price, uint256 points);
event LifeGiven(address forSupportedNFT, uint256 id);
event Unwrapped(uint256 nftId);
event CareTakerAdded(uint256 nftId, address _to);
event CareTakerRemoved(uint256 nftId);
constructor(address _museToken)
public
ERC721PresetMinterPauserAutoId(
"VNFT",
"VNFT",
"https://gallery.verynify.io/api/"
)
{
_setupRole(OPERATOR_ROLE, _msgSender());
muse = IMuseToken(_museToken);
}
modifier notPaused() {
require(!gameStopped, "Contract is paused");
_;
}
modifier onlyOperator() {
require(
hasRole(OPERATOR_ROLE, _msgSender()),
"Roles: caller does not have the OPERATOR role"
);
_;
}
modifier onlyMinter() {
require(
hasRole(MINTER_ROLE, _msgSender()),
"Roles: caller does not have the MINTER role"
);
_;
}
function contractURI() public pure returns (string memory) {
return "https://gallery.verynifty.io/api";
}
// in case a bug happens or we upgrade to another smart contract
function pauseGame(bool _pause) external onlyOperator {
gameStopped = _pause;
}
function changeFatalityPct(uint256 _newpct) external onlyOperator {
fatalityPct = _newpct;
}
// change how much to burn on each buy and how much goes to community.
function changeBurnPercentage(uint256 percentage) external onlyOperator {
require(percentage <= 100);
burnPercentage = percentage;
emit BurnPercentageChanged(burnPercentage);
}
function changeGiveLifePrice(uint256 _newPrice) external onlyOperator {
giveLifePrice = _newPrice * 10**18;
}
function changeMaxDevAllocation(uint256 amount) external onlyOperator {
maxDevAllocation = amount;
}
function itemExists(uint256 itemId) public view returns (bool) {
if (bytes(itemName[itemId]).length > 0) {
return true;
}
}
// check that VNFT didn't starve
function isVnftAlive(uint256 _nftId) public view returns (bool) {
uint256 _timeUntilStarving = timeUntilStarving[_nftId];
if (_timeUntilStarving != 0 && _timeUntilStarving >= block.timestamp) {
return true;
}
}
function getVnftScore(uint256 _nftId) public view returns (uint256) {
return vnftScore[_nftId];
}
function getItemInfo(uint256 _itemId)
public
view
returns (
string memory _name,
uint256 _price,
uint256 _points,
uint256 _timeExtension
)
{
_name = itemName[_itemId];
_price = itemPrice[_itemId];
_timeExtension = itemTimeExtension[_itemId];
_points = itemPoints[_itemId];
}
function getVnftInfo(uint256 _nftId)
public
view
returns (
uint256 _vNFT,
bool _isAlive,
uint256 _score,
uint256 _level,
uint256 _expectedReward,
uint256 _timeUntilStarving,
uint256 _lastTimeMined,
uint256 _timeVnftBorn,
address _owner,
address _token,
uint256 _tokenId,
uint256 _fatalityReward
)
{
_vNFT = _nftId;
_isAlive = this.isVnftAlive(_nftId);
_score = this.getVnftScore(_nftId);
_level = this.level(_nftId);
_expectedReward = this.getRewards(_nftId);
_timeUntilStarving = timeUntilStarving[_nftId];
_lastTimeMined = lastTimeMined[_nftId];
_timeVnftBorn = timeVnftBorn[_nftId];
_owner = this.ownerOf(_nftId);
_token = vnftDetails[_nftId].token;
_tokenId = vnftDetails[_nftId].id;
_fatalityReward = getFatalityReward(_nftId);
}
function editCurves(
uint256 _la,
uint256 _lb,
uint256 _ra,
uint256 _rb
) external onlyOperator {
la = _la;
lb = _lb;
ra = _ra;
rb = _rb;
}
uint256 la = 2;
uint256 lb = 2;
uint256 ra = 6;
uint256 rb = 7;
// get the level the vNFT is on to calculate points
function level(uint256 tokenId) external view returns (uint256) {
// This is the formula L(x) = 2 * sqrt(x * 2)
uint256 _score = vnftScore[tokenId].div(100);
if (_score == 0) {
return 1;
}
uint256 _level = sqrtu(_score.mul(la));
return (_level.mul(lb));
}
// get the level the vNFT is on to calculate the token reward
function getRewards(uint256 tokenId) external view returns (uint256) {
// This is the formula to get token rewards R(level)=(level)*6/7+6
uint256 _level = this.level(tokenId);
if (_level == 1) {
return 6 ether;
}
_level = _level.mul(1 ether).mul(ra).div(rb);
return (_level.add(5 ether));
}
// edit specific item in case token goes up in value and the price for items gets to expensive for normal users.
function editItem(
uint256 _id,
uint256 _price,
uint256 _points,
string calldata _name,
uint256 _timeExtension
) external onlyOperator {
itemPrice[_id] = _price;
itemPoints[_id] = _points;
itemName[_id] = _name;
itemTimeExtension[_id] = _timeExtension;
}
//can mine once every 24 hours per token.
function claimMiningRewards(uint256 nftId) external notPaused {
require(isVnftAlive(nftId), "Your vNFT is dead, you can't mine");
require(
block.timestamp >= lastTimeMined[nftId].add(1 days) ||
lastTimeMined[nftId] == 0,
"Current timestamp is over the limit to claim the tokens"
);
require(
ownerOf(nftId) == msg.sender ||
careTaker[nftId][ownerOf(nftId)] == msg.sender,
"You must own the vNFT to claim rewards"
);
//reset last start mined so can't remine and cheat
lastTimeMined[nftId] = block.timestamp;
uint256 _reward = this.getRewards(nftId);
muse.mint(msg.sender, _reward);
emit ClaimedMiningRewards(nftId, msg.sender, _reward);
}
// Buy accesory to the VNFT
function buyAccesory(uint256 nftId, uint256 itemId) external notPaused {
require(itemExists(itemId), "This item doesn't exist");
uint256 amount = itemPrice[itemId];
require(
ownerOf(nftId) == msg.sender ||
careTaker[nftId][ownerOf(nftId)] == msg.sender,
"You must own the vNFT or be a care taker to buy items"
);
// require(isVnftAlive(nftId), "Your vNFT is dead");
uint256 amountToBurn = amount.mul(burnPercentage).div(100);
// recalculate time until starving
timeUntilStarving[nftId] = block.timestamp.add(
itemTimeExtension[itemId]
);
if (!isVnftAlive(nftId)) {
vnftScore[nftId] = itemPoints[itemId];
} else {
vnftScore[nftId] = vnftScore[nftId].add(itemPoints[itemId]);
}
// burn 90% so they go back to community mining and staking, and send 10% to devs
if (devAllocation <= maxDevAllocation) {
devAllocation = devAllocation.add(amount.sub(amountToBurn));
muse.transferFrom(msg.sender, address(this), amount);
// burn 90% of token, 10% stay for dev and community fund
muse.burn(amountToBurn);
} else {
muse.burnFrom(msg.sender, amount);
}
emit VnftConsumed(nftId, msg.sender, itemId);
}
function setBaseURI(string memory baseURI_) public onlyOperator {
_setBaseURI(baseURI_);
}
function mint(address player) public override onlyMinter {
//pet minted has 3 days until it starves at first
timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days);
timeVnftBorn[_tokenIds.current()] = block.timestamp;
vnftDetails[_tokenIds.current()] = VNFTObj(
address(this),
_tokenIds.current(),
721
);
super._mint(player, _tokenIds.current());
_tokenIds.increment();
emit VnftMinted(msg.sender);
}
// kill starverd NFT and get fatalityPct of his points.
function fatality(uint256 _deadId, uint256 _tokenId) external notPaused {
require(
!isVnftAlive(_deadId),
"The vNFT has to be starved to claim his points"
);
vnftScore[_tokenId] = vnftScore[_tokenId].add(
(vnftScore[_deadId].mul(fatalityPct).div(100))
);
vnftScore[_deadId] = 0;
delete vnftDetails[_deadId];
_burn(_deadId);
emit VnftFatalized(_deadId, msg.sender);
}
// Check how much score you'll get by fatality someone.
function getFatalityReward(uint256 _deadId) public view returns (uint256) {
if (isVnftAlive(_deadId)) {
return 0;
} else {
return (vnftScore[_deadId].mul(60).div(100));
}
}
// add items/accessories
function createItem(
string calldata name,
uint256 price,
uint256 points,
uint256 timeExtension
) external onlyOperator returns (bool) {
_itemIds.increment();
uint256 newItemId = _itemIds.current();
itemName[newItemId] = name;
itemPrice[newItemId] = price * 10**18;
itemPoints[newItemId] = points;
itemTimeExtension[newItemId] = timeExtension;
emit ItemCreated(newItemId, name, price, points);
}
// *****************************
// LOGIC FOR EXTERNAL NFTS
// ****************************
// support an external nft to mine rewards and play
function addNft(address _nftToken, uint256 _type) public onlyOperator {
supportedNfts.push(
NFTInfo({token: _nftToken, active: true, standard: _type})
);
}
function supportedNftLength() external view returns (uint256) {
return supportedNfts.length;
}
function updateSupportedNFT(
uint256 index,
bool _active,
address _address
) public onlyOperator {
supportedNfts[index].active = _active;
supportedNfts[index].token = _address;
}
// aka WRAP: lets give life to your erc721 token and make it fun to mint $muse!
function giveLife(
uint256 index,
uint256 _id,
uint256 nftType
) external notPaused {
uint256 amountToBurn = giveLifePrice.mul(burnPercentage).div(100);
if (devAllocation <= maxDevAllocation) {
devAllocation = devAllocation.add(giveLifePrice.sub(amountToBurn));
muse.transferFrom(msg.sender, address(this), giveLifePrice);
// burn 90% of token, 10% stay for dev and community fund
muse.burn(amountToBurn);
} else {
muse.burnFrom(msg.sender, giveLifePrice);
}
if (nftType == 721) {
IERC721(supportedNfts[index].token).transferFrom(
msg.sender,
address(this),
_id
);
} else if (nftType == 1155) {
IERC1155(supportedNfts[index].token).safeTransferFrom(
msg.sender,
address(this),
_id,
1, //the amount of tokens to transfer which always be 1
"0x0"
);
}
// mint a vNFT
vnftDetails[_tokenIds.current()] = VNFTObj(
supportedNfts[index].token,
_id,
nftType
);
timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days);
timeVnftBorn[_tokenIds.current()] = block.timestamp;
super._mint(msg.sender, _tokenIds.current());
_tokenIds.increment();
emit LifeGiven(supportedNfts[index].token, _id);
}
// unwrap your vNFT if it is not dead, and get back your original NFT
function unwrap(uint256 _vnftId) external {
require(isVnftAlive(_vnftId), "Your vNFT is dead, you can't unwrap it");
transferFrom(msg.sender, address(this), _vnftId);
VNFTObj memory details = vnftDetails[_vnftId];
timeUntilStarving[_vnftId] = 1;
vnftScore[_vnftId] = 0;
emit Unwrapped(_vnftId);
_withdraw(details.id, details.token, msg.sender, details.standard);
}
// withdraw dead wrapped NFTs or send them to the burn address.
function withdraw(
uint256 _id,
address _contractAddr,
address _to,
uint256 _type
) external onlyOperator {
_withdraw(_id, _contractAddr, _to, _type);
}
function _withdraw(
uint256 _id,
address _contractAddr,
address _to,
uint256 _type
) internal {
if (_type == 1155) {
IERC1155(_contractAddr).safeTransferFrom(
address(this),
_to,
_id,
1,
""
);
} else if (_type == 721) {
IERC721(_contractAddr).transferFrom(address(this), _to, _id);
}
}
// add care taker so in the future if vNFTs are sent to tokenizing platforms like niftex we can whitelist and the previous owner could still mine and do interesting stuff.
function addCareTaker(uint256 _tokenId, address _careTaker) external {
require(
hasRole(OPERATOR_ROLE, _msgSender()) ||
ownerOf(_tokenId) == msg.sender,
"Roles: caller does not have the OPERATOR role"
);
careTaker[_tokenId][msg.sender] = _careTaker;
emit CareTakerAdded(_tokenId, _careTaker);
}
function clearCareTaker(uint256 _tokenId) external {
require(
hasRole(OPERATOR_ROLE, _msgSender()) ||
ownerOf(_tokenId) == msg.sender,
"Roles: caller does not have the OPERATOR role"
);
delete careTaker[_tokenId][msg.sender];
emit CareTakerRemoved(_tokenId);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/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.
*/
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;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC1155Receiver.sol";
import "../../introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
constructor() public {
_registerInterface(
ERC1155Receiver(0).onERC1155Received.selector ^
ERC1155Receiver(0).onERC1155BatchReceived.selector
);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
contract TokenizeNFT is Ownable {
using SafeMath for uint256;
uint256 public currentRace = 0;
uint256 public constant maxParticipants = 10;
uint256 public minParticipant = 2;
struct Participant {
address nftContract;
uint256 nftId;
uint256 score;
address payable add;
}
mapping(uint256 => Participant[]) public participants;
mapping(uint256 => uint256) public raceParticipants;
mapping(uint256 => uint256) public raceMaxScore;
mapping(uint256 => uint256) public raceStart;
mapping(address => uint256) public whitelist;
uint256 public entryPrice = 1 ether / 10; //0.1 eth
uint256 public raceDuration = 2 * 1 hours;
address payable raceMaster = address(0);
event raceEnded(uint256 prize, address winner);
event participantEntered(uint256 bet, address who);
constructor() public {}
function settleRaceIfPossible() public {
if (
raceStart[currentRace] + raceDuration < now ||
raceParticipants[currentRace] >= maxParticipants
) {
uint256 maxScore = 0;
address payable winner = address(0);
// logic to distribute prize
for (uint256 i; i < participants[currentRace].length; i++) {
participants[currentRace][i].score = randomNumber(i, 100).mul(99 + whitelist[participants[currentRace][i].nftContract]).div(100); // Need to check this one more
if (participants[currentRace][i].score > maxScore) {
winner = participants[currentRace][i].add;
maxScore = participants[currentRace][i].score;
}
}
currentRace = currentRace.add(1);
winner.transfer(participants[currentRace].length.mul(entryPrice).mul(95).div(100)); //Check reentrency
raceMaster.transfer(participants[currentRace].length.mul(entryPrice).mul(5).div(100));
//Emit race won event
emit raceEnded(participants[currentRace].length.mul(entryPrice).mul(95).div(100), winner);
}
}
function joinRace(address _tokenAddress, uint256 _tokenId, uint256 _tokenType) public payable {
require(msg.value > entryPrice, "Not enough ETH to participate");
require(whitelist[_tokenAddress] > 0, "This NFT is not whitelisted");
if (_tokenType == 725) {
require(IERC721(_tokenAddress).ownerOf(_tokenId) == msg.sender, "You don't own the NFT");
} else if (_tokenType == 1155) {
require(IERC1155(_tokenAddress).balanceOf(msg.sender, _tokenId) > 0, "You don't own the NFT");
}
// check if nft is not already registered
participants[currentRace].push(Participant(_tokenAddress, _tokenId, 0, msg.sender));
settleRaceIfPossible(); // this will launch the previous race if possible
emit participantEntered(entryPrice, msg.sender);
}
function getRaceInfo(uint256 raceNumber)
public
view
returns (uint256 _raceNumber, uint256 _participantsCount, Participant[maxParticipants] memory _participants)
{
_raceNumber = raceNumber;
_participantsCount = participants[raceNumber].length;
for (uint256 i; i < participants[raceNumber].length; i++) {
_participants[i] = participants[raceNumber][i];
}
}
/* generates a number from 0 to 2^n based on the last n blocks */
function randomNumber(uint256 seed, uint256 max)
public
view
returns (uint256 _randomNumber)
{
uint256 n = 0;
for (uint256 i = 0; i < 2; i++) {
if (
uint256(
keccak256(
abi.encodePacked(blockhash(block.number - i - 1), seed)
)
) %
2 ==
0
) n += 2**i;
}
return n % max;
}
function max(uint a, uint b) private pure returns (uint) {
return a > b ? a : b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @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 ERC20Pausable is ERC20, Pausable {
/**
* @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");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
/**
* @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 other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: 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 virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @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 ERC20Burnable is Context, ERC20 {
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
contract MuseToken is ERC20PresetMinterPauser {
// Cap at 1 million
uint256 internal _cap = 1000000000 * 10**18;
constructor() public ERC20PresetMinterPauser("Muse", "MUSE") {}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
// change cap in case of decided by the community
function changeCap(uint256 _newCap) external {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have minter role to mint"
);
_cap = _newCap;
}
/**
* @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(ERC20PresetMinterPauser) {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// When minting tokens
require(
totalSupply().add(amount) <= _cap,
"ERC20Capped: cap exceeded"
);
}
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/presets/ERC1155PresetMinterPauser.sol";
contract NiftyAddons is ERC1155PresetMinterPauser {
constructor(string memory uri) public ERC1155PresetMinterPauser(uri) {}
}
/*pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
import "../interfaces/IMuseToken.sol";
import "../interfaces/IVNFT.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract TokenizeNFT is Ownable, ERC20PresetMinterPauser {
using SafeMath for uint256;
IVNFT public vnft;
IMuseToken public muse;
uint256 public premint;
address public creator;
uint256 public MAXTOKENS = 20;
uint256 public defaultGem;
uint256 public startSale;
uint256 public totalDays = 100;
uint256 public currentVNFT;
constructor(
IVNFT _vnft,
IMuseToken _muse,
string memory _tokenName,
string memory _tokenSymbol,
address _creator,
uint256 _premint,
uint256 _defaultGem
) public ERC20PresetMinterPauser(_tokenName, _tokenSymbol) {
vnft = _vnft;
muse = _muse;
creator = _creator;
premint = _premint * 1 ether;
defaultGem = _defaultGem;
if (premint > 0) {
mint(_creator, premint);
}
startSale = now;
muse.approve(address(vnft), MAX_INT);
vnft.mint(address(this));
currentVNFT = vnft.tokenOfOwnerByIndex(address(this), vnft.balanceOf(address(this)) - 1);
}
function join(address _to, uint256 _times) public {
require(_times < MAXTOKENS, "Can't whale in");
uint256 lastTimeMined = vnft.lastTimeMined(currentVNFT);
muse.transferFrom(
msg.sender,
address(this),
vnft.itemPrice(defaultGem) * _times
);
uint256 index = 0;
while (index < _times) {
vnft.buyAccesory(currentVNFT, defaultGem);
index = index + 1;
}
if (lastTimeMined + 1 days < now) {
vnft.claimMiningRewards(currentVNFT);
tickets = 2;
}
mint(_to, getJoinReturn(_times));
}
function getMuseValue(uint256 _quantity) public view returns (uint256) {
uint256 reward = totalSupply().div(_quantity);
return reward;
}
function getJoinReturn(uint256 _times) public pure returns (uint256) {
uint256 daysStarted = now.sub(startSale.div(1 days));
if (daysStarted >= totalDays) // The reward starts at toalDay (100) and decrease from 1 token everyday
{
return 1 * _times * 1 ether;
} else {
return ((totalDays - daysStarted) * 1 ether * _times);
}
}
function remove(address _to, uint256 _quantity) public {
_burn(msg.sender, _quantity);
muse.transfer(_to, getMuseValue(_quantity));
if (totalSupply() == 0 && vnft.isVnftAlive(currentVNFT)) {
vnft.safeTransferFrom(address(this), msg.sender, currentVNFT);
}
}
function max(uint256 a, uint256 b) private pure returns (uint256) {
return a > b ? a : b;
}
}*/
/*pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract Roles is AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR");
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(OPERATOR_ROLE, _msgSender());
}
modifier onlyMinter() {
require(
hasRole(MINTER_ROLE, _msgSender()),
"Roles: caller does not have the MINTER role"
);
_;
}
modifier onlyOperator() {
require(
hasRole(OPERATOR_ROLE, _msgSender()),
"Roles: caller does not have the OPERATOR role"
);
_;
}
}
interface IERC721 is IERC165 {
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) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId)
external
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function mint(address to) external;
}
// Stake to get vnfts
contract Pool is Roles {
using SafeMath for uint256;
IERC20 public token;
IERC20 public poolToken;
// min $muse amount required to stake
uint256 public minStake = 5 * 10**18;
uint256 public totalStaked;
bool public gameStopped = false;
mapping(address => uint256) public balance;
mapping(address => uint256) public lastUpdateTime;
mapping(address => uint256) public points;
event Staked(address who, uint256 amount);
event Withdrawal(address who, uint256 amount);
event VnftMinted(address to);
event StakeReqChanged(uint256 newAmount);
event PriceOfvnftChanged(uint256 newAmount);
constructor(address _token, address _poolToken) public {
poolToken = IERC20(_poolToken);
token = IERC20(_token);
}
modifier notPaused() {
require(!gameStopped, "Contract is paused");
_;
}
// in case a bug happens or we upgrade to another smart contract
function pauseGame(bool _pause) external onlyOperator {
gameStopped = _pause;
}
// changes stake requirement
function changeStakeReq(uint256 _newAmount) external onlyOperator {
minStake = _newAmount;
emit StakeReqChanged(_newAmount);
}
function changePriceOfNFT(uint256 _newAmount) external onlyOperator {
vnftPrice = _newAmount;
emit PriceOfvnftChanged(_newAmount);
}
modifier updateReward(address account) {
if (account != address(0)) {
points[account] = earned(account);
lastUpdateTime[account] = block.timestamp;
}
_;
}
//calculate how many points earned so far, this needs to give roughly 1 point a day per 5 tokens staked?.
function earned(address account) public view returns (uint256) {
uint256 blockTime = block.timestamp;
return
balance[account]
.mul(blockTime.sub(lastUpdateTime[account]).mul(2314814814000))
.div(1e18)
.add(points[account]);
}
function stake(uint256 _amount)
external
updateReward(msg.sender)
notPaused
{
require(
_amount >= minStake,
"You need to stake at least the min $muse"
);
// transfer tokens to this address to stake them
totalStaked = totalStaked.add(_amount);
balance[msg.sender] = balance[msg.sender].add(_amount);
poolToken.transferFrom(msg.sender, address(this), _amount);
emit Staked(msg.sender, _amount);
}
// withdraw part of your stake
function withdraw(uint256 amount) internal updateReward(msg.sender) {
require(amount > 0, "Amount can't be 0");
require(totalStaked >= amount);
points[msg.sender] = 0;
lastUpdateTime[msg.sender] = 0;
balance[msg.sender] = balance[msg.sender].sub(amount);
totalStaked = totalStaked.sub(amount);
// transfer erc20 back from the contract to the user
poolToken.transfer(msg.sender, amount);
emit Withdrawal(msg.sender, amount);
}
// withdraw all your amount staked
function exit() external notPaused {
withdraw(balance[msg.sender]);
}
//redeem a vNFT based on a set points price
function redeem() public updateReward(msg.sender) notPaused {
token.transfer(msg.sender, points[msg.sender]);
points[msg.sender] = 0;
}
}
*/
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
// @TODO DOn't Forget!!!
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "../interfaces/IMuseToken.sol";
import "../interfaces/IVNFT.sol";
// SPDX-License-Identifier: MIT
// Extending IERC1155 with mint and burn
interface IERC1155 is IERC165Upgradeable {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function mint(
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function mintBatch(
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function burn(
address account,
uint256 id,
uint256 value
) external;
function burnBatch(
address account,
uint256[] calldata ids,
uint256[] calldata values
) external;
}
contract VNFTx is Initializable, OwnableUpgradeable, ERC1155HolderUpgradeable {
/* START V1 STORAGE */
using SafeMathUpgradeable for uint256;
bool paused;
IVNFT public vnft;
IMuseToken public muse;
IERC1155 public addons;
uint256 public artistPct;
struct Addon {
string _type;
uint256 price;
uint256 requiredhp;
uint256 rarity;
string artistName;
address artistAddr;
uint256 quantity;
uint256 used;
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
mapping(uint256 => Addon) public addon;
mapping(uint256 => EnumerableSetUpgradeable.UintSet) private addonsConsumed;
EnumerableSetUpgradeable.UintSet lockedAddons;
//nftid to rarity points
mapping(uint256 => uint256) public rarity;
mapping(uint256 => uint256) public challengesUsed;
//!important, decides which gem score hp is based of
uint256 public healthGemScore;
uint256 public healthGemId;
uint256 public healthGemPrice;
uint256 public healthGemDays;
// premium hp is the min requirement for premium features.
uint256 public premiumHp;
uint256 public hpMultiplier;
uint256 public rarityMultiplier;
uint256 public addonsMultiplier;
//expected addons to be used for max hp
uint256 public expectedAddons;
//Expected rarity, this should be changed according to new addons introduced.
uint256 expectedRarity;
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _addonId;
/* END V1 STORAGE */
event BuyAddon(uint256 nftId, uint256 addon, address player);
event CreateAddon(
uint256 addonId,
string _type,
uint256 rarity,
uint256 quantity
);
event EditAddon(
uint256 addonId,
string _type,
uint256 price,
uint256 _quantity
);
event AttachAddon(uint256 addonId, uint256 nftId);
event RemoveAddon(uint256 addonId, uint256 nftId);
constructor() public {}
function initialize(
IVNFT _vnft,
IMuseToken _muse,
IERC1155 _addons
) public initializer {
vnft = _vnft;
muse = _muse;
addons = _addons;
paused = false;
artistPct = 5;
healthGemScore = 100;
healthGemId = 1;
healthGemPrice = 13 * 10**18;
healthGemDays = 1;
premiumHp = 90;
hpMultiplier = 70;
rarityMultiplier = 15;
addonsMultiplier = 15;
expectedAddons = 10;
expectedRarity = 300;
OwnableUpgradeable.__Ownable_init();
}
modifier tokenOwner(uint256 _id) {
require(
vnft.ownerOf(_id) == msg.sender,
"You must own the vNFT to use this feature"
);
_;
}
modifier notLocked(uint256 _id) {
require(!lockedAddons.contains(_id), "This addon is locked");
_;
}
modifier notPaused() {
require(!paused, "Contract paused!");
_;
}
// get how many addons a pet is using
function addonsBalanceOf(uint256 _nftId) public view returns (uint256) {
return addonsConsumed[_nftId].length();
}
// get a specific addon
function addonsOfNftByIndex(uint256 _nftId, uint256 _index)
public
view
returns (uint256)
{
return addonsConsumed[_nftId].at(_index);
}
function getHp(uint256 _nftId) public view returns (uint256) {
// A vnft need to get at least x score every two days to be healthy
uint256 currentScore = vnft.vnftScore(_nftId);
uint256 timeBorn = vnft.timeVnftBorn(_nftId);
uint256 daysLived = (now.sub(timeBorn)).div(1 days);
// multiply by healthy gem divided by 2 (every 2 days)
uint256 expectedScore = daysLived.mul(
healthGemScore.div(healthGemDays)
);
// get # of addons used
uint256 addonsUsed = addonsBalanceOf(_nftId);
if (
!vnft.isVnftAlive(_nftId) //not dead
) {
return 0;
} else if (daysLived < 1) {
return 70;
}
// here we get the % they get from score, from rarity, from used and then return based on their multiplier
uint256 fromScore = min(currentScore.mul(100).div(expectedScore), 100);
uint256 fromRarity = min(
rarity[_nftId].mul(100).div(expectedRarity),
100
);
uint256 fromUsed = min(addonsUsed.mul(100).div(expectedAddons), 100);
uint256 hp = (fromRarity.mul(rarityMultiplier))
.add(fromScore.mul(hpMultiplier))
.add(fromUsed.mul(addonsMultiplier));
//return hp
if (hp > 100) {
return 100;
} else {
return hp.div(100);
}
}
function getChallenges(uint256 _nftId) public view returns (uint256) {
if (vnft.level(_nftId) <= challengesUsed[_nftId]) {
return 0;
}
return vnft.level(_nftId).sub(challengesUsed[_nftId]);
}
function buyAddon(uint256 _nftId, uint256 addonId)
public
tokenOwner(_nftId)
notPaused
{
Addon storage _addon = addon[addonId];
require(
getHp(_nftId) >= _addon.requiredhp,
"Raise your HP to buy this addon"
);
require(
// @TODO double check < or <=
_addon.used < _addon.quantity,
"Addon not available"
);
_addon.used = _addon.used.add(1);
addonsConsumed[_nftId].add(addonId);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
uint256 artistCut = _addon.price.mul(artistPct).div(100);
muse.transferFrom(msg.sender, _addon.artistAddr, artistCut);
muse.burnFrom(msg.sender, _addon.price.sub(artistCut));
emit BuyAddon(_nftId, addonId, msg.sender);
}
function useAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notPaused
{
require(
!addonsConsumed[_nftId].contains(_addonID),
"Pet already has this addon"
);
require(
addons.balanceOf(msg.sender, _addonID) >= 1,
"!own the addon to use it"
);
Addon storage _addon = addon[_addonID];
require(
getHp(_nftId) >= _addon.requiredhp,
"Raise your HP to use this addon"
);
// _addon.used = _addon.used.add(1);
addonsConsumed[_nftId].add(_addonID);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
addons.safeTransferFrom(msg.sender, address(this), _addonID, 1, "0x0");
emit AttachAddon(_addonID, _nftId);
}
function transferAddon(
uint256 _nftId,
uint256 _addonID,
uint256 _toId
) external tokenOwner(_nftId) notLocked(_addonID) {
Addon storage _addon = addon[_addonID];
require(
getHp(_toId) >= _addon.requiredhp,
"Receiving vNFT with no enough HP"
);
emit RemoveAddon(_addonID, _nftId);
emit AttachAddon(_addonID, _toId);
addonsConsumed[_nftId].remove(_addonID);
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_toId].add(_addonID);
rarity[_toId] = rarity[_toId].add(_addon.rarity);
}
function removeAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notLocked(_addonID)
{
// maybe can take this out for gas and the .remove would throw if no addonid on user?
require(
addonsConsumed[_nftId].contains(_addonID),
"Pet doesn't have this addon"
);
Addon storage _addon = addon[_addonID];
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_nftId].remove(_addonID);
emit RemoveAddon(_addonID, _nftId);
addons.safeTransferFrom(address(this), msg.sender, _addonID, 1, "0x0");
}
// this is in case a dead pet addons is stuck in contract, we can use for diff cases.
function withdraw(uint256 _id, address _to) external onlyOwner {
addons.safeTransferFrom(address(this), _to, _id, 1, "");
}
function createAddon(
string calldata _type,
uint256 price,
uint256 _hp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
bool _lock
) external onlyOwner {
_addonId.increment();
uint256 newAddonId = _addonId.current();
addon[newAddonId] = Addon(
_type,
price,
_hp,
_rarity,
_artistName,
_artist,
_quantity,
0
);
addons.mint(address(this), newAddonId, _quantity, "");
if (_lock) {
lockAddon(newAddonId);
}
emit CreateAddon(newAddonId, _type, _rarity, _quantity);
}
function getVnftInfo(uint256 _nftId)
public
view
returns (
uint256 _vNFT,
uint256 _rarity,
uint256 _hp,
uint256 _addonsCount,
uint256[10] memory _addons
)
{
_vNFT = _nftId;
_rarity = rarity[_nftId];
_hp = getHp(_nftId);
_addonsCount = addonsBalanceOf(_nftId);
uint256 index = 0; // NOT FOR @JULES THIS IS HIGHLY EXPERIMENTAL NEED TO TEST
while (index < _addonsCount && index < 10) {
_addons[index] = (addonsConsumed[_nftId].at(index));
index = index + 1;
}
}
function editAddon(
uint256 _id,
string calldata _type,
uint256 price,
uint256 _requiredhp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
uint256 _used,
bool _lock
) external onlyOwner {
Addon storage _addon = addon[_id];
_addon._type = _type;
_addon.price = price * 10**18;
_addon.requiredhp = _requiredhp;
_addon.rarity = _rarity;
_addon.artistName = _artistName;
_addon.artistAddr = _artist;
if (_quantity > _addon.quantity) {
addons.mint(address(this), _id, _quantity.sub(_addon.quantity), "");
} else if (_quantity < _addon.quantity) {
addons.burn(address(this), _id, _addon.quantity - _quantity);
}
_addon.quantity = _quantity;
_addon.used = _used;
if (_lock) {
lockAddon(_id);
}
emit EditAddon(_id, _type, price, _quantity);
}
function lockAddon(uint256 _id) public onlyOwner {
lockedAddons.add(_id);
}
function unlockAddon(uint256 _id) public onlyOwner {
lockedAddons.remove(_id);
}
function setArtistPct(uint256 _newPct) external onlyOwner {
artistPct = _newPct;
}
function setHealthStrat(
uint256 _score,
uint256 _healthGemPrice,
uint256 _healthGemId,
uint256 _days,
uint256 _hpMultiplier,
uint256 _rarityMultiplier,
uint256 _expectedAddons,
uint256 _addonsMultiplier,
uint256 _expectedRarity,
uint256 _premiumHp
) external onlyOwner {
healthGemScore = _score;
healthGemPrice = _healthGemPrice;
healthGemId = _healthGemId;
healthGemDays = _days;
hpMultiplier = _hpMultiplier;
rarityMultiplier = _rarityMultiplier;
expectedAddons = _expectedAddons;
addonsMultiplier = _addonsMultiplier;
expectedRarity = _expectedRarity;
premiumHp = _premiumHp;
}
function pause(bool _paused) public onlyOwner {
paused = _paused;
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.24 <0.7.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;
/**
* @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 IERC165Upgradeable {
/**
* @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: MIT
pragma solidity ^0.6.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.
*/
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;
import "../math/SafeMathUpgradeable.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library CountersUpgradeable {
using SafeMathUpgradeable for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
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 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
pragma solidity ^0.6.0;
import "./ERC1155ReceiverUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable {
function __ERC1155Holder_init() internal initializer {
__ERC165_init_unchained();
__ERC1155Receiver_init_unchained();
__ERC1155Holder_init_unchained();
}
function __ERC1155Holder_init_unchained() internal initializer {
}
function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
uint256[50] private __gap;
}
// 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 EnumerableSetUpgradeable {
// 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));
}
}
pragma solidity ^0.6.0;
// Interface for our erc20 token
interface IMuseToken {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
external
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function mintingFinished() external view returns (bool);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/introspection/IERC165.sol";
interface IVNFT {
// function ownerOf(uint256 _tokenId) external view returns (address _owner);
function balanceOf(address owner) external view returns (uint256 balance);
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 id);
function totalSupply() external view returns (uint256);
function fatality(uint256 _deadId, uint256 _tokenId) external;
function buyAccesory(uint256 nftId, uint256 itemId) external;
function claimMiningRewards(uint256 nftId) external;
function addCareTaker(uint256 _tokenId, address _careTaker) external;
function careTaker(uint256 _tokenId, address _user)
external
view
returns (address _careTaker);
function ownerOf(uint256 _tokenId) external view returns (address _owner);
function itemPrice(uint256 itemId) external view returns (uint256 _amount);
function getRewards(uint256 tokenId) external view returns (uint256);
function isVnftAlive(uint256 _nftId) external view returns (bool);
function level(uint256 tokenId) external view returns (uint256);
function timeUntilStarving(uint256 _tokenId)
external
view
returns (uint256 _time);
function lastTimeMined(uint256 _tokenId)
external
view
returns (uint256 _time);
function getVnftInfo(uint256 _nftId)
external
view
returns (
uint256 _vNFT,
bool _isAlive,
uint256 _score,
uint256 _level,
uint256 _expectedReward,
uint256 _timeUntilStarving,
uint256 _lastTimeMined,
uint256 _timeVnftBorn,
address _owner,
address _token,
uint256 _tokenId,
uint256 _fatalityReward
);
function vnftScore(uint256 _tokenId) external view returns (uint256 _score);
function vnftScore(
uint256 _tokenId,
address //TODO What is this one?
) external view returns (uint256 _score);
function timeVnftBorn(uint256 _tokenId)
external
view
returns (uint256 _born);
function mint(address to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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;
import "./IERC1155ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable {
function __ERC1155Receiver_init() internal initializer {
__ERC165_init_unchained();
__ERC1155Receiver_init_unchained();
}
function __ERC1155Receiver_init_unchained() internal initializer {
_registerInterface(
ERC1155ReceiverUpgradeable(0).onERC1155Received.selector ^
ERC1155ReceiverUpgradeable(0).onERC1155BatchReceived.selector
);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
// @TODO DOn't Forget!!!
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "../interfaces/IMuseToken.sol";
import "../interfaces/IVNFT.sol";
// SPDX-License-Identifier: MIT
// Extending IERC1155 with mint and burn
interface IERC1155 is IERC165Upgradeable {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function mint(
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function mintBatch(
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function burn(
address account,
uint256 id,
uint256 value
) external;
function burnBatch(
address account,
uint256[] calldata ids,
uint256[] calldata values
) external;
}
contract VNFTxV5 is
Initializable,
OwnableUpgradeable,
ERC1155HolderUpgradeable
{
/* START V1 STORAGE */
using SafeMathUpgradeable for uint256;
bool paused;
IVNFT public vnft;
IMuseToken public muse;
IERC1155 public addons;
uint256 public artistPct;
struct Addon {
string _type;
uint256 price;
uint256 requiredhp;
uint256 rarity;
string artistName;
address artistAddr;
uint256 quantity;
uint256 used;
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
mapping(uint256 => Addon) public addon;
mapping(uint256 => EnumerableSetUpgradeable.UintSet) private addonsConsumed;
EnumerableSetUpgradeable.UintSet lockedAddons;
//nftid to rarity points
mapping(uint256 => uint256) public rarity;
mapping(uint256 => uint256) public challengesUsed;
//!important, decides which gem score hp is based of
uint256 public healthGemScore;
uint256 public healthGemId;
uint256 public healthGemPrice;
uint256 public healthGemDays;
// premium hp is the min requirement for premium features.
uint256 public premiumHp;
uint256 public hpMultiplier;
uint256 public rarityMultiplier;
uint256 public addonsMultiplier;
//expected addons to be used for max hp
uint256 public expectedAddons;
//Expected rarity, this should be changed according to new addons introduced.
uint256 expectedRarity;
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _addonId;
/* END V1 STORAGE */
uint256 cashbackPct;
event BuyAddon(uint256 nftId, uint256 addon, address player);
event CreateAddon(
uint256 addonId,
string _type,
uint256 rarity,
uint256 quantity
);
event EditAddon(
uint256 addonId,
string _type,
uint256 price,
uint256 _quantity
);
event AttachAddon(uint256 addonId, uint256 nftId);
event RemoveAddon(uint256 addonId, uint256 nftId);
/* EnD OF v3 Storage */
mapping(uint256 => uint256) public hpLostOnBattle;
mapping(uint256 => uint256) public timesAttacked;
mapping(address => uint256) public toReceiveCashback;
mapping(uint256 => uint256) private alreadyReceivedCashback;
event Cashback(uint256 nft, uint256 amount);
event Battle(uint256 winner, uint256 loser, uint256 museWon);
/*
** END OF V4 STORAGE
*/
mapping(uint256 => uint256) private petAlreadyReceivedCashback;
constructor() public {}
// function initialize(
// IVNFT _vnft,
// IMuseToken _muse,
// IERC1155 _addons
// ) public initializer {
// vnft = _vnft;
// muse = _muse;
// addons = _addons;
// paused = false;
// artistPct = 5;
// healthGemScore = 100;
// healthGemId = 1;
// healthGemPrice = 13 * 10**18;
// healthGemDays = 1;
// premiumHp = 90;
// hpMultiplier = 70;
// rarityMultiplier = 15;
// addonsMultiplier = 15;
// expectedAddons = 10;
// expectedRarity = 300;
// OwnableUpgradeable.__Ownable_init();
// cashbackPct = 40;
// }
modifier tokenOwner(uint256 _id) {
require(
vnft.ownerOf(_id) == msg.sender,
"3" //You must own the vNFT to use this feature
);
_;
}
modifier notLocked(uint256 _id) {
require(!lockedAddons.contains(_id), "1"); //This addon is locked
_;
}
modifier containsAddon(uint256 nftId, uint256 addonId) {
require(addonsConsumed[nftId].contains(addonId), "fail");
_;
}
modifier notPaused() {
require(!paused, "2"); //Contract paused!
_;
}
// get how many addons a pet is using
function addonsBalanceOf(uint256 _nftId) public view returns (uint256) {
return addonsConsumed[_nftId].length();
}
// get a specific addon
function addonsOfNftByIndex(uint256 _nftId, uint256 _index)
public
view
returns (uint256)
{
return addonsConsumed[_nftId].at(_index);
}
function getHp(uint256 _nftId) public view returns (uint256) {
// A vnft need to get at least x score every two days to be healthy
uint256 currentScore = vnft.vnftScore(_nftId);
uint256 daysLived = getDaysLived(_nftId);
// multiply by healthy gem divided by 2 (every 2 days)
uint256 expectedScore = daysLived
.mul(healthGemScore.div(healthGemDays))
.add(hpLostOnBattle[_nftId]);
// get # of addons used
uint256 addonsUsed = addonsBalanceOf(_nftId);
if (
!vnft.isVnftAlive(_nftId) //not dead
) {
return 0;
} else if (daysLived < 1) {
return 70;
}
// here we get the % they get from score, from rarity, from used and then return based on their multiplier
uint256 fromScore = min(currentScore.mul(100).div(expectedScore), 100);
uint256 fromRarity = min(
rarity[_nftId].mul(100).div(expectedRarity),
100
);
uint256 fromUsed = min(addonsUsed.mul(100).div(expectedAddons), 100);
uint256 hp = (fromRarity.mul(rarityMultiplier))
.add(fromScore.mul(hpMultiplier))
.add(fromUsed.mul(addonsMultiplier));
return min(hp.div(100), 100);
}
function getChallenges(uint256 _nftId) public view returns (uint256) {
if (vnft.level(_nftId) <= challengesUsed[_nftId]) {
return 0;
}
return vnft.level(_nftId).sub(challengesUsed[_nftId]);
}
function buyAddon(uint256 _nftId, uint256 addonId)
public
tokenOwner(_nftId)
notPaused()
{
Addon storage _addon = addon[addonId];
require(!addonsConsumed[_nftId].contains(addonId), "4"); // Pet already has this addon
require(getHp(_nftId) >= _addon.requiredhp, "5"); // Pet already has this addon
require(
_addon.used < _addon.quantity &&
addons.balanceOf(address(this), addonId) >= 1,
"6"
); //Addon not available
_addon.used = _addon.used.add(1);
addonsConsumed[_nftId].add(addonId);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
uint256 artistCut = _addon.price.mul(artistPct).div(100);
muse.transferFrom(msg.sender, _addon.artistAddr, artistCut);
muse.burnFrom(msg.sender, _addon.price.sub(artistCut));
emit BuyAddon(_nftId, addonId, msg.sender);
}
function useAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notPaused()
{
require(!addonsConsumed[_nftId].contains(_addonID), "4"); // Pet already has this addon
require(addons.balanceOf(msg.sender, _addonID) >= 1, "7"); //own the addon to use it
Addon storage _addon = addon[_addonID];
require(getHp(_nftId) >= _addon.requiredhp, "8"); // Raise your HP to use this addon
addonsConsumed[_nftId].add(_addonID);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
addons.safeTransferFrom(msg.sender, address(this), _addonID, 1, "");
emit AttachAddon(_addonID, _nftId);
}
function removeAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notLocked(_addonID)
containsAddon(_nftId, _addonID)
{
Addon storage _addon = addon[_addonID];
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_nftId].remove(_addonID);
emit RemoveAddon(_addonID, _nftId);
addons.safeTransferFrom(address(this), msg.sender, _addonID, 1, "");
}
function getDaysLived(uint256 _nftId) public view returns (uint256) {
return (now - vnft.timeVnftBorn(_nftId)) / 1 days;
}
function getAttackInfo(uint256 _nftId, uint256 _opponent)
public
view
returns (
uint256 oponentHp,
uint256 attackerHp,
uint256 successPercent,
uint256 estimatedReward
)
{
oponentHp = getHp(_opponent);
attackerHp = getHp(_nftId);
// The percentage of attack is weighted between your HP and the pet HP
// in the case where oponent as 20HP and attacker has 100
// the chance of winning is 3 times your HP: 3*100 out of 320 (sum of both HP and attacker hp*3)
successPercent = attackerHp.mul(3).mul(100).div(
oponentHp.add(attackerHp.mul(3))
);
estimatedReward = vnft
.level(_nftId)
.add(vnft.level(_opponent))
.mul(10)
.div(100);
if (estimatedReward <= 4) {
estimatedReward = 4;
}
}
// kill them all
function battle(uint256 _nftId, uint256 _opponent)
public
tokenOwner(_nftId)
containsAddon(_nftId, 4)
notPaused()
{
(
uint256 oponentHp,
uint256 attackerHp,
uint256 successPercent,
) = getAttackInfo(_nftId, _opponent);
require(vnft.ownerOf(_opponent) != msg.sender, "A"); // Can't atack yourself
// require x challenges and x hp or xx rarity for battles
require(
getChallenges(_nftId) >= 1 && attackerHp >= 70, //decide
"D"
); // can't challenge
require(timesAttacked[_opponent] <= 10, "E"); // This pet was attacked 10 times already
// require opponent to be of certain threshold 30?
require(oponentHp <= 90, "F"); // You can't attack this pet
challengesUsed[_nftId] = challengesUsed[_nftId] + 1;
timesAttacked[_opponent] = timesAttacked[_opponent] + 1;
//decide winner
uint256 loser;
uint256 winner;
if (randomNumber(_nftId + _opponent, 100) > successPercent) {
loser = _nftId;
winner = _opponent;
} else {
loser = _opponent;
winner = _nftId;
}
// then do all calcs based on winner, could be opponent or nftid
if (getHp(loser) < 20) {
// need 6 health gem score more to to expected score
hpLostOnBattle[loser] = hpLostOnBattle[loser].add(
healthGemScore * 6
);
} else if (getHp(loser) >= 20) {
// need 3 health gem score more to to expected score
hpLostOnBattle[loser] = hpLostOnBattle[loser].add(
healthGemScore * 3
);
}
uint256 museWon = 0;
if (winner == _nftId) {
// get 15% of level in muse
museWon = (vnft.level(winner).add(vnft.level(loser)).mul(10)) / 100;
if (museWon <= 4) {
museWon = 4;
}
muse.mint(vnft.ownerOf(winner), museWon * 10**18);
}
emit Battle(winner, loser, museWon);
}
function cashback(uint256 _nftId)
external
tokenOwner(_nftId)
containsAddon(_nftId, 1)
notPaused()
{
// have premium hp
require(getHp(_nftId) >= premiumHp, "H"); // Raise your hp to claim cashback
// didn't get cashback in last 7 days or first time (0)
require(
(toReceiveCashback[msg.sender] <= block.timestamp &&
petAlreadyReceivedCashback[_nftId] <= block.timestamp) ||
(toReceiveCashback[msg.sender] == 0 &&
petAlreadyReceivedCashback[_nftId] == 0),
"I"
); // You can't claim cahsback yet
petAlreadyReceivedCashback[_nftId] = block.timestamp.add(7 days);
uint256 currentScore = vnft.vnftScore(_nftId);
uint256 daysLived = getDaysLived(_nftId);
require(daysLived >= 14, "J"); // Lived at least 14 days for cashback
uint256 expectedScore = daysLived.mul(
healthGemScore.div(healthGemDays)
);
uint256 fromScore = min(currentScore.mul(100).div(expectedScore), 100);
uint256 museSpent = healthGemPrice.mul(7).mul(fromScore).div(100);
uint256 cashbackAmt = museSpent.mul(cashbackPct).div(100);
muse.mint(msg.sender, cashbackAmt);
alreadyReceivedCashback[_nftId] = alreadyReceivedCashback[_nftId].add(
cashbackAmt
);
emit Cashback(_nftId, cashbackAmt);
}
// this is in case a dead pet addons is stuck in contract, we can use for diff cases.
function withdraw(uint256 _id, address _to) external onlyOwner {
addons.safeTransferFrom(address(this), _to, _id, 1, "");
}
function createAddon(
string calldata _type,
uint256 price,
uint256 _hp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
bool _lock
) external onlyOwner {
_addonId.increment();
uint256 newAddonId = _addonId.current();
addon[newAddonId] = Addon(
_type,
price,
_hp,
_rarity,
_artistName,
_artist,
_quantity,
0
);
addons.mint(address(this), newAddonId, _quantity, "");
if (_lock) {
lockAddon(newAddonId);
}
emit CreateAddon(newAddonId, _type, _rarity, _quantity);
}
function getVnftInfo(uint256 _nftId)
public
view
returns (
uint256 _vNFT,
uint256 _rarity,
uint256 _hp,
uint256 _addonsCount,
uint256[10] memory _addons
)
{
_vNFT = _nftId;
_rarity = rarity[_nftId];
_hp = getHp(_nftId);
_addonsCount = addonsBalanceOf(_nftId);
uint256 index = 0;
while (index < _addonsCount && index < 10) {
_addons[index] = (addonsConsumed[_nftId].at(index));
index = index + 1;
}
}
function editAddon(
uint256 _id,
string calldata _type,
uint256 price,
uint256 _requiredhp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
uint256 _used,
bool _lock
) external onlyOwner {
Addon storage _addon = addon[_id];
_addon._type = _type;
_addon.price = price * 10**18;
_addon.requiredhp = _requiredhp;
_addon.rarity = _rarity;
_addon.artistName = _artistName;
_addon.artistAddr = _artist;
if (_quantity > _addon.quantity) {
addons.mint(address(this), _id, _quantity.sub(_addon.quantity), "");
} else if (_quantity < _addon.quantity) {
addons.burn(address(this), _id, _addon.quantity - _quantity);
}
_addon.quantity = _quantity;
_addon.used = _used;
if (_lock) {
lockAddon(_id);
}
emit EditAddon(_id, _type, price, _quantity);
}
function lockAddon(uint256 _id) public onlyOwner {
lockedAddons.add(_id);
}
function setHealthStrat(
uint256 _score,
uint256 _healthGemPrice,
uint256 _healthGemId,
uint256 _days,
uint256 _hpMultiplier,
uint256 _rarityMultiplier,
uint256 _expectedAddons,
uint256 _addonsMultiplier,
uint256 _expectedRarity,
uint256 _premiumHp,
uint256 _cashbackPct
) external onlyOwner {
healthGemScore = _score;
healthGemPrice = _healthGemPrice;
healthGemId = _healthGemId;
healthGemDays = _days;
hpMultiplier = _hpMultiplier;
rarityMultiplier = _rarityMultiplier;
expectedAddons = _expectedAddons;
addonsMultiplier = _addonsMultiplier;
expectedRarity = _expectedRarity;
premiumHp = _premiumHp;
cashbackPct = _cashbackPct;
}
function pause(bool _paused) public onlyOwner {
paused = _paused;
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
/* generates a number from 0 to 2^n based on the last n blocks */
function randomNumber(uint256 seed, uint256 max)
public
view
returns (uint256 _randomNumber)
{
uint256 n = 0;
for (uint256 i = 0; i < 5; i++) {
n += uint256(
keccak256(
abi.encodePacked(blockhash(block.number - i - 1), seed)
)
);
}
return (n * seed) % max;
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
// @TODO DOn't Forget!!!
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "../interfaces/IMuseToken.sol";
import "../interfaces/IVNFT.sol";
// SPDX-License-Identifier: MIT
// Extending IERC1155 with mint and burn
interface IERC1155 is IERC165Upgradeable {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function mint(
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function mintBatch(
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function burn(
address account,
uint256 id,
uint256 value
) external;
function burnBatch(
address account,
uint256[] calldata ids,
uint256[] calldata values
) external;
}
contract VNFTxV4 is
Initializable,
OwnableUpgradeable,
ERC1155HolderUpgradeable
{
/* START V1 STORAGE */
using SafeMathUpgradeable for uint256;
bool paused;
IVNFT public vnft;
IMuseToken public muse;
IERC1155 public addons;
uint256 public artistPct;
struct Addon {
string _type;
uint256 price;
uint256 requiredhp;
uint256 rarity;
string artistName;
address artistAddr;
uint256 quantity;
uint256 used;
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
mapping(uint256 => Addon) public addon;
mapping(uint256 => EnumerableSetUpgradeable.UintSet) private addonsConsumed;
EnumerableSetUpgradeable.UintSet lockedAddons;
//nftid to rarity points
mapping(uint256 => uint256) public rarity;
mapping(uint256 => uint256) public challengesUsed;
//!important, decides which gem score hp is based of
uint256 public healthGemScore;
uint256 public healthGemId;
uint256 public healthGemPrice;
uint256 public healthGemDays;
// premium hp is the min requirement for premium features.
uint256 public premiumHp;
uint256 public hpMultiplier;
uint256 public rarityMultiplier;
uint256 public addonsMultiplier;
//expected addons to be used for max hp
uint256 public expectedAddons;
//Expected rarity, this should be changed according to new addons introduced.
uint256 expectedRarity;
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _addonId;
/* END V1 STORAGE */
uint256 cashbackPct;
event BuyAddon(uint256 nftId, uint256 addon, address player);
event CreateAddon(
uint256 addonId,
string _type,
uint256 rarity,
uint256 quantity
);
event EditAddon(
uint256 addonId,
string _type,
uint256 price,
uint256 _quantity
);
event AttachAddon(uint256 addonId, uint256 nftId);
event RemoveAddon(uint256 addonId, uint256 nftId);
/* EnD OF v3 Storage */
mapping(uint256 => uint256) public hpLostOnBattle;
mapping(uint256 => uint256) public timesAttacked;
mapping(address => uint256) public toReceiveCashback;
mapping(uint256 => uint256) private alreadyReceivedCashback;
event Cashback(uint256 nft, uint256 amount);
event Battle(uint256 winner, uint256 loser, uint256 museWon);
/*
** END OF V4 STORAGE
*/
constructor() public {}
modifier tokenOwner(uint256 _id) {
require(
vnft.ownerOf(_id) == msg.sender,
"3" //You must own the vNFT to use this feature
);
_;
}
modifier notLocked(uint256 _id) {
require(!lockedAddons.contains(_id), "1"); //This addon is locked
_;
}
modifier containsAddon(uint256 nftId, uint256 addonId) {
require(addonsConsumed[nftId].contains(addonId), "fail");
_;
}
modifier notPaused() {
require(!paused, "2"); //Contract paused!
_;
}
// get how many addons a pet is using
function addonsBalanceOf(uint256 _nftId) public view returns (uint256) {
return addonsConsumed[_nftId].length();
}
// get a specific addon
function addonsOfNftByIndex(uint256 _nftId, uint256 _index)
public
view
returns (uint256)
{
return addonsConsumed[_nftId].at(_index);
}
function getHp(uint256 _nftId) public view returns (uint256) {
// A vnft need to get at least x score every two days to be healthy
uint256 currentScore = vnft.vnftScore(_nftId);
uint256 daysLived = getDaysLived(_nftId);
// multiply by healthy gem divided by 2 (every 2 days)
uint256 expectedScore = daysLived
.mul(healthGemScore.div(healthGemDays))
.add(hpLostOnBattle[_nftId]);
// get # of addons used
uint256 addonsUsed = addonsBalanceOf(_nftId);
if (
!vnft.isVnftAlive(_nftId) //not dead
) {
return 0;
} else if (daysLived < 1) {
return 70;
}
// here we get the % they get from score, from rarity, from used and then return based on their multiplier
uint256 fromScore = min(currentScore.mul(100).div(expectedScore), 100);
uint256 fromRarity = min(
rarity[_nftId].mul(100).div(expectedRarity),
100
);
uint256 fromUsed = min(addonsUsed.mul(100).div(expectedAddons), 100);
uint256 hp = (fromRarity.mul(rarityMultiplier))
.add(fromScore.mul(hpMultiplier))
.add(fromUsed.mul(addonsMultiplier));
return min(hp.div(100), 100);
}
function getChallenges(uint256 _nftId) public view returns (uint256) {
if (vnft.level(_nftId) <= challengesUsed[_nftId]) {
return 0;
}
return vnft.level(_nftId).sub(challengesUsed[_nftId]);
}
function buyAddon(uint256 _nftId, uint256 addonId)
public
tokenOwner(_nftId)
notPaused()
{
Addon storage _addon = addon[addonId];
require(!addonsConsumed[_nftId].contains(addonId), "4"); // Pet already has this addon
require(getHp(_nftId) >= _addon.requiredhp, "5"); // Pet already has this addon
require(
_addon.used < _addon.quantity &&
addons.balanceOf(address(this), addonId) >= 1,
"6"
); //Addon not available
_addon.used = _addon.used.add(1);
addonsConsumed[_nftId].add(addonId);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
uint256 artistCut = _addon.price.mul(artistPct).div(100);
muse.transferFrom(msg.sender, _addon.artistAddr, artistCut);
muse.burnFrom(msg.sender, _addon.price.sub(artistCut));
emit BuyAddon(_nftId, addonId, msg.sender);
}
function useAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notPaused()
{
require(!addonsConsumed[_nftId].contains(_addonID), "4"); // Pet already has this addon
require(addons.balanceOf(msg.sender, _addonID) >= 1, "7"); //own the addon to use it
Addon storage _addon = addon[_addonID];
require(getHp(_nftId) >= _addon.requiredhp, "8"); // Raise your HP to use this addon
addonsConsumed[_nftId].add(_addonID);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
addons.safeTransferFrom(msg.sender, address(this), _addonID, 1, "");
emit AttachAddon(_addonID, _nftId);
}
function removeAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notLocked(_addonID)
containsAddon(_nftId, _addonID)
{
Addon storage _addon = addon[_addonID];
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_nftId].remove(_addonID);
emit RemoveAddon(_addonID, _nftId);
addons.safeTransferFrom(address(this), msg.sender, _addonID, 1, "");
}
function getDaysLived(uint256 _nftId) public view returns (uint256) {
return (now - vnft.timeVnftBorn(_nftId)) / 1 days;
}
function getAttackInfo(uint256 _nftId, uint256 _opponent)
public
view
returns (
uint256 oponentHp,
uint256 attackerHp,
uint256 successPercent,
uint256 estimatedReward
)
{
oponentHp = getHp(_opponent);
attackerHp = getHp(_nftId);
// The percentage of attack is weighted between your HP and the pet HP
// in the case where oponent as 20HP and attacker has 100
// the chance of winning is 3 times your HP: 3*100 out of 320 (sum of both HP and attacker hp*3)
successPercent = attackerHp.mul(3).mul(100).div(
oponentHp.add(attackerHp.mul(3))
);
estimatedReward = vnft
.level(_nftId)
.add(vnft.level(_opponent))
.mul(10)
.div(100);
if (estimatedReward <= 4) {
estimatedReward = 4;
}
}
// kill them all
function battle(uint256 _nftId, uint256 _opponent)
public
tokenOwner(_nftId)
containsAddon(_nftId, 4)
notPaused()
{
(
uint256 oponentHp,
uint256 attackerHp,
uint256 successPercent,
) = getAttackInfo(_nftId, _opponent);
require(vnft.ownerOf(_opponent) != msg.sender, "A"); // Can't atack yourself
// require x challenges and x hp or xx rarity for battles
require(
getChallenges(_nftId) >= 1 && attackerHp >= 70, //decide
"D"
); // can't challenge
require(timesAttacked[_opponent] <= 10, "E"); // This pet was attacked 10 times already
// require opponent to be of certain threshold 30?
require(oponentHp <= 90, "F"); // You can't attack this pet
challengesUsed[_nftId] = challengesUsed[_nftId] + 1;
timesAttacked[_opponent] = timesAttacked[_opponent] + 1;
//decide winner
uint256 loser;
uint256 winner;
if (randomNumber(_nftId + _opponent, 100) > successPercent) {
loser = _nftId;
winner = _opponent;
} else {
loser = _opponent;
winner = _nftId;
}
// then do all calcs based on winner, could be opponent or nftid
if (getHp(loser) < 20) {
// need 6 health gem score more to to expected score
hpLostOnBattle[loser] = hpLostOnBattle[loser].add(
healthGemScore * 6
);
} else if (getHp(loser) >= 20) {
// need 3 health gem score more to to expected score
hpLostOnBattle[loser] = hpLostOnBattle[loser].add(
healthGemScore * 3
);
}
uint256 museWon = 0;
if (winner == _nftId) {
// get 15% of level in muse
museWon = (vnft.level(winner).add(vnft.level(loser)).mul(10)) / 100;
if (museWon <= 4) {
museWon = 4;
}
muse.mint(vnft.ownerOf(winner), museWon * 10**18);
}
emit Battle(winner, loser, museWon);
}
function cashback(uint256 _nftId)
external
tokenOwner(_nftId)
containsAddon(_nftId, 1)
notPaused()
{
// have premium hp
require(getHp(_nftId) >= premiumHp, "H"); // Raise your hp to claim cashback
// didn't get cashback in last 7 days or first time (0)
require(
toReceiveCashback[msg.sender] <= block.timestamp ||
toReceiveCashback[msg.sender] == 0,
"I"
); // You can't claim cahsback yet
toReceiveCashback[msg.sender] = block.timestamp.add(7 days);
uint256 currentScore = vnft.vnftScore(_nftId);
uint256 daysLived = getDaysLived(_nftId);
require(daysLived >= 14, "J"); // Lived at least 14 days for cashback
uint256 expectedScore = daysLived.mul(
healthGemScore.div(healthGemDays)
);
uint256 fromScore = min(currentScore.mul(100).div(expectedScore), 100);
uint256 museSpent = healthGemPrice.mul(7).mul(fromScore).div(100);
uint256 cashbackAmt = museSpent.mul(cashbackPct).div(100);
muse.mint(msg.sender, cashbackAmt);
alreadyReceivedCashback[_nftId] = alreadyReceivedCashback[_nftId].add(
cashbackAmt
);
emit Cashback(_nftId, cashbackAmt);
}
// this is in case a dead pet addons is stuck in contract, we can use for diff cases.
function withdraw(uint256 _id, address _to) external onlyOwner {
addons.safeTransferFrom(address(this), _to, _id, 1, "");
}
function createAddon(
string calldata _type,
uint256 price,
uint256 _hp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
bool _lock
) external onlyOwner {
_addonId.increment();
uint256 newAddonId = _addonId.current();
addon[newAddonId] = Addon(
_type,
price,
_hp,
_rarity,
_artistName,
_artist,
_quantity,
0
);
addons.mint(address(this), newAddonId, _quantity, "");
if (_lock) {
lockAddon(newAddonId);
}
emit CreateAddon(newAddonId, _type, _rarity, _quantity);
}
function getVnftInfo(uint256 _nftId)
public
view
returns (
uint256 _vNFT,
uint256 _rarity,
uint256 _hp,
uint256 _addonsCount,
uint256[10] memory _addons
)
{
_vNFT = _nftId;
_rarity = rarity[_nftId];
_hp = getHp(_nftId);
_addonsCount = addonsBalanceOf(_nftId);
uint256 index = 0;
while (index < _addonsCount && index < 10) {
_addons[index] = (addonsConsumed[_nftId].at(index));
index = index + 1;
}
}
function editAddon(
uint256 _id,
string calldata _type,
uint256 price,
uint256 _requiredhp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
uint256 _used,
bool _lock
) external onlyOwner {
Addon storage _addon = addon[_id];
_addon._type = _type;
_addon.price = price * 10**18;
_addon.requiredhp = _requiredhp;
_addon.rarity = _rarity;
_addon.artistName = _artistName;
_addon.artistAddr = _artist;
if (_quantity > _addon.quantity) {
addons.mint(address(this), _id, _quantity.sub(_addon.quantity), "");
} else if (_quantity < _addon.quantity) {
addons.burn(address(this), _id, _addon.quantity - _quantity);
}
_addon.quantity = _quantity;
_addon.used = _used;
if (_lock) {
lockAddon(_id);
}
emit EditAddon(_id, _type, price, _quantity);
}
function lockAddon(uint256 _id) public onlyOwner {
lockedAddons.add(_id);
}
function setHealthStrat(
uint256 _score,
uint256 _healthGemPrice,
uint256 _healthGemId,
uint256 _days,
uint256 _hpMultiplier,
uint256 _rarityMultiplier,
uint256 _expectedAddons,
uint256 _addonsMultiplier,
uint256 _expectedRarity,
uint256 _premiumHp,
uint256 _cashbackPct
) external onlyOwner {
healthGemScore = _score;
healthGemPrice = _healthGemPrice;
healthGemId = _healthGemId;
healthGemDays = _days;
hpMultiplier = _hpMultiplier;
rarityMultiplier = _rarityMultiplier;
expectedAddons = _expectedAddons;
addonsMultiplier = _addonsMultiplier;
expectedRarity = _expectedRarity;
premiumHp = _premiumHp;
cashbackPct = _cashbackPct;
}
function pause(bool _paused) public onlyOwner {
paused = _paused;
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
/* generates a number from 0 to 2^n based on the last n blocks */
function randomNumber(uint256 seed, uint256 max)
public
view
returns (uint256 _randomNumber)
{
uint256 n = 0;
for (uint256 i = 0; i < 5; i++) {
n += uint256(
keccak256(
abi.encodePacked(blockhash(block.number - i - 1), seed)
)
);
}
return (n * seed) % max;
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
// @TODO DOn't Forget!!!
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "../interfaces/IMuseToken.sol";
import "../interfaces/IVNFT.sol";
// SPDX-License-Identifier: MIT
// Extending IERC1155 with mint and burn
interface IERC1155 is IERC165Upgradeable {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function mint(
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function mintBatch(
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function burn(
address account,
uint256 id,
uint256 value
) external;
function burnBatch(
address account,
uint256[] calldata ids,
uint256[] calldata values
) external;
}
contract VNFTxV3 is
Initializable,
OwnableUpgradeable,
ERC1155HolderUpgradeable
{
/* START V1 STORAGE */
using SafeMathUpgradeable for uint256;
bool paused;
IVNFT public vnft;
IMuseToken public muse;
IERC1155 public addons;
uint256 public artistPct;
struct Addon {
string _type;
uint256 price;
uint256 requiredhp;
uint256 rarity;
string artistName;
address artistAddr;
uint256 quantity;
uint256 used;
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
mapping(uint256 => Addon) public addon;
mapping(uint256 => EnumerableSetUpgradeable.UintSet) private addonsConsumed;
EnumerableSetUpgradeable.UintSet lockedAddons;
//nftid to rarity points
mapping(uint256 => uint256) public rarity;
mapping(uint256 => uint256) public challengesUsed;
//!important, decides which gem score hp is based of
uint256 public healthGemScore;
uint256 public healthGemId;
uint256 public healthGemPrice;
uint256 public healthGemDays;
// premium hp is the min requirement for premium features.
uint256 public premiumHp;
uint256 public hpMultiplier;
uint256 public rarityMultiplier;
uint256 public addonsMultiplier;
//expected addons to be used for max hp
uint256 public expectedAddons;
//Expected rarity, this should be changed according to new addons introduced.
uint256 expectedRarity;
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _addonId;
/* END V1 STORAGE */
event BuyAddon(uint256 nftId, uint256 addon, address player);
event CreateAddon(
uint256 addonId,
string _type,
uint256 rarity,
uint256 quantity
);
event EditAddon(
uint256 addonId,
string _type,
uint256 price,
uint256 _quantity
);
event AttachAddon(uint256 addonId, uint256 nftId);
event RemoveAddon(uint256 addonId, uint256 nftId);
constructor() public {}
modifier tokenOwner(uint256 _id) {
require(
vnft.ownerOf(_id) == msg.sender,
"You must own the vNFT to use this feature"
);
_;
}
modifier notLocked(uint256 _id) {
require(!lockedAddons.contains(_id), "This addon is locked");
_;
}
modifier notPaused() {
require(!paused, "Contract paused!");
_;
}
// get how many addons a pet is using
function addonsBalanceOf(uint256 _nftId) public view returns (uint256) {
return addonsConsumed[_nftId].length();
}
// get a specific addon
function addonsOfNftByIndex(uint256 _nftId, uint256 _index)
public
view
returns (uint256)
{
return addonsConsumed[_nftId].at(_index);
}
function getHp(uint256 _nftId) public view returns (uint256) {
// A vnft need to get at least x score every two days to be healthy
uint256 currentScore = vnft.vnftScore(_nftId);
uint256 timeBorn = vnft.timeVnftBorn(_nftId);
uint256 daysLived = (now.sub(timeBorn)).div(1 days);
// multiply by healthy gem divided by 2 (every 2 days)
uint256 expectedScore = daysLived.mul(
healthGemScore.div(healthGemDays)
);
// get # of addons used
uint256 addonsUsed = addonsBalanceOf(_nftId);
if (
!vnft.isVnftAlive(_nftId) //not dead
) {
return 0;
} else if (daysLived < 1) {
return 70;
}
// here we get the % they get from score, from rarity, from used and then return based on their multiplier
uint256 fromScore = min(currentScore.mul(100).div(expectedScore), 100);
uint256 fromRarity = min(
rarity[_nftId].mul(100).div(expectedRarity),
100
);
uint256 fromUsed = min(addonsUsed.mul(100).div(expectedAddons), 100);
uint256 hp = (fromRarity.mul(rarityMultiplier))
.add(fromScore.mul(hpMultiplier))
.add(fromUsed.mul(addonsMultiplier));
return min(hp.div(100), 100);
}
function getChallenges(uint256 _nftId) public view returns (uint256) {
if (vnft.level(_nftId) <= challengesUsed[_nftId]) {
return 0;
}
return vnft.level(_nftId).sub(challengesUsed[_nftId]);
}
function buyAddon(uint256 _nftId, uint256 addonId)
public
tokenOwner(_nftId)
notPaused
{
Addon storage _addon = addon[addonId];
require(
getHp(_nftId) >= _addon.requiredhp,
"Raise your HP to buy this addon"
);
require(
// @TODO double check < or <=
_addon.used < _addon.quantity &&
addons.balanceOf(address(this), addonId) >= 1,
"Addon not available"
);
_addon.used = _addon.used.add(1);
addonsConsumed[_nftId].add(addonId);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
uint256 artistCut = _addon.price.mul(artistPct).div(100);
muse.transferFrom(msg.sender, _addon.artistAddr, artistCut);
muse.burnFrom(msg.sender, _addon.price.sub(artistCut));
emit BuyAddon(_nftId, addonId, msg.sender);
}
function useAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notPaused
{
require(
!addonsConsumed[_nftId].contains(_addonID),
"Pet already has this addon"
);
require(
addons.balanceOf(msg.sender, _addonID) >= 1,
"!own the addon to use it"
);
Addon storage _addon = addon[_addonID];
require(
getHp(_nftId) >= _addon.requiredhp,
"Raise your HP to use this addon"
);
addonsConsumed[_nftId].add(_addonID);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
addons.safeTransferFrom(msg.sender, address(this), _addonID, 1, "");
emit AttachAddon(_addonID, _nftId);
}
function transferAddon(
uint256 _nftId,
uint256 _addonID,
uint256 _toId
) external tokenOwner(_nftId) notLocked(_addonID) {
Addon storage _addon = addon[_addonID];
require(
getHp(_toId) >= _addon.requiredhp,
"Receiving vNFT with no enough HP"
);
emit RemoveAddon(_addonID, _nftId);
emit AttachAddon(_addonID, _toId);
addonsConsumed[_nftId].remove(_addonID);
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_toId].add(_addonID);
rarity[_toId] = rarity[_toId].add(_addon.rarity);
}
function removeAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notLocked(_addonID)
{
// maybe can take this out for gas and the .remove would throw if no addonid on user?
require(
addonsConsumed[_nftId].contains(_addonID),
"Pet doesn't have this addon"
);
Addon storage _addon = addon[_addonID];
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_nftId].remove(_addonID);
emit RemoveAddon(_addonID, _nftId);
addons.safeTransferFrom(address(this), msg.sender, _addonID, 1, "");
}
function removeMultiple(
uint256[] calldata nftIds,
uint256[] calldata addonIds
) external {
for (uint256 i = 0; i < addonIds.length; i++) {
removeAddon(nftIds[i], addonIds[i]);
}
}
function useMultiple(uint256[] calldata nftIds, uint256[] calldata addonIds)
external
{
for (uint256 i = 0; i < addonIds.length; i++) {
useAddon(nftIds[i], addonIds[i]);
}
}
function buyMultiple(uint256[] calldata nftIds, uint256[] calldata addonIds)
external
{
for (uint256 i = 0; i < addonIds.length; i++) {
useAddon(nftIds[i], addonIds[i]);
}
}
// this is in case a dead pet addons is stuck in contract, we can use for diff cases.
function withdraw(uint256 _id, address _to) external onlyOwner {
addons.safeTransferFrom(address(this), _to, _id, 1, "");
}
function createAddon(
string calldata _type,
uint256 price,
uint256 _hp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
bool _lock
) external onlyOwner {
_addonId.increment();
uint256 newAddonId = _addonId.current();
addon[newAddonId] = Addon(
_type,
price,
_hp,
_rarity,
_artistName,
_artist,
_quantity,
0
);
addons.mint(address(this), newAddonId, _quantity, "");
if (_lock) {
lockAddon(newAddonId);
}
emit CreateAddon(newAddonId, _type, _rarity, _quantity);
}
function getVnftInfo(uint256 _nftId)
public
view
returns (
uint256 _vNFT,
uint256 _rarity,
uint256 _hp,
uint256 _addonsCount,
uint256[10] memory _addons
)
{
_vNFT = _nftId;
_rarity = rarity[_nftId];
_hp = getHp(_nftId);
_addonsCount = addonsBalanceOf(_nftId);
uint256 index = 0; // NOT FOR @JULES THIS IS HIGHLY EXPERIMENTAL NEED TO TEST
while (index < _addonsCount && index < 10) {
_addons[index] = (addonsConsumed[_nftId].at(index));
index = index + 1;
}
}
function editAddon(
uint256 _id,
string calldata _type,
uint256 price,
uint256 _requiredhp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
uint256 _used,
bool _lock
) external onlyOwner {
Addon storage _addon = addon[_id];
_addon._type = _type;
_addon.price = price * 10**18;
_addon.requiredhp = _requiredhp;
_addon.rarity = _rarity;
_addon.artistName = _artistName;
_addon.artistAddr = _artist;
if (_quantity > _addon.quantity) {
addons.mint(address(this), _id, _quantity.sub(_addon.quantity), "");
} else if (_quantity < _addon.quantity) {
addons.burn(address(this), _id, _addon.quantity - _quantity);
}
_addon.quantity = _quantity;
_addon.used = _used;
if (_lock) {
lockAddon(_id);
}
emit EditAddon(_id, _type, price, _quantity);
}
function lockAddon(uint256 _id) public onlyOwner {
lockedAddons.add(_id);
}
function unlockAddon(uint256 _id) public onlyOwner {
lockedAddons.remove(_id);
}
function setArtistPct(uint256 _newPct) external onlyOwner {
artistPct = _newPct;
}
function setHealthStrat(
uint256 _score,
uint256 _healthGemPrice,
uint256 _healthGemId,
uint256 _days,
uint256 _hpMultiplier,
uint256 _rarityMultiplier,
uint256 _expectedAddons,
uint256 _addonsMultiplier,
uint256 _expectedRarity,
uint256 _premiumHp
) external onlyOwner {
healthGemScore = _score;
healthGemPrice = _healthGemPrice;
healthGemId = _healthGemId;
healthGemDays = _days;
hpMultiplier = _hpMultiplier;
rarityMultiplier = _rarityMultiplier;
expectedAddons = _expectedAddons;
addonsMultiplier = _addonsMultiplier;
expectedRarity = _expectedRarity;
premiumHp = _premiumHp;
}
function pause(bool _paused) public onlyOwner {
paused = _paused;
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
// @TODO DOn't Forget!!!
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "../interfaces/IMuseToken.sol";
import "../interfaces/IVNFT.sol";
// SPDX-License-Identifier: MIT
// Extending IERC1155 with mint and burn
interface IERC1155 is IERC165Upgradeable {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function mint(
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function mintBatch(
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
function burn(
address account,
uint256 id,
uint256 value
) external;
function burnBatch(
address account,
uint256[] calldata ids,
uint256[] calldata values
) external;
}
contract VNFTxV2 is
Initializable,
OwnableUpgradeable,
ERC1155HolderUpgradeable
{
/* START V1 STORAGE */
using SafeMathUpgradeable for uint256;
bool paused;
IVNFT public vnft;
IMuseToken public muse;
IERC1155 public addons;
uint256 public artistPct;
struct Addon {
string _type;
uint256 price;
uint256 requiredhp;
uint256 rarity;
string artistName;
address artistAddr;
uint256 quantity;
uint256 used;
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
mapping(uint256 => Addon) public addon;
mapping(uint256 => EnumerableSetUpgradeable.UintSet) private addonsConsumed;
EnumerableSetUpgradeable.UintSet lockedAddons;
//nftid to rarity points
mapping(uint256 => uint256) public rarity;
mapping(uint256 => uint256) public challengesUsed;
//!important, decides which gem score hp is based of
uint256 public healthGemScore;
uint256 public healthGemId;
uint256 public healthGemPrice;
uint256 public healthGemDays;
// premium hp is the min requirement for premium features.
uint256 public premiumHp;
uint256 public hpMultiplier;
uint256 public rarityMultiplier;
uint256 public addonsMultiplier;
//expected addons to be used for max hp
uint256 public expectedAddons;
//Expected rarity, this should be changed according to new addons introduced.
uint256 expectedRarity;
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _addonId;
/* END V1 STORAGE */
event BuyAddon(uint256 nftId, uint256 addon, address player);
event CreateAddon(
uint256 addonId,
string _type,
uint256 rarity,
uint256 quantity
);
event EditAddon(
uint256 addonId,
string _type,
uint256 price,
uint256 _quantity
);
event AttachAddon(uint256 addonId, uint256 nftId);
event RemoveAddon(uint256 addonId, uint256 nftId);
constructor() public {}
modifier tokenOwner(uint256 _id) {
require(
vnft.ownerOf(_id) == msg.sender,
"You must own the vNFT to use this feature"
);
_;
}
modifier notLocked(uint256 _id) {
require(!lockedAddons.contains(_id), "This addon is locked");
_;
}
modifier notPaused() {
require(!paused, "Contract paused!");
_;
}
// get how many addons a pet is using
function addonsBalanceOf(uint256 _nftId) public view returns (uint256) {
return addonsConsumed[_nftId].length();
}
// get a specific addon
function addonsOfNftByIndex(uint256 _nftId, uint256 _index)
public
view
returns (uint256)
{
return addonsConsumed[_nftId].at(_index);
}
function getHp(uint256 _nftId) public view returns (uint256) {
// A vnft need to get at least x score every two days to be healthy
uint256 currentScore = vnft.vnftScore(_nftId);
uint256 timeBorn = vnft.timeVnftBorn(_nftId);
uint256 daysLived = (now.sub(timeBorn)).div(1 days);
// multiply by healthy gem divided by 2 (every 2 days)
uint256 expectedScore = daysLived.mul(
healthGemScore.div(healthGemDays)
);
// get # of addons used
uint256 addonsUsed = addonsBalanceOf(_nftId);
if (
!vnft.isVnftAlive(_nftId) //not dead
) {
return 0;
} else if (daysLived < 1) {
return 70;
}
// here we get the % they get from score, from rarity, from used and then return based on their multiplier
uint256 fromScore = min(currentScore.mul(100).div(expectedScore), 100);
uint256 fromRarity = min(rarity[_nftId].mul(100).div(expectedRarity), 100);
uint256 fromUsed = min(addonsUsed.mul(100).div(expectedAddons), 100);
uint256 hp = (fromRarity.mul(rarityMultiplier))
.add(fromScore.mul(hpMultiplier))
.add(fromUsed.mul(addonsMultiplier));
return min(hp.div(100), 100);
}
function getChallenges(uint256 _nftId) public view returns (uint256) {
if (vnft.level(_nftId) <= challengesUsed[_nftId]) {
return 0;
}
return vnft.level(_nftId).sub(challengesUsed[_nftId]);
}
function buyAddon(uint256 _nftId, uint256 addonId)
public
tokenOwner(_nftId)
notPaused
{
Addon storage _addon = addon[addonId];
require(
getHp(_nftId) >= _addon.requiredhp,
"Raise your HP to buy this addon"
);
require(
// @TODO double check < or <=
_addon.used < addons.balanceOf(address(this), addonId),
"Addon not available"
);
_addon.used = _addon.used.add(1);
addonsConsumed[_nftId].add(addonId);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
uint256 artistCut = _addon.price.mul(artistPct).div(100);
muse.transferFrom(msg.sender, _addon.artistAddr, artistCut);
muse.burnFrom(msg.sender, _addon.price.sub(artistCut));
emit BuyAddon(_nftId, addonId, msg.sender);
}
function useAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notPaused
{
require(
!addonsConsumed[_nftId].contains(_addonID),
"Pet already has this addon"
);
require(
addons.balanceOf(msg.sender, _addonID) >= 1,
"!own the addon to use it"
);
Addon storage _addon = addon[_addonID];
require(
getHp(_nftId) >= _addon.requiredhp,
"Raise your HP to use this addon"
);
_addon.used = _addon.used.add(1);
addonsConsumed[_nftId].add(_addonID);
rarity[_nftId] = rarity[_nftId].add(_addon.rarity);
addons.safeTransferFrom(msg.sender, address(this), _addonID, 1, "0x0");
emit AttachAddon(_addonID, _nftId);
}
function transferAddon(
uint256 _nftId,
uint256 _addonID,
uint256 _toId
) external tokenOwner(_nftId) notLocked(_addonID) {
Addon storage _addon = addon[_addonID];
require(
getHp(_toId) >= _addon.requiredhp,
"Receiving vNFT with no enough HP"
);
emit RemoveAddon(_addonID, _nftId);
emit AttachAddon(_addonID, _toId);
addonsConsumed[_nftId].remove(_addonID);
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_toId].add(_addonID);
rarity[_toId] = rarity[_toId].add(_addon.rarity);
}
function removeAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notLocked(_addonID)
{
// maybe can take this out for gas and the .remove would throw if no addonid on user?
require(
addonsConsumed[_nftId].contains(_addonID),
"Pet doesn't have this addon"
);
Addon storage _addon = addon[_addonID];
rarity[_nftId] = rarity[_nftId].sub(_addon.rarity);
addonsConsumed[_nftId].remove(_addonID);
emit RemoveAddon(_addonID, _nftId);
addons.safeTransferFrom(address(this), msg.sender, _addonID, 1, "0x0");
}
function removeMultiple(
uint256[] calldata nftIds,
uint256[] calldata addonIds
) external {
for (uint256 i = 0; i < addonIds.length; i++) {
removeAddon(nftIds[i], addonIds[i]);
}
}
function useMultiple(uint256[] calldata nftIds, uint256[] calldata addonIds)
external
{
for (uint256 i = 0; i < addonIds.length; i++) {
useAddon(nftIds[i], addonIds[i]);
}
}
function buyMultiple(uint256[] calldata nftIds, uint256[] calldata addonIds)
external
{
for (uint256 i = 0; i < addonIds.length; i++) {
useAddon(nftIds[i], addonIds[i]);
}
}
// this is in case a dead pet addons is stuck in contract, we can use for diff cases.
function withdraw(uint256 _id, address _to) external onlyOwner {
addons.safeTransferFrom(address(this), _to, _id, 1, "");
}
function createAddon(
string calldata _type,
uint256 price,
uint256 _hp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
bool _lock
) external onlyOwner {
_addonId.increment();
uint256 newAddonId = _addonId.current();
addon[newAddonId] = Addon(
_type,
price,
_hp,
_rarity,
_artistName,
_artist,
_quantity,
0
);
addons.mint(address(this), newAddonId, _quantity, "");
if (_lock) {
lockAddon(newAddonId);
}
emit CreateAddon(newAddonId, _type, _rarity, _quantity);
}
function getVnftInfo(uint256 _nftId)
public
view
returns (
uint256 _vNFT,
uint256 _rarity,
uint256 _hp,
uint256 _addonsCount,
uint256[10] memory _addons
)
{
_vNFT = _nftId;
_rarity = rarity[_nftId];
_hp = getHp(_nftId);
_addonsCount = addonsBalanceOf(_nftId);
uint256 index = 0; // NOT FOR @JULES THIS IS HIGHLY EXPERIMENTAL NEED TO TEST
while (index < _addonsCount && index < 10) {
_addons[index] = (addonsConsumed[_nftId].at(index));
index = index + 1;
}
}
function editAddon(
uint256 _id,
string calldata _type,
uint256 price,
uint256 _requiredhp,
uint256 _rarity,
string calldata _artistName,
address _artist,
uint256 _quantity,
uint256 _used,
bool _lock
) external onlyOwner {
Addon storage _addon = addon[_id];
_addon._type = _type;
_addon.price = price * 10**18;
_addon.requiredhp = _requiredhp;
_addon.rarity = _rarity;
_addon.artistName = _artistName;
_addon.artistAddr = _artist;
if (_quantity > _addon.quantity) {
addons.mint(address(this), _id, _quantity.sub(_addon.quantity), "");
} else if (_quantity < _addon.quantity) {
addons.burn(address(this), _id, _addon.quantity - _quantity);
}
_addon.quantity = _quantity;
_addon.used = _used;
if (_lock) {
lockAddon(_id);
}
emit EditAddon(_id, _type, price, _quantity);
}
function lockAddon(uint256 _id) public onlyOwner {
lockedAddons.add(_id);
}
function unlockAddon(uint256 _id) public onlyOwner {
lockedAddons.remove(_id);
}
function setArtistPct(uint256 _newPct) external onlyOwner {
artistPct = _newPct;
}
function setHealthStrat(
uint256 _score,
uint256 _healthGemPrice,
uint256 _healthGemId,
uint256 _days,
uint256 _hpMultiplier,
uint256 _rarityMultiplier,
uint256 _expectedAddons,
uint256 _addonsMultiplier,
uint256 _expectedRarity,
uint256 _premiumHp
) external onlyOwner {
healthGemScore = _score;
healthGemPrice = _healthGemPrice;
healthGemId = _healthGemId;
healthGemDays = _days;
hpMultiplier = _hpMultiplier;
rarityMultiplier = _rarityMultiplier;
expectedAddons = _expectedAddons;
addonsMultiplier = _addonsMultiplier;
expectedRarity = _expectedRarity;
premiumHp = _premiumHp;
}
function pause(bool _paused) public onlyOwner {
paused = _paused;
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
| Buy accesory to the VNFT require(isVnftAlive(nftId), "Your vNFT is dead"); recalculate time until starving burn 90% of token, 10% stay for dev and community fund | function buyAccesory(uint256 nftId, uint256 itemId) external notPaused {
require(itemExists(itemId), "This item doesn't exist");
uint256 amount = itemPrice[itemId];
require(
ownerOf(nftId) == msg.sender ||
careTaker[nftId][ownerOf(nftId)] == msg.sender,
"You must own the vNFT or be a care taker to buy items"
);
uint256 amountToBurn = amount.mul(burnPercentage).div(100);
timeUntilStarving[nftId] = block.timestamp.add(
itemTimeExtension[itemId]
);
if (!isVnftAlive(nftId)) {
vnftScore[nftId] = itemPoints[itemId];
vnftScore[nftId] = vnftScore[nftId].add(itemPoints[itemId]);
}
if (devAllocation <= maxDevAllocation) {
devAllocation = devAllocation.add(amount.sub(amountToBurn));
muse.transferFrom(msg.sender, address(this), amount);
muse.burn(amountToBurn);
muse.burnFrom(msg.sender, amount);
}
emit VnftConsumed(nftId, msg.sender, itemId);
}
| 9,860,685 |
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import 'OpenZeppelin/[email protected]/contracts/ownership/Ownable.sol';
import 'OpenZeppelin/[email protected]/contracts/math/SafeMath.sol';
// import 'Uniswap/[email protected]/contracts/interfaces/IUniswapV2Pair.sol';
import './interfaces/IMdexPair.sol';
import './GoblinConfig.sol';
import './PriceOracle.sol';
import './SafeToken.sol';
interface IPancakeswapGoblin {
function lpToken() external view returns (IMdexPair);
}
contract PancakeswapGoblinConfig is Ownable, GoblinConfig {
using SafeToken for address;
using SafeMath for uint;
struct Config {
bool acceptDebt;
uint64 workFactor;
uint64 killFactor;
uint64 maxPriceDiff;
}
PriceOracle public oracle;
mapping(address => Config) public goblins;
constructor(PriceOracle _oracle) public {
oracle = _oracle;
}
/// @dev Set oracle address. Must be called by owner.
function setOracle(PriceOracle _oracle) external onlyOwner {
oracle = _oracle;
}
/// @dev Set goblin configurations. Must be called by owner.
function setConfigs(address[] calldata addrs, Config[] calldata configs) external onlyOwner {
uint len = addrs.length;
require(configs.length == len, 'bad len');
for (uint idx = 0; idx < len; idx++) {
goblins[addrs[idx]] = Config({
acceptDebt: configs[idx].acceptDebt,
workFactor: configs[idx].workFactor,
killFactor: configs[idx].killFactor,
maxPriceDiff: configs[idx].maxPriceDiff
});
}
}
/// @dev Return whether the given goblin is stable, presumably not under manipulation.
function isStable(address goblin) public view returns (bool) {
IMdexPair lp = IPancakeswapGoblin(goblin).lpToken();
address token0 = lp.token0();
address token1 = lp.token1();
// 1. Check that reserves and balances are consistent (within 1%)
(uint r0, uint r1, ) = lp.getReserves();
uint t0bal = token0.balanceOf(address(lp));
uint t1bal = token1.balanceOf(address(lp));
require(t0bal.mul(100) <= r0.mul(101), 'bad t0 balance');
require(t1bal.mul(100) <= r1.mul(101), 'bad t1 balance');
// 2. Check that price is in the acceptable range
(uint price, uint lastUpdate) = oracle.getPrice(token0, token1);
require(lastUpdate >= now - 7 days, 'price too stale');
uint lpPrice = r1.mul(1e18).div(r0);
uint maxPriceDiff = goblins[goblin].maxPriceDiff;
require(lpPrice <= price.mul(maxPriceDiff).div(10000), 'price too high');
require(lpPrice >= price.mul(10000).div(maxPriceDiff), 'price too low');
// 3. Done
return true;
}
/// @dev Return whether the given goblin accepts more debt.
function acceptDebt(address goblin) external view returns (bool) {
require(isStable(goblin), '!stable');
return goblins[goblin].acceptDebt;
}
/// @dev Return the work factor for the goblin + BNB debt, using 1e4 as denom.
function workFactor(
address goblin,
uint /* debt */
) external view returns (uint) {
require(isStable(goblin), '!stable');
return uint(goblins[goblin].workFactor);
}
/// @dev Return the kill factor for the goblin + BNB debt, using 1e4 as denom.
function killFactor(
address goblin,
uint /* debt */
) external view returns (uint) {
require(isStable(goblin), '!stable');
return uint(goblins[goblin].killFactor);
}
}
| Return the work factor for the goblin + BNB debt, using 1e4 as denom. | function workFactor(
address goblin,
uint /* debt */
) external view returns (uint) {
require(isStable(goblin), '!stable');
return uint(goblins[goblin].workFactor);
}
| 5,429,070 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "../interfaces/IERC721PortalFacet.sol";
import "../libraries/LibDiamond.sol";
import "../libraries/LibGovernance.sol";
import "../libraries/LibFeeCalculator.sol";
import "../libraries/LibPayment.sol";
import "../libraries/LibRouter.sol";
import "../libraries/LibERC721.sol";
import "../WrappedERC721.sol";
contract ERC721PortalFacet is IERC721PortalFacet, ERC721Holder {
using SafeERC20 for IERC20;
/// @notice Mints wrapped `_tokenId` to the `receiver` address.
/// Must be authorised by the configured supermajority threshold of `signatures` from the `members` set.
/// @param _sourceChain ID of the source chain
/// @param _transactionId The source transaction ID + log index
/// @param _wrappedToken The address of the wrapped ERC-721 token on the current chain
/// @param _tokenId The target token ID
/// @param _metadata The tokenID's metadata, used to be queried as ERC-721.tokenURI
/// @param _receiver The address of the receiver on this chain
/// @param _signatures The array of signatures from the members, authorising the operation
function mintERC721(
uint256 _sourceChain,
bytes memory _transactionId,
address _wrappedToken,
uint256 _tokenId,
string memory _metadata,
address _receiver,
bytes[] calldata _signatures
) external override whenNotPaused {
LibGovernance.validateSignaturesLength(_signatures.length);
bytes32 ethHash = computeMessage(
_sourceChain,
block.chainid,
_transactionId,
_wrappedToken,
_tokenId,
_metadata,
_receiver
);
LibRouter.Storage storage rs = LibRouter.routerStorage();
require(
!rs.hashesUsed[ethHash],
"ERC721PortalFacet: transaction already submitted"
);
validateAndStoreTx(ethHash, _signatures);
WrappedERC721(_wrappedToken).safeMint(_receiver, _tokenId, _metadata);
emit MintERC721(
_sourceChain,
_transactionId,
_wrappedToken,
_tokenId,
_metadata,
_receiver
);
}
/// @notice Burns `_tokenId` of `wrappedToken` and initializes a portal transaction to the target chain
/// The wrappedToken's fee payment is transferred to the contract upon execution.
/// @param _targetChain The target chain to which the wrapped asset will be transferred
/// @param _wrappedToken The address of the wrapped token
/// @param _tokenId The tokenID of `wrappedToken` to burn
/// @param _paymentToken The current payment token
/// @param _fee The fee amount for the wrapped token's payment token
/// @param _receiver The address of the receiver on the target chain
function burnERC721(
uint256 _targetChain,
address _wrappedToken,
uint256 _tokenId,
address _paymentToken,
uint256 _fee,
bytes memory _receiver
) public override whenNotPaused {
address payment = LibERC721.erc721Payment(_wrappedToken);
require(
LibPayment.containsPaymentToken(payment),
"ERC721PortalFacet: payment token not supported"
);
require(
_paymentToken == payment,
"ERC721PortalFacet: _paymentToken does not match the current set payment token"
);
uint256 currentFee = LibERC721.erc721Fee(_wrappedToken);
require(
_fee == currentFee,
"ERC721PortalFacet: _fee does not match current set payment token fee"
);
IERC20(payment).safeTransferFrom(msg.sender, address(this), _fee);
LibFeeCalculator.accrueFee(payment, _fee);
WrappedERC721(_wrappedToken).burn(_tokenId);
emit BurnERC721(
_targetChain,
_wrappedToken,
_tokenId,
_receiver,
payment,
_fee
);
}
/// @notice Sets ERC-721 contract payment token and fee amount
/// @param _erc721 The target ERC-721 contract
/// @param _payment The target payment token
/// @param _fee The fee required upon every portal transfer
function setERC721Payment(
address _erc721,
address _payment,
uint256 _fee
) external override {
LibDiamond.enforceIsContractOwner();
require(
LibPayment.containsPaymentToken(_payment),
"ERC721PortalFacet: payment token not supported"
);
LibERC721.setERC721PaymentFee(_erc721, _payment, _fee);
emit SetERC721Payment(_erc721, _payment, _fee);
}
/// @notice Returns the payment token for an ERC-721
/// @param _erc721 The address of the ERC-721 Token
function erc721Payment(address _erc721)
external
view
override
returns (address)
{
return LibERC721.erc721Payment(_erc721);
}
/// @notice Returns the payment fee for an ERC-721
/// @param _erc721 The address of the ERC-721 Token
function erc721Fee(address _erc721)
external
view
override
returns (uint256)
{
return LibERC721.erc721Fee(_erc721);
}
/// @notice Computes the bytes32 ethereum signed message hash for signatures
/// @param _sourceChain The chain where the bridge transaction was initiated from
/// @param _targetChain The target chain of the bridge transaction.
/// Should always be the current chainId.
/// @param _transactionId The transaction ID of the bridge transaction
/// @param _token The address of the token on this chain
/// @param _tokenId The token ID for the _token
/// @param _metadata The metadata for the token ID
/// @param _receiver The receiving address on the current chain
function computeMessage(
uint256 _sourceChain,
uint256 _targetChain,
bytes memory _transactionId,
address _token,
uint256 _tokenId,
string memory _metadata,
address _receiver
) internal pure returns (bytes32) {
bytes32 hashedData = keccak256(
abi.encode(
_sourceChain,
_targetChain,
_transactionId,
_token,
_tokenId,
_metadata,
_receiver
)
);
return ECDSA.toEthSignedMessageHash(hashedData);
}
/// @notice Validates the signatures and the data and saves the transaction
/// @param _ethHash The hashed data
/// @param _signatures The array of signatures from the members, authorising the operation
function validateAndStoreTx(bytes32 _ethHash, bytes[] calldata _signatures)
internal
{
LibRouter.Storage storage rs = LibRouter.routerStorage();
LibGovernance.validateSignatures(_ethHash, _signatures);
rs.hashesUsed[_ethHash] = true;
}
/// Modifier to make a function callable only when the contract is not paused
modifier whenNotPaused() {
LibGovernance.enforceNotPaused();
_;
}
}
| Computes the bytes32 ethereum signed message hash for signatures _sourceChain The chain where the bridge transaction was initiated from _targetChain The target chain of the bridge transaction. Should always be the current chainId. _transactionId The transaction ID of the bridge transaction _token The address of the token on this chain _tokenId The token ID for the _token _metadata The metadata for the token ID _receiver The receiving address on the current chain | function computeMessage(
uint256 _sourceChain,
uint256 _targetChain,
bytes memory _transactionId,
address _token,
uint256 _tokenId,
string memory _metadata,
address _receiver
) internal pure returns (bytes32) {
bytes32 hashedData = keccak256(
abi.encode(
_sourceChain,
_targetChain,
_transactionId,
_token,
_tokenId,
_metadata,
_receiver
)
);
return ECDSA.toEthSignedMessageHash(hashedData);
}
| 1,786,071 |
/**
* ________ __ __ __ __ _______ __ __ __ __
* | \| \ | \ | \ | \ | \ | \ | \ | \ | \
* | $$$$$$$$ \$$ _______ ____| $$ _| $$_ | $$____ ______ | $$$$$$$\ ______ | $$____ | $$____ \$$ _| $$_
* | $$__ | \| \ / $$ | $$ \ | $$ \ / \ | $$__| $$ | \ | $$ \ | $$ \ | \| $$ \
* | $$ \ | $$| $$$$$$$\| $$$$$$$ \$$$$$$ | $$$$$$$\| $$$$$$\ | $$ $$ \$$$$$$\| $$$$$$$\| $$$$$$$\| $$ \$$$$$$
* | $$$$$ | $$| $$ | $$| $$ | $$ | $$ __ | $$ | $$| $$ $$ | $$$$$$$\ / $$| $$ | $$| $$ | $$| $$ | $$ __
* | $$ | $$| $$ | $$| $$__| $$ | $$| \| $$ | $$| $$$$$$$$ | $$ | $$| $$$$$$$| $$__/ $$| $$__/ $$| $$ | $$| \
* | $$ | $$| $$ | $$ \$$ $$ \$$ $$| $$ | $$ \$$ \ | $$ | $$ \$$ $$| $$ $$| $$ $$| $$ \$$ $$
* \$$ \$$ \$$ \$$ \$$$$$$$ \$$$$ \$$ \$$ \$$$$$$$ \$$ \$$ \$$$$$$$ \$$$$$$$ \$$$$$$$ \$$ \$$$$
*
*
* ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐
* ║ ║├┤ ├┤ ││ │├─┤│ │https://findtherabbit.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤
* ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘
*/
// File: contracts/lib/SafeMath.sol
pragma solidity 0.5.4;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
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;
}
}
// File: contracts/Messages.sol
pragma solidity 0.5.4;
/**
* EIP712 Ethereum typed structured data hashing and signing
*/
contract Messages {
struct AcceptGame {
uint256 bet;
bool isHost;
address opponentAddress;
bytes32 hashOfMySecret;
bytes32 hashOfOpponentSecret;
}
struct SecretData {
bytes32 salt;
uint8 secret;
}
/**
* Domain separator encoding per EIP 712.
* keccak256(
* "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
* )
*/
bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472;
/**
* AcceptGame struct type encoding per EIP 712
* keccak256(
* "AcceptGame(uint256 bet,bool isHost,address opponentAddress,bytes32 hashOfMySecret,bytes32 hashOfOpponentSecret)"
* )
*/
bytes32 private constant ACCEPTGAME_TYPEHASH = 0x5ceee84403c984fbd9fb4ebf11b09c4f28f87290116c8b7f24a3e2a89d26588f;
/**
* Domain separator per EIP 712
*/
bytes32 public DOMAIN_SEPARATOR;
/**
* @notice Calculates acceptGameHash according to EIP 712.
* @param _acceptGame AcceptGame instance to hash.
* @return bytes32 EIP 712 hash of _acceptGame.
*/
function _hash(AcceptGame memory _acceptGame) internal pure returns (bytes32) {
return keccak256(abi.encode(
ACCEPTGAME_TYPEHASH,
_acceptGame.bet,
_acceptGame.isHost,
_acceptGame.opponentAddress,
_acceptGame.hashOfMySecret,
_acceptGame.hashOfOpponentSecret
));
}
/**
* @notice Calculates secretHash according to EIP 712.
* @param _salt Salt of the gamer.
* @param _secret Secret of the gamer.
*/
function _hashOfSecret(bytes32 _salt, uint8 _secret) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_salt, _secret));
}
/**
* @return the recovered address from the signature
*/
function _recoverAddress(
bytes32 messageHash,
bytes memory signature
)
internal
view
returns (address)
{
bytes32 r;
bytes32 s;
bytes1 v;
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := mload(add(signature, 0x60))
}
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
messageHash
));
return ecrecover(digest, uint8(v), r, s);
}
/**
* @return the address of the gamer signing the AcceptGameMessage
*/
function _getSignerAddress(
uint256 _value,
bool _isHost,
address _opponentAddress,
bytes32 _hashOfMySecret,
bytes32 _hashOfOpponentSecret,
bytes memory signature
)
internal
view
returns (address playerAddress)
{
AcceptGame memory message = AcceptGame({
bet: _value,
isHost: _isHost,
opponentAddress: _opponentAddress,
hashOfMySecret: _hashOfMySecret,
hashOfOpponentSecret: _hashOfOpponentSecret
});
bytes32 messageHash = _hash(message);
playerAddress = _recoverAddress(messageHash, signature);
}
}
// File: contracts/Ownable.sol
pragma solidity 0.5.4;
/**
* @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 () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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(), "not owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public 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;
}
}
// File: contracts/Claimable.sol
pragma solidity 0.5.4;
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "not pending owner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(_owner, pendingOwner);
_owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/lib/ERC20Basic.sol
pragma solidity 0.5.4;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
}
// File: contracts/FindTheRabbit.sol
pragma solidity 0.5.4;
/**
* @title FindTheRabbit
* @dev Base game contract
*/
contract FindTheRabbit is Messages, Claimable {
using SafeMath for uint256;
enum GameState {
Invalid, // Default value for a non-created game
HostBetted, // A player, who initiated an offchain game and made a bet
JoinBetted, // A player, who joined the game and made a bet
Filled, // Both players made bets
DisputeOpenedByHost, // Dispute is opened by the initiating player
DisputeOpenedByJoin, // Dispute is opened by the joining player
DisputeWonOnTimeoutByHost, // Dispute is closed on timeout and the prize was taken by the initiating player
DisputeWonOnTimeoutByJoin, // Dispute is closed on timeout and the prize was taken by the joining player
CanceledByHost, // The joining player has not made a bet and the game is closed by the initiating player
CanceledByJoin, // The initiating player has not made a bet and the game is closed by the joining player
WonByHost, // The initiating has won the game
WonByJoin // The joining player has won the game
}
//Event is triggered after both players have placed their bets
event GameCreated(
address indexed host,
address indexed join,
uint256 indexed bet,
bytes32 gameId,
GameState state
);
//Event is triggered after the first bet has been placed
event GameOpened(bytes32 gameId, address indexed player);
//Event is triggered after the game has been closed
event GameCanceled(bytes32 gameId, address indexed player, address indexed opponent);
/**
* @dev Event triggered after after opening a dispute
* @param gameId 32 byte game identifier
* @param disputeOpener is a player who opened a dispute
* @param defendant is a player against whom a dispute is opened
*/
event DisputeOpened(bytes32 gameId, address indexed disputeOpener, address indexed defendant);
//Event is triggered after a dispute is resolved by the function resolveDispute()
event DisputeResolved(bytes32 gameId, address indexed player);
//Event is triggered after a dispute is closed after the amount of time specified in disputeTimer
event DisputeClosedOnTimeout(bytes32 gameId, address indexed player);
//Event is triggered after sending the winning to the winner
event WinnerReward(address indexed winner, uint256 amount);
//Event is triggered after the jackpot is sent to the winner
event JackpotReward(bytes32 gameId, address player, uint256 amount);
//Event is triggered after changing the gameId that claims the jackpot
event CurrentJackpotGame(bytes32 gameId);
//Event is triggered after sending the reward to the referrer
event ReferredReward(address referrer, uint256 amount);
// Emitted when calimTokens function is invoked.
event ClaimedTokens(address token, address owner, uint256 amount);
//The address of the contract that will verify the signature per EIP 712.
//In this case, the current address of the contract.
address public verifyingContract = address(this);
//An disambiguating salt for the protocol per EIP 712.
//Set through the constructor.
bytes32 public salt;
//An address of the creators' account receiving the percentage of Commission for the game
address payable public teamWallet;
//Percentage of commission from the game that is sent to the creators
uint256 public commissionPercent;
//Percentage of reward to the player who invited new players
//0.1% is equal 1
//0.5% is equal 5
//1% is equal 10
//10% is equal 100
uint256 public referralPercent;
//Maximum allowed value of the referralPercent. (10% = 100)
uint256 public maxReferralPercent = 100;
//Minimum bet value to create a new game
uint256 public minBet = 0.01 ether;
//Percentage of game commission added to the jackpot value
uint256 public jackpotPercent;
//Jackpot draw time in UNIX time stamp format.
uint256 public jackpotDrawTime;
//Current jackpot value
uint256 public jackpotValue;
//The current value of the gameId of the applicant for the jackpot.
bytes32 public jackpotGameId;
//Number of seconds added to jackpotDrawTime each time a new game is added to the jackpot.
uint256 public jackpotGameTimerAddition;
//Initial timeout for a new jackpot round.
uint256 public jackpotAccumulationTimer;
//Timeout in seconds during which the dispute cannot be opened.
uint256 public revealTimer;
//Maximum allowed value of the minRevealTimer in seconds.
uint256 public maxRevealTimer;
//Minimum allowed value of the minRevealTimer in seconds.
uint256 public minRevealTimer;
//Timeout in seconds during which the dispute cannot be closed
//and players can call the functions win() and resolveDispute().
uint256 public disputeTimer;
//Maximum allowed value of the maxDisputeTimer in seconds.
uint256 public maxDisputeTimer;
//Minimum allowed value of the minDisputeTimer in seconds.
uint256 public minDisputeTimer;
//Timeout in seconds after the first bet
//during which the second player's bet is expected
//and the game cannot be closed.
uint256 public waitingBetTimer;
//Maximum allowed value of the waitingBetTimer in seconds.
uint256 public maxWaitingBetTimer;
//Minimum allowed value of the waitingBetTimer in seconds.
uint256 public minWaitingBetTimer;
//The time during which the game must be completed to qualify for the jackpot.
uint256 public gameDurationForJackpot;
uint256 public chainId;
//Mapping for storing information about all games
mapping(bytes32 => Game) public games;
//Mapping for storing information about all disputes
mapping(bytes32 => Dispute) public disputes;
//Mapping for storing information about all players
mapping(address => Statistics) public players;
struct Game {
uint256 bet; // bet value for the game
address payable host; // address of the initiating player
address payable join; // address of the joining player
uint256 creationTime; // the time of the last bet in the game.
GameState state; // current state of the game
bytes hostSignature; // the value of the initiating player's signature
bytes joinSignature; // the value of the joining player's signature
bytes32 gameId; // 32 byte game identifier
}
struct Dispute {
address payable disputeOpener; // address of the player, who opened the dispute.
uint256 creationTime; // dispute opening time of the dispute.
bytes32 opponentHash; // hash from an opponent's secret and salt
uint256 secret; // secret value of the player, who opened the dispute
bytes32 salt; // salt value of the player, who opened the dispute
bool isHost; // true if the player initiated the game.
}
struct Statistics {
uint256 totalGames; // totalGames played by the player
uint256 totalUnrevealedGames; // total games that have been disputed against a player for unrevealing the secret on time
uint256 totalNotFundedGames; // total number of games a player has not send funds on time
uint256 totalOpenedDisputes; // total number of disputed games created by a player against someone for unrevealing the secret on time
uint256 avgBetAmount; // average bet value
}
/**
* @dev Throws if the game state is not Filled.
*/
modifier isFilled(bytes32 _gameId) {
require(games[_gameId].state == GameState.Filled, "game state is not Filled");
_;
}
/**
* @dev Throws if the game is not Filled or dispute has not been opened.
*/
modifier verifyGameState(bytes32 _gameId) {
require(
games[_gameId].state == GameState.DisputeOpenedByHost ||
games[_gameId].state == GameState.DisputeOpenedByJoin ||
games[_gameId].state == GameState.Filled,
"game state are not Filled or OpenedDispute"
);
_;
}
/**
* @dev Throws if at least one player has not made a bet.
*/
modifier isOpen(bytes32 _gameId) {
require(
games[_gameId].state == GameState.HostBetted ||
games[_gameId].state == GameState.JoinBetted,
"game state is not Open");
_;
}
/**
* @dev Throws if called by any account other than the participant's one in this game.
*/
modifier onlyParticipant(bytes32 _gameId) {
require(
games[_gameId].host == msg.sender || games[_gameId].join == msg.sender,
"you are not a participant of this game"
);
_;
}
/**
* @dev Setting the parameters of the contract.
* Description of the main parameters can be found above.
* @param _chainId Id of the current chain.
* @param _maxValueOfTimer maximum value for revealTimer, disputeTimer and waitingBetTimer.
* Minimum values are set with revealTimer, disputeTimer, and waitingBetTimer values passed to the constructor.
*/
constructor (
uint256 _chainId,
address payable _teamWallet,
uint256 _commissionPercent,
uint256 _jackpotPercent,
uint256 _referralPercent,
uint256 _jackpotGameTimerAddition,
uint256 _jackpotAccumulationTimer,
uint256 _revealTimer,
uint256 _disputeTimer,
uint256 _waitingBetTimer,
uint256 _gameDurationForJackpot,
bytes32 _salt,
uint256 _maxValueOfTimer
) public {
teamWallet = _teamWallet;
jackpotDrawTime = getTime().add(_jackpotAccumulationTimer);
jackpotAccumulationTimer = _jackpotAccumulationTimer;
commissionPercent = _commissionPercent;
jackpotPercent = _jackpotPercent;
referralPercent = _referralPercent;
jackpotGameTimerAddition = _jackpotGameTimerAddition;
revealTimer = _revealTimer;
minRevealTimer = _revealTimer;
maxRevealTimer = _maxValueOfTimer;
disputeTimer = _disputeTimer;
minDisputeTimer = _disputeTimer;
maxDisputeTimer = _maxValueOfTimer;
waitingBetTimer = _waitingBetTimer;
minWaitingBetTimer = _waitingBetTimer;
maxWaitingBetTimer = _maxValueOfTimer;
gameDurationForJackpot = _gameDurationForJackpot;
salt = _salt;
chainId = _chainId;
DOMAIN_SEPARATOR = keccak256(abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256("Find The Rabbit"),
keccak256("0.1"),
_chainId,
verifyingContract,
salt
));
}
/**
* @dev Change the current waitingBetTimer value.
* Change can be made only within the maximum and minimum values.
* @param _waitingBetTimer is a new value of waitingBetTimer
*/
function setWaitingBetTimerValue(uint256 _waitingBetTimer) external onlyOwner {
require(_waitingBetTimer >= minWaitingBetTimer, "must be more than minWaitingBetTimer");
require(_waitingBetTimer <= maxWaitingBetTimer, "must be less than maxWaitingBetTimer");
waitingBetTimer = _waitingBetTimer;
}
/**
* @dev Change the current disputeTimer value.
* Change can be made only within the maximum and minimum values.
* @param _disputeTimer is a new value of disputeTimer.
*/
function setDisputeTimerValue(uint256 _disputeTimer) external onlyOwner {
require(_disputeTimer >= minDisputeTimer, "must be more than minDisputeTimer");
require(_disputeTimer <= maxDisputeTimer, "must be less than maxDisputeTimer");
disputeTimer = _disputeTimer;
}
/**
* @dev Change the current revealTimer value.
* Change can be made only within the maximum and minimum values.
* @param _revealTimer is a new value of revealTimer
*/
function setRevealTimerValue(uint256 _revealTimer) external onlyOwner {
require(_revealTimer >= minRevealTimer, "must be more than minRevealTimer");
require(_revealTimer <= maxRevealTimer, "must be less than maxRevealTimer");
revealTimer = _revealTimer;
}
/**
* @dev Change the current minBet value.
* @param _newValue is a new value of minBet.
*/
function setMinBetValue(uint256 _newValue) external onlyOwner {
require(_newValue != 0, "must be greater than 0");
minBet = _newValue;
}
/**
* @dev Change the current jackpotGameTimerAddition.
* Change can be made only within the maximum and minimum values.
* Jackpot should not hold significant value
* @param _jackpotGameTimerAddition is a new value of jackpotGameTimerAddition
*/
function setJackpotGameTimerAddition(uint256 _jackpotGameTimerAddition) external onlyOwner {
if (chainId == 1) {
// jackpot must be less than 150 DAI. 1 ether = 150 DAI
require(jackpotValue <= 1 ether);
}
if (chainId == 99) {
// jackpot must be less than 150 DAI. 1 POA = 0.03 DAI
require(jackpotValue <= 4500 ether);
}
require(_jackpotGameTimerAddition >= 2 minutes, "must be more than 2 minutes");
require(_jackpotGameTimerAddition <= 1 hours, "must be less than 1 hour");
jackpotGameTimerAddition = _jackpotGameTimerAddition;
}
/**
* @dev Change the current referralPercent value.
* Example:
* 1 = 0.1%
* 5 = 0.5%
* 10 = 1%
* @param _newValue is a new value of referralPercent.
*/
function setReferralPercentValue(uint256 _newValue) external onlyOwner {
require(_newValue <= maxReferralPercent, "must be less than maxReferralPercent");
referralPercent = _newValue;
}
/**
* @dev Change the current commissionPercent value.
* Example:
* 1 = 1%
* @param _newValue is a new value of commissionPercent.
*/
function setCommissionPercent(uint256 _newValue) external onlyOwner {
require(_newValue <= 20, "must be less than 20");
commissionPercent = _newValue;
}
/**
* @dev Change the current teamWallet address.
* @param _newTeamWallet is a new teamWallet address.
*/
function setTeamWalletAddress(address payable _newTeamWallet) external onlyOwner {
require(_newTeamWallet != address(0));
teamWallet = _newTeamWallet;
}
/**
* @return information about the jackpot.
*/
function getJackpotInfo()
external
view
returns (
uint256 _jackpotDrawTime,
uint256 _jackpotValue,
bytes32 _jackpotGameId
)
{
_jackpotDrawTime = jackpotDrawTime;
_jackpotValue = jackpotValue;
_jackpotGameId = jackpotGameId;
}
/**
* @return timers used for games.
*/
function getTimers()
external
view
returns (
uint256 _revealTimer,
uint256 _disputeTimer,
uint256 _waitingBetTimer,
uint256 _jackpotAccumulationTimer
)
{
_revealTimer = revealTimer;
_disputeTimer = disputeTimer;
_waitingBetTimer = waitingBetTimer;
_jackpotAccumulationTimer = jackpotAccumulationTimer;
}
/**
* @dev Transfer of tokens from the contract
* @param _token the address of the tokens to be transferred.
*/
function claimTokens(address _token) public onlyOwner {
ERC20Basic erc20token = ERC20Basic(_token);
uint256 balance = erc20token.balanceOf(address(this));
erc20token.transfer(owner(), balance);
emit ClaimedTokens(_token, owner(), balance);
}
/**
* @dev Allows to create a game and place a bet.
* @param _isHost True if the sending account initiated the game.
* @param _hashOfMySecret Hash value of the sending account's secret and salt.
* @param _hashOfOpponentSecret Hash value of the opponent account's secret and salt.
* @param _hostSignature Signature of the initiating player from the following values:
* bet,
* isHost, // true
* opponentAddress, // join address
* hashOfMySecret, // hash of host secret
* hashOfOpponentSecret // hash of join secret
* @param _joinSignature Signature of the joining player from the following values:
* bet,
* isHost, // false
* opponentAddress, // host address
* hashOfMySecret, // hash of join secret
* hashOfOpponentSecret // hash of host secret
*/
function createGame(
bool _isHost,
bytes32 _hashOfMySecret,
bytes32 _hashOfOpponentSecret,
bytes memory _hostSignature,
bytes memory _joinSignature
)
public
payable
{
require(msg.value >= minBet, "must be greater than the minimum value");
bytes32 gameId = getGameId(_hostSignature, _joinSignature);
address opponent = _getSignerAddress(
msg.value,
!_isHost,
msg.sender,
_hashOfOpponentSecret,
_hashOfMySecret,
_isHost ? _joinSignature : _hostSignature);
require(opponent != msg.sender, "send your opponent's signature");
Game storage game = games[gameId];
if (game.gameId == 0){
_recordGameInfo(msg.value, _isHost, gameId, opponent, _hostSignature, _joinSignature);
emit GameOpened(game.gameId, msg.sender);
} else {
require(game.host == msg.sender || game.join == msg.sender, "you are not paticipant in this game");
require(game.state == GameState.HostBetted || game.state == GameState.JoinBetted, "the game is not Opened");
if (_isHost) {
require(game.host == msg.sender, "you are not the host in this game");
require(game.join == opponent, "invalid join signature");
require(game.state == GameState.JoinBetted, "you have already made a bet");
} else {
require(game.join == msg.sender, "you are not the join in this game.");
require(game.host == opponent, "invalid host signature");
require(game.state == GameState.HostBetted, "you have already made a bet");
}
game.creationTime = getTime();
game.state = GameState.Filled;
emit GameCreated(game.host, game.join, game.bet, game.gameId, game.state);
}
}
/**
* @dev If the disclosure is true, the winner gets a prize.
* @notice a referrer will be sent a reward to.
* only if the referrer has previously played the game and the sending account has not.
* @param _gameId 32 byte game identifier.
* @param _hostSecret The initiating player's secret.
* @param _hostSalt The initiating player's salt.
* @param _joinSecret The joining player's secret.
* @param _joinSalt The joining player's salt.
* @param _referrer The winning player's referrer. The referrer must have played games.
*/
function win(
bytes32 _gameId,
uint8 _hostSecret,
bytes32 _hostSalt,
uint8 _joinSecret,
bytes32 _joinSalt,
address payable _referrer
)
public
verifyGameState(_gameId)
onlyParticipant(_gameId)
{
Game storage game = games[_gameId];
bytes32 hashOfHostSecret = _hashOfSecret(_hostSalt, _hostSecret);
bytes32 hashOfJoinSecret = _hashOfSecret(_joinSalt, _joinSecret);
address host = _getSignerAddress(
game.bet,
true,
game.join,
hashOfHostSecret,
hashOfJoinSecret,
game.hostSignature
);
address join = _getSignerAddress(
game.bet,
false,
game.host,
hashOfJoinSecret,
hashOfHostSecret,
game.joinSignature
);
require(host == game.host && join == game.join, "invalid reveals");
address payable winner;
if (_hostSecret == _joinSecret){
winner = game.join;
game.state = GameState.WonByJoin;
} else {
winner = game.host;
game.state = GameState.WonByHost;
}
if (isPlayerExist(_referrer) && _referrer != msg.sender) {
_processPayments(game.bet, winner, _referrer);
}
else {
_processPayments(game.bet, winner, address(0));
}
_jackpotPayoutProcessing(_gameId);
_recordStatisticInfo(game.host, game.join, game.bet);
}
/**
* @dev If during the time specified in revealTimer one of the players does not send
* the secret and salt to the opponent, the player can open a dispute.
* @param _gameId 32 byte game identifier
* @param _secret Secret of the player, who opens the dispute.
* @param _salt Salt of the player, who opens the dispute.
* @param _isHost True if the sending account initiated the game.
* @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt.
*/
function openDispute(
bytes32 _gameId,
uint8 _secret,
bytes32 _salt,
bool _isHost,
bytes32 _hashOfOpponentSecret
)
public
onlyParticipant(_gameId)
{
require(timeUntilOpenDispute(_gameId) == 0, "the waiting time for revealing is not over yet");
Game storage game = games[_gameId];
require(isSecretDataValid(
_gameId,
_secret,
_salt,
_isHost,
_hashOfOpponentSecret
), "invalid salt or secret");
_recordDisputeInfo(_gameId, msg.sender, _hashOfOpponentSecret, _secret, _salt, _isHost);
game.state = _isHost ? GameState.DisputeOpenedByHost : GameState.DisputeOpenedByJoin;
address defendant = _isHost ? game.join : game.host;
players[msg.sender].totalOpenedDisputes = (players[msg.sender].totalOpenedDisputes).add(1);
players[defendant].totalUnrevealedGames = (players[defendant].totalUnrevealedGames).add(1);
emit DisputeOpened(_gameId, msg.sender, defendant);
}
/**
* @dev Allows the accused player to make a secret disclosure
* and pick up the winnings in case of victory.
* @param _gameId 32 byte game identifier.
* @param _secret An accused player's secret.
* @param _salt An accused player's salt.
* @param _isHost True if the sending account initiated the game.
* @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt.
*/
function resolveDispute(
bytes32 _gameId,
uint8 _secret,
bytes32 _salt,
bool _isHost,
bytes32 _hashOfOpponentSecret
)
public
returns(address payable winner)
{
require(isDisputeOpened(_gameId), "there is no dispute");
Game storage game = games[_gameId];
Dispute memory dispute = disputes[_gameId];
require(msg.sender != dispute.disputeOpener, "only for the opponent");
require(isSecretDataValid(
_gameId,
_secret,
_salt,
_isHost,
_hashOfOpponentSecret
), "invalid salt or secret");
if (_secret == dispute.secret) {
winner = game.join;
game.state = GameState.WonByJoin;
} else {
winner = game.host;
game.state = GameState.WonByHost;
}
_processPayments(game.bet, winner, address(0));
_jackpotPayoutProcessing(_gameId);
_recordStatisticInfo(game.host, game.join, game.bet);
emit DisputeResolved(_gameId, msg.sender);
}
/**
* @dev If during the time specified in disputeTimer the accused player does not manage to resolve a dispute
* the player, who has opened the dispute, can close the dispute and get the win.
* @param _gameId 32 byte game identifier.
* @return address of the winning player.
*/
function closeDisputeOnTimeout(bytes32 _gameId) public returns (address payable winner) {
Game storage game = games[_gameId];
Dispute memory dispute = disputes[_gameId];
require(timeUntilCloseDispute(_gameId) == 0, "the time has not yet come out");
winner = dispute.disputeOpener;
game.state = (winner == game.host) ? GameState.DisputeWonOnTimeoutByHost : GameState.DisputeWonOnTimeoutByJoin;
_processPayments(game.bet, winner, address(0));
_jackpotPayoutProcessing(_gameId);
_recordStatisticInfo(game.host, game.join, game.bet);
emit DisputeClosedOnTimeout(_gameId, msg.sender);
}
/**
* @dev If one of the player made a bet and during the time specified in waitingBetTimer
* the opponent does not make a bet too, the player can take his bet back.
* @param _gameId 32 byte game identifier.
*/
function cancelGame(
bytes32 _gameId
)
public
onlyParticipant(_gameId)
{
require(timeUntilCancel(_gameId) == 0, "the waiting time for the second player's bet is not over yet");
Game storage game = games[_gameId];
address payable recipient;
recipient = game.state == GameState.HostBetted ? game.host : game.join;
address defendant = game.state == GameState.HostBetted ? game.join : game.host;
game.state = (recipient == game.host) ? GameState.CanceledByHost : GameState.CanceledByJoin;
recipient.transfer(game.bet);
players[defendant].totalNotFundedGames = (players[defendant].totalNotFundedGames).add(1);
emit GameCanceled(_gameId, msg.sender, defendant);
}
/**
* @dev Jackpot draw if the time has come and there is a winner.
*/
function drawJackpot() public {
require(isJackpotAvailable(), "is not avaliable yet");
require(jackpotGameId != 0, "no game to claim on the jackpot");
require(jackpotValue != 0, "jackpot's empty");
_payoutJackpot();
}
/**
* @return true if there is open dispute for given `_gameId`
*/
function isDisputeOpened(bytes32 _gameId) public view returns(bool) {
return (
games[_gameId].state == GameState.DisputeOpenedByHost ||
games[_gameId].state == GameState.DisputeOpenedByJoin
);
}
/**
* @return true if a player played at least one game and did not Cancel it.
*/
function isPlayerExist(address _player) public view returns (bool) {
return players[_player].totalGames != 0;
}
/**
* @return the time after which a player can close the game.
* @param _gameId 32 byte game identifier.
*/
function timeUntilCancel(
bytes32 _gameId
)
public
view
isOpen(_gameId)
returns (uint256 remainingTime)
{
uint256 timePassed = getTime().sub(games[_gameId].creationTime);
if (waitingBetTimer > timePassed) {
return waitingBetTimer.sub(timePassed);
} else {
return 0;
}
}
/**
* @return the time after which a player can open the dispute.
* @param _gameId 32 byte game identifier.
*/
function timeUntilOpenDispute(
bytes32 _gameId
)
public
view
isFilled(_gameId)
returns (uint256 remainingTime)
{
uint256 timePassed = getTime().sub(games[_gameId].creationTime);
if (revealTimer > timePassed) {
return revealTimer.sub(timePassed);
} else {
return 0;
}
}
/**
* @return the time after which a player can close the dispute opened by him.
* @param _gameId 32 byte game identifier.
*/
function timeUntilCloseDispute(
bytes32 _gameId
)
public
view
returns (uint256 remainingTime)
{
require(isDisputeOpened(_gameId), "there is no open dispute");
uint256 timePassed = getTime().sub(disputes[_gameId].creationTime);
if (disputeTimer > timePassed) {
return disputeTimer.sub(timePassed);
} else {
return 0;
}
}
/**
* @return the current time in UNIX timestamp format.
*/
function getTime() public view returns(uint) {
return block.timestamp;
}
/**
* @return the current game state.
* @param _gameId 32 byte game identifier
*/
function getGameState(bytes32 _gameId) public view returns(GameState) {
return games[_gameId].state;
}
/**
* @return true if the sent secret and salt match the genuine ones.
* @param _gameId 32 byte game identifier.
* @param _secret A player's secret.
* @param _salt A player's salt.
* @param _isHost True if the sending account initiated the game.
* @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt.
*/
function isSecretDataValid(
bytes32 _gameId,
uint8 _secret,
bytes32 _salt,
bool _isHost,
bytes32 _hashOfOpponentSecret
)
public
view
returns (bool)
{
Game memory game = games[_gameId];
bytes32 hashOfPlayerSecret = _hashOfSecret(_salt, _secret);
address player = _getSignerAddress(
game.bet,
_isHost,
_isHost ? game.join : game.host,
hashOfPlayerSecret,
_hashOfOpponentSecret,
_isHost ? game.hostSignature : game.joinSignature
);
require(msg.sender == player, "the received address does not match with msg.sender");
if (_isHost) {
return player == game.host;
} else {
return player == game.join;
}
}
/**
* @return true if the jackpotDrawTime has come.
*/
function isJackpotAvailable() public view returns (bool) {
return getTime() >= jackpotDrawTime;
}
function isGameAllowedForJackpot(bytes32 _gameId) public view returns (bool) {
return getTime() - games[_gameId].creationTime < gameDurationForJackpot;
}
/**
* @return an array of statuses for the listed games.
* @param _games array of games identifier.
*/
function getGamesStates(bytes32[] memory _games) public view returns(GameState[] memory) {
GameState[] memory _states = new GameState[](_games.length);
for (uint i=0; i<_games.length; i++) {
Game storage game = games[_games[i]];
_states[i] = game.state;
}
return _states;
}
/**
* @return an array of Statistics for the listed players.
* @param _players array of players' addresses.
*/
function getPlayersStatistic(address[] memory _players) public view returns(uint[] memory) {
uint[] memory _statistics = new uint[](_players.length * 5);
for (uint i=0; i<_players.length; i++) {
Statistics storage player = players[_players[i]];
_statistics[5*i + 0] = player.totalGames;
_statistics[5*i + 1] = player.totalUnrevealedGames;
_statistics[5*i + 2] = player.totalNotFundedGames;
_statistics[5*i + 3] = player.totalOpenedDisputes;
_statistics[5*i + 4] = player.avgBetAmount;
}
return _statistics;
}
/**
* @return GameId generated for current values of the signatures.
* @param _signatureHost Signature of the initiating player.
* @param _signatureJoin Signature of the joining player.
*/
function getGameId(bytes memory _signatureHost, bytes memory _signatureJoin) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_signatureHost, _signatureJoin));
}
/**
* @dev jackpot draw.
*/
function _payoutJackpot() internal {
Game storage jackpotGame = games[jackpotGameId];
uint256 reward = jackpotValue.div(2);
jackpotValue = 0;
jackpotGameId = 0;
jackpotDrawTime = (getTime()).add(jackpotAccumulationTimer);
if (jackpotGame.host.send(reward)) {
emit JackpotReward(jackpotGame.gameId, jackpotGame.host, reward.mul(2));
}
if (jackpotGame.join.send(reward)) {
emit JackpotReward(jackpotGame.gameId, jackpotGame.join, reward.mul(2));
}
}
/**
* @dev adds the completed game to the jackpot draw.
* @param _gameId 32 byte game identifier.
*/
function _addGameToJackpot(bytes32 _gameId) internal {
jackpotDrawTime = jackpotDrawTime.add(jackpotGameTimerAddition);
jackpotGameId = _gameId;
emit CurrentJackpotGame(_gameId);
}
/**
* @dev update jackpot info.
* @param _gameId 32 byte game identifier.
*/
function _jackpotPayoutProcessing(bytes32 _gameId) internal {
if (isJackpotAvailable()) {
if (jackpotGameId != 0 && jackpotValue != 0) {
_payoutJackpot();
}
else {
jackpotDrawTime = (getTime()).add(jackpotAccumulationTimer);
}
}
if (isGameAllowedForJackpot(_gameId)) {
_addGameToJackpot(_gameId);
}
}
/**
* @dev take a commission to the creators, reward to referrer, and commission for the jackpot from the winning amount.
* Sending prize to winner.
* @param _bet bet in the current game.
* @param _winner the winner's address.
* @param _referrer the referrer's address.
*/
function _processPayments(uint256 _bet, address payable _winner, address payable _referrer) internal {
uint256 doubleBet = (_bet).mul(2);
uint256 commission = (doubleBet.mul(commissionPercent)).div(100);
uint256 jackpotPart = (doubleBet.mul(jackpotPercent)).div(100);
uint256 winnerStake;
if (_referrer != address(0) && referralPercent != 0 ) {
uint256 referrerPart = (doubleBet.mul(referralPercent)).div(1000);
winnerStake = doubleBet.sub(commission).sub(jackpotPart).sub(referrerPart);
if (_referrer.send(referrerPart)) {
emit ReferredReward(_referrer, referrerPart);
}
}
else {
winnerStake = doubleBet.sub(commission).sub(jackpotPart);
}
jackpotValue = jackpotValue.add(jackpotPart);
_winner.transfer(winnerStake);
teamWallet.transfer(commission);
emit WinnerReward(_winner, winnerStake);
}
/**
* @dev filling in the "Game" structure.
*/
function _recordGameInfo(
uint256 _value,
bool _isHost,
bytes32 _gameId,
address _opponent,
bytes memory _hostSignature,
bytes memory _joinSignature
) internal {
Game memory _game = Game({
bet: _value,
host: _isHost ? msg.sender : address(uint160(_opponent)),
join: _isHost ? address(uint160(_opponent)) : msg.sender,
creationTime: getTime(),
state: _isHost ? GameState.HostBetted : GameState.JoinBetted ,
gameId: _gameId,
hostSignature: _hostSignature,
joinSignature: _joinSignature
});
games[_gameId] = _game;
}
/**
* @dev filling in the "Dispute" structure.
*/
function _recordDisputeInfo(
bytes32 _gameId,
address payable _disputeOpener,
bytes32 _hashOfOpponentSecret,
uint8 _secret,
bytes32 _salt,
bool _isHost
) internal {
Dispute memory _dispute = Dispute({
disputeOpener: _disputeOpener,
creationTime: getTime(),
opponentHash: _hashOfOpponentSecret,
secret: _secret,
salt: _salt,
isHost: _isHost
});
disputes[_gameId] = _dispute;
}
/**
* @dev filling in the "Statistics" structure.
*/
function _recordStatisticInfo(address _host, address _join, uint256 _bet) internal {
Statistics storage statHost = players[_host];
Statistics storage statJoin = players[_join];
statHost.avgBetAmount = _calculateAvgBet(_host, _bet);
statJoin.avgBetAmount = _calculateAvgBet(_join, _bet);
statHost.totalGames = (statHost.totalGames).add(1);
statJoin.totalGames = (statJoin.totalGames).add(1);
}
/**
* @dev recalculation of an average bet value for a player.
* @param _player the address of the player.
* @param _bet bet from the last played game.
*/
function _calculateAvgBet(address _player, uint256 _bet) internal view returns (uint256 newAvgBetValue){
Statistics storage statistics = players[_player];
uint256 totalBets = (statistics.avgBetAmount).mul(statistics.totalGames).add(_bet);
newAvgBetValue = totalBets.div(statistics.totalGames.add(1));
}
} | recalculation of an average bet value for a player. _player the address of the player. _bet bet from the last played game./ | function _calculateAvgBet(address _player, uint256 _bet) internal view returns (uint256 newAvgBetValue){
Statistics storage statistics = players[_player];
uint256 totalBets = (statistics.avgBetAmount).mul(statistics.totalGames).add(_bet);
newAvgBetValue = totalBets.div(statistics.totalGames.add(1));
}
| 13,000,787 |
./full_match/1/0xe229084e0892f26a2Eec44349C36463F4b93E5c6/sources/contracts/TransactionManager.sol | Transfer Asset to Receiver after swpping stable token to asset txData All of the data (invariant and variant) for a crosschain transaction. The variant data provided is checked against what was stored when the `prepare` function was called. relayerFee The fee that should go to the relayer when they are calling the function for the user Send the relayer the fee | function transferAssetToReceiver(TransactionData calldata txData, uint256 relayerFee)
internal returns(uint256)
{
uint256 toSend;
unchecked {
toSend = txData.amount - relayerFee;
}
address stableToken = getStableToken();
if (relayerFee > 0) {
LibAsset.transferAsset(stableToken, payable(msg.sender), relayerFee);
}
if (toSend > 0) {
LibAsset.transferAsset(txData.receivingAssetId, payable(txData.receivingAddress), toSend);
}
return toSend;
}
| 8,344,640 |
./full_match/1/0x5E972096a48C73bAb6b56DA3eb2D60cEDF48e21c/sources/contracts/tokens/GenesisOwnerKey.sol | --------------------------------------- - Public Functions - --------------------------------------- | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
GameProp memory gp = _gameProps[tokenId];
string memory strTokenId = Strings.toString(tokenId);
string memory s1 = string(
abi.encodePacked(
'{"name": "',
name(),
": ",
tierName,
" #",
strTokenId,
'", "image": "',
tierImageURI,
'", "external_url": "',
tierExternalURL,
'", "animation_url": "',
tierAnimationURL
)
);
string memory s2 = Base64.encode(
bytes(
string(
abi.encodePacked(
s1,
'", "description": "PlayEstates Founding Member Token"',
', "attributes": [',
'{ "trait_type": "Tier", "value": "',
tierName,
'"},',
'{ "trait_type": "ID", "value": "',
strTokenId,
'"},',
'{ "display_type": "number", "trait_type": "Game Play", "value": ',
Strings.toString(gp.game_play),
"},",
'{ "display_type": "number", "trait_type": "Token Transaction", "value": ',
Strings.toString(gp.token_transaction),
"}",
"]}"
)
)
)
);
string memory output = string(
abi.encodePacked("data:application/json;base64,", s2)
);
return output;
}
| 4,853,841 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
pragma experimental ABIEncoderV2;
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "interfaces/uniswap/IUniswapRouterV2.sol";
import "interfaces/uniswap/IUniswapV2Factory.sol";
import "interfaces/curve/ICurveFi.sol";
import "interfaces/curve/ICurveGauge.sol";
import "interfaces/uniswap/IUniswapRouterV2.sol";
import "interfaces/badger/IBadgerGeyser.sol";
import "interfaces/badger/IController.sol";
import "../BaseStrategy.sol";
import "interfaces/uniswap/IStakingRewards.sol";
/*
Strategy to compound badger rewards
- Deposit Badger into the vault to receive more from a special rewards pool
*/
contract StrategyDiggLpMetaFarm is BaseStrategy {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address public geyser;
address public digg; // Digg Token
address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; // wBTC Token
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Weth Token, used for crv <> weth <> wbtc route
event HarvestLpMetaFarm(
uint256 badgerHarvested,
uint256 totalDigg,
uint256 diggConvertedToWbtc,
uint256 wbtcFromConversion,
uint256 lpGained,
uint256 lpDeposited,
uint256 timestamp,
uint256 blockNumber
);
struct HarvestData {
uint256 badgerHarvested;
uint256 totalDigg;
uint256 diggConvertedToWbtc;
uint256 wbtcFromConversion;
uint256 lpGained;
uint256 lpDeposited;
}
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[3] memory _wantConfig,
uint256[3] memory _feeConfig
) public initializer {
__BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian);
want = _wantConfig[0];
geyser = _wantConfig[1];
digg = _wantConfig[2];
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
}
/// ===== View Functions =====
function getName() external override pure returns (string memory) {
return "StrategyBadgerLpMetaFarm";
}
function balanceOfPool() public override view returns (uint256) {
return IStakingRewards(geyser).balanceOf(address(this));
}
function getProtectedTokens() public override view returns (address[] memory) {
address[] memory protectedTokens = new address[](3);
protectedTokens[0] = want;
protectedTokens[1] = geyser;
protectedTokens[2] = digg;
return protectedTokens;
}
/// ===== Internal Core Implementations =====
function _onlyNotProtectedTokens(address _asset) internal override {
require(address(want) != _asset, "want");
require(address(geyser) != _asset, "geyser");
require(address(digg) != _asset, "digg");
}
/// @dev Deposit Badger into the staking contract
function _deposit(uint256 _want) internal override {
_safeApproveHelper(want, geyser, _want);
IStakingRewards(geyser).stake(_want);
}
/// @dev Exit stakingRewards position
/// @dev Harvest all Badger and sent to controller
function _withdrawAll() internal override {
IStakingRewards(geyser).exit();
// Send non-native rewards to controller
uint256 _badger = IERC20Upgradeable(digg).balanceOf(address(this));
IERC20Upgradeable(digg).safeTransfer(IController(controller).rewards(), _badger);
}
/// @dev Withdraw from staking rewards, using earnings first
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want < _amount) {
uint256 _toWithdraw = _amount.sub(_want);
IStakingRewards(geyser).withdraw(_toWithdraw);
}
return _amount;
}
/// @dev Harvest accumulated digg rewards and convert them to LP tokens
/// @dev Restake the gained LP tokens in the Geyser
function harvest() external whenNotPaused returns (HarvestData memory) {
_onlyAuthorizedActors();
HarvestData memory harvestData;
uint256 _beforeBadger = IERC20Upgradeable(digg).balanceOf(address(this));
uint256 _beforeLp = IERC20Upgradeable(want).balanceOf(address(this));
// Harvest rewards from Geyser
IStakingRewards(geyser).getReward();
harvestData.totalDigg = IERC20Upgradeable(digg).balanceOf(address(this));
harvestData.badgerHarvested = harvestData.totalDigg.sub(_beforeBadger);
// Swap half of harvested digg for wBTC in liquidity pool
if (harvestData.totalDigg > 0) {
harvestData.diggConvertedToWbtc = harvestData.badgerHarvested.div(2);
if (harvestData.diggConvertedToWbtc > 0) {
address[] memory path = new address[](2);
path[0] = digg; // Badger
path[1] = wbtc;
_swap(digg, harvestData.diggConvertedToWbtc, path);
// Add Badger and wBTC as liquidity if any to add
_add_max_liquidity_uniswap(digg, wbtc);
}
}
// Deposit gained LP position into staking rewards
harvestData.lpDeposited = IERC20Upgradeable(want).balanceOf(address(this));
harvestData.lpGained = harvestData.lpDeposited.sub(_beforeLp);
if (harvestData.lpGained > 0) {
_deposit(harvestData.lpGained);
}
emit HarvestLpMetaFarm(
harvestData.badgerHarvested,
harvestData.totalDigg,
harvestData.diggConvertedToWbtc,
harvestData.wbtcFromConversion,
harvestData.lpGained,
harvestData.lpDeposited,
block.timestamp,
block.number
);
emit Harvest(harvestData.lpGained, block.number);
return harvestData;
}
}
| Exit stakingRewards position Harvest all Badger and sent to controller Send non-native rewards to controller | function _withdrawAll() internal override {
IStakingRewards(geyser).exit();
uint256 _badger = IERC20Upgradeable(digg).balanceOf(address(this));
IERC20Upgradeable(digg).safeTransfer(IController(controller).rewards(), _badger);
}
| 5,411,109 |
pragma solidity ^0.5.0;
contract Users {
//Estructura
struct User {
string name;
bytes32 status;
address walletAddress;
uint createdAt;
uint updatedAt;
}
//sirve para mapear la direccion de la wallet con el id de usuario
mapping (address => uint) public usersIds;
//Array del usuario que contiene la lista de los usuarios y sus detalles
User[] public users;
//sale un evento cuando el usuario se registro
event newUserRegistered(uint id);
// sale un evento cuando se actualiza el estado o el nombre
event userUpdateEvent(uint id);
// Modifier: revisa si el smart contract esta registrado
modifier checkSenderIsRegistered {
require(isRegistered());
_;
}
/**
* Constructor funcion
*/
constructor() public
{
// NOTE: El primero debe ser vacio, dado a que esto hace que se inicialice el constructor
// of the usersIds mapping that does not exist (like usersIds[0x12345]) you will
// receive 0, that's why in the first position (with index 0) must be initialized
addUser(address(0x0), "", "");
// Some dummy data
addUser(address(0x333333333333), "Leo Brown", "Available");
addUser(address(0x111111111111), "John Doe", "Very happy");
addUser(address(0x222222222222), "Mary Smith", "Not in the mood today");
}
//los usuarios no se pueden actualizar despues de creados, alguien sabe por que?
/**
* Function to register a new user.
*
* @param _userName The displaying name
* @param _status The status of the user
*/
function registerUser(string memory _userName, bytes32 _status) public
returns(uint)
{
return addUser(msg.sender, _userName, _status);
}
/**
* Agregar un usuario debe ser privado para que otro usuario no agregue un usuario
*
* @param _wAddr direccion de la wallet
* @param _userName mostrar el nombre de usuario
* @param _status mostrar el estado del usuario
*/
function addUser(address _wAddr, string memory _userName, bytes32 _status) private
returns(uint)
{
// checkear si el usuario ya existe
uint userId = usersIds[_wAddr];
require (userId == 0);
// asociar su wallet con su ID
usersIds[_wAddr] = users.length;
uint newUserId = users.length++;
// guardar el nuevo usuario
users[newUserId] = User({
name: _userName,
status: _status,
walletAddress: _wAddr,
createdAt: now,
updatedAt: now
});
// emitting the event that a new user has been registered
emit newUserRegistered(newUserId);
return newUserId;
}
/**
* Update the user profile of the caller of this method.
* Note: the user can modify only his own profile.
*
* @param _newUserName The new user's displaying name
* @param _newStatus The new user's status
*/
function updateUser(string memory _newUserName, bytes32 _newStatus) checkSenderIsRegistered public
returns(uint)
{
// Un usuario puede modificar solo su perfil
uint userId = usersIds[msg.sender];
User storage user = users[userId];
user.name = _newUserName;
user.status = _newStatus;
user.updatedAt = now;
emit userUpdateEvent(userId);
return userId;
}
/**
* Get the user's profile information.
*
* @param _id The ID of the user stored on the blockchain.
*/
function getUserById(uint _id) public view
returns(
uint,
string memory,
bytes32,
address,
uint,
uint
) {
// checkea si la informacion es valida
require( (_id > 0) || (_id <= users.length) );
User memory i = users[_id];
return (
_id,
i.name,
i.status,
i.walletAddress,
i.createdAt,
i.updatedAt
);
}
/**
* Return the profile information of the caller.
*/
function getOwnProfile() checkSenderIsRegistered public view
returns(
uint,
string memory,
bytes32,
address,
uint,
uint
) {
uint id = usersIds[msg.sender];
return getUserById(id);
}
/**
* Check if the user that is calling the smart contract is registered.
*/
function isRegistered() public view returns (bool)
{
return (usersIds[msg.sender] > 0);
}
/**
* Return the number of total registered users.
*/
function totalUsers() public view returns (uint)
{
// NOTE: the total registered user is length-1 because the user with
// index 0 is empty check the contructor: addUser(address(0x0), "", "");
return users.length - 1;
}
} | Agregar un usuario debe ser privado para que otro usuario no agregue un usuario _wAddr direccion de la wallet _userName mostrar el nombre de usuario _status mostrar el estado del usuario/ checkear si el usuario ya existe asociar su wallet con su ID guardar el nuevo usuario | function addUser(address _wAddr, string memory _userName, bytes32 _status) private
returns(uint)
{
uint userId = usersIds[_wAddr];
require (userId == 0);
usersIds[_wAddr] = users.length;
uint newUserId = users.length++;
users[newUserId] = User({
name: _userName,
status: _status,
walletAddress: _wAddr,
createdAt: now,
updatedAt: now
});
return newUserId;
}
| 12,896,211 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
import "./OffchainAggregator.sol";
import "./SimpleReadAccessController.sol";
/**
* @notice Wrapper of OffchainAggregator which checks read access on Aggregator-interface methods
*/
contract AccessControlledOffchainAggregator is OffchainAggregator, SimpleReadAccessController {
constructor(
uint32 _maximumGasPrice,
uint32 _reasonableGasPrice,
uint32 _microLinkPerEth,
uint32 _linkGweiPerObservation,
uint32 _linkGweiPerTransmission,
address _link,
address _validator,
int192 _minAnswer,
int192 _maxAnswer,
AccessControllerInterface _billingAccessController,
AccessControllerInterface _requesterAccessController,
uint8 _decimals,
string memory description
)
OffchainAggregator(
_maximumGasPrice,
_reasonableGasPrice,
_microLinkPerEth,
_linkGweiPerObservation,
_linkGweiPerTransmission,
_link,
_validator,
_minAnswer,
_maxAnswer,
_billingAccessController,
_requesterAccessController,
_decimals,
description
) {
}
/*
* v2 Aggregator interface
*/
/// @inheritdoc OffchainAggregator
function latestAnswer()
public
override
view
checkAccess()
returns (int256)
{
return super.latestAnswer();
}
/// @inheritdoc OffchainAggregator
function latestTimestamp()
public
override
view
checkAccess()
returns (uint256)
{
return super.latestTimestamp();
}
/// @inheritdoc OffchainAggregator
function latestRound()
public
override
view
checkAccess()
returns (uint256)
{
return super.latestRound();
}
/// @inheritdoc OffchainAggregator
function getAnswer(uint256 _roundId)
public
override
view
checkAccess()
returns (int256)
{
return super.getAnswer(_roundId);
}
/// @inheritdoc OffchainAggregator
function getTimestamp(uint256 _roundId)
public
override
view
checkAccess()
returns (uint256)
{
return super.getTimestamp(_roundId);
}
/*
* v3 Aggregator interface
*/
/// @inheritdoc OffchainAggregator
function description()
public
override
view
checkAccess()
returns (string memory)
{
return super.description();
}
/// @inheritdoc OffchainAggregator
function getRoundData(uint80 _roundId)
public
override
view
checkAccess()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return super.getRoundData(_roundId);
}
/// @inheritdoc OffchainAggregator
function latestRoundData()
public
override
view
checkAccess()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return super.latestRoundData();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./AccessControllerInterface.sol";
import "./AggregatorV2V3Interface.sol";
import "./AggregatorValidatorInterface.sol";
import "./LinkTokenInterface.sol";
import "./Owned.sol";
import "./OffchainAggregatorBilling.sol";
/**
* @notice Onchain verification of reports from the offchain reporting protocol
* @dev For details on its operation, see the offchain reporting protocol design
* @dev doc, which refers to this contract as simply the "contract".
*/
contract OffchainAggregator is Owned, OffchainAggregatorBilling, AggregatorV2V3Interface {
uint256 constant private maxUint32 = (1 << 32) - 1;
// Storing these fields used on the hot path in a HotVars variable reduces the
// retrieval of all of them to a single SLOAD. If any further fields are
// added, make sure that storage of the struct still takes at most 32 bytes.
struct HotVars {
// Provides 128 bits of security against 2nd pre-image attacks, but only
// 64 bits against collisions. This is acceptable, since a malicious owner has
// easier way of messing up the protocol than to find hash collisions.
bytes16 latestConfigDigest;
uint40 latestEpochAndRound; // 32 most sig bits for epoch, 8 least sig bits for round
// Current bound assumed on number of faulty/dishonest oracles participating
// in the protocol, this value is referred to as f in the design
uint8 threshold;
// Chainlink Aggregators expose a roundId to consumers. The offchain reporting
// protocol does not use this id anywhere. We increment it whenever a new
// transmission is made to provide callers with contiguous ids for successive
// reports.
uint32 latestAggregatorRoundId;
}
HotVars internal s_hotVars;
// Transmission records the median answer from the transmit transaction at
// time timestamp
struct Transmission {
int192 answer; // 192 bits ought to be enough for anyone
uint64 timestamp;
}
mapping(uint32 /* aggregator round ID */ => Transmission) internal s_transmissions;
// incremented each time a new config is posted. This count is incorporated
// into the config digest, to prevent replay attacks.
uint32 internal s_configCount;
uint32 internal s_latestConfigBlockNumber; // makes it easier for offchain systems
// to extract config from logs.
// Lowest answer the system is allowed to report in response to transmissions
int192 immutable public minAnswer;
// Highest answer the system is allowed to report in response to transmissions
int192 immutable public maxAnswer;
/*
* @param _maximumGasPrice highest gas price for which transmitter will be compensated
* @param _reasonableGasPrice transmitter will receive reward for gas prices under this value
* @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
* @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
* @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
* @param _link address of the LINK contract
* @param _validator address of validator contract (must satisfy AggregatorValidatorInterface)
* @param _minAnswer lowest answer the median of a report is allowed to be
* @param _maxAnswer highest answer the median of a report is allowed to be
* @param _billingAccessController access controller for billing admin functions
* @param _requesterAccessController access controller for requesting new rounds
* @param _decimals answers are stored in fixed-point format, with this many digits of precision
* @param _description short human-readable description of observable this contract's answers pertain to
*/
constructor(
uint32 _maximumGasPrice,
uint32 _reasonableGasPrice,
uint32 _microLinkPerEth,
uint32 _linkGweiPerObservation,
uint32 _linkGweiPerTransmission,
address _link,
address _validator,
int192 _minAnswer,
int192 _maxAnswer,
AccessControllerInterface _billingAccessController,
AccessControllerInterface _requesterAccessController,
uint8 _decimals,
string memory _description
)
OffchainAggregatorBilling(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
_linkGweiPerObservation, _linkGweiPerTransmission, _link,
_billingAccessController
)
{
decimals = _decimals;
s_description = _description;
setRequesterAccessController(_requesterAccessController);
setValidator(_validator);
minAnswer = _minAnswer;
maxAnswer = _maxAnswer;
}
/*
* Config logic
*/
/**
* @notice triggers a new run of the offchain reporting protocol
* @param previousConfigBlockNumber block in which the previous config was set, to simplify historic analysis
* @param configCount ordinal number of this config setting among all config settings over the life of this contract
* @param signers ith element is address ith oracle uses to sign a report
* @param transmitters ith element is address ith oracle uses to transmit a report via the transmit method
* @param threshold maximum number of faulty/dishonest oracles the protocol can tolerate while still working correctly
* @param encodedConfigVersion version of the serialization format used for "encoded" parameter
* @param encoded serialized data used by oracles to configure their offchain operation
*/
event ConfigSet(
uint32 previousConfigBlockNumber,
uint64 configCount,
address[] signers,
address[] transmitters,
uint8 threshold,
uint64 encodedConfigVersion,
bytes encoded
);
// Reverts transaction if config args are invalid
modifier checkConfigValid (
uint256 _numSigners, uint256 _numTransmitters, uint256 _threshold
) {
require(_numSigners <= maxNumOracles, "too many signers");
require(_threshold > 0, "threshold must be positive");
require(
_numSigners == _numTransmitters,
"oracle addresses out of registration"
);
require(_numSigners > 3*_threshold, "faulty-oracle threshold too high");
_;
}
/**
* @notice sets offchain reporting protocol configuration incl. participating oracles
* @param _signers addresses with which oracles sign the reports
* @param _transmitters addresses oracles use to transmit the reports
* @param _threshold number of faulty oracles the system can tolerate
* @param _encodedConfigVersion version number for offchainEncoding schema
* @param _encoded encoded off-chain oracle configuration
*/
function setConfig(
address[] calldata _signers,
address[] calldata _transmitters,
uint8 _threshold,
uint64 _encodedConfigVersion,
bytes calldata _encoded
)
external
checkConfigValid(_signers.length, _transmitters.length, _threshold)
onlyOwner()
{
while (s_signers.length != 0) { // remove any old signer/transmitter addresses
uint lastIdx = s_signers.length - 1;
address signer = s_signers[lastIdx];
address transmitter = s_transmitters[lastIdx];
payOracle(transmitter);
delete s_oracles[signer];
delete s_oracles[transmitter];
s_signers.pop();
s_transmitters.pop();
}
for (uint i = 0; i < _signers.length; i++) { // add new signer/transmitter addresses
require(
s_oracles[_signers[i]].role == Role.Unset,
"repeated signer address"
);
s_oracles[_signers[i]] = Oracle(uint8(i), Role.Signer);
require(s_payees[_transmitters[i]] != address(0), "payee must be set");
require(
s_oracles[_transmitters[i]].role == Role.Unset,
"repeated transmitter address"
);
s_oracles[_transmitters[i]] = Oracle(uint8(i), Role.Transmitter);
s_signers.push(_signers[i]);
s_transmitters.push(_transmitters[i]);
}
s_hotVars.threshold = _threshold;
uint32 previousConfigBlockNumber = s_latestConfigBlockNumber;
s_latestConfigBlockNumber = uint32(block.number);
s_configCount += 1;
uint64 configCount = s_configCount;
{
s_hotVars.latestConfigDigest = configDigestFromConfigData(
address(this),
configCount,
_signers,
_transmitters,
_threshold,
_encodedConfigVersion,
_encoded
);
s_hotVars.latestEpochAndRound = 0;
}
emit ConfigSet(
previousConfigBlockNumber,
configCount,
_signers,
_transmitters,
_threshold,
_encodedConfigVersion,
_encoded
);
}
function configDigestFromConfigData(
address _contractAddress,
uint64 _configCount,
address[] calldata _signers,
address[] calldata _transmitters,
uint8 _threshold,
uint64 _encodedConfigVersion,
bytes calldata _encodedConfig
) internal pure returns (bytes16) {
return bytes16(keccak256(abi.encode(_contractAddress, _configCount,
_signers, _transmitters, _threshold, _encodedConfigVersion, _encodedConfig
)));
}
/**
* @notice information about current offchain reporting protocol configuration
* @return configCount ordinal number of current config, out of all configs applied to this contract so far
* @return blockNumber block at which this config was set
* @return configDigest domain-separation tag for current config (see configDigestFromConfigData)
*/
function latestConfigDetails()
external
view
returns (
uint32 configCount,
uint32 blockNumber,
bytes16 configDigest
)
{
return (s_configCount, s_latestConfigBlockNumber, s_hotVars.latestConfigDigest);
}
/**
* @return list of addresses permitted to transmit reports to this contract
* @dev The list will match the order used to specify the transmitter during setConfig
*/
function transmitters()
external
view
returns(address[] memory)
{
return s_transmitters;
}
/*
* On-chain validation logc
*/
// Maximum gas the validation logic can use
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// Contract containing the validation logic
AggregatorValidatorInterface private s_validator;
/**
* @notice indicates that the address of the validator contract has been set
* @param previous setting of the address prior to this event
* @param current the new value for the address
*/
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice address of the contract which does external data validation
* @return validator address
*/
function validator()
external
view
returns (AggregatorValidatorInterface)
{
return s_validator;
}
/**
* @notice sets the address which does external data validation
* @param _newValidator designates the address of the new validation contract
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(s_validator);
if (previous != _newValidator) {
s_validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
function validateAnswer(
uint32 _aggregatorRoundId,
int256 _answer
)
private
{
AggregatorValidatorInterface av = s_validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevAggregatorRoundId = _aggregatorRoundId - 1;
int256 prevAggregatorRoundAnswer = s_transmissions[prevAggregatorRoundId].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAggregatorRoundId,
prevAggregatorRoundAnswer,
_aggregatorRoundId,
_answer
) {} catch {}
}
/*
* requestNewRound logic
*/
AccessControllerInterface internal s_requesterAccessController;
/**
* @notice emitted when a new requester access controller contract is set
* @param old the address prior to the current setting
* @param current the address of the new access controller contract
*/
event RequesterAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current);
/**
* @notice emitted to immediately request a new round
* @param requester the address of the requester
* @param configDigest the latest transmission's configDigest
* @param epoch the latest transmission's epoch
* @param round the latest transmission's round
*/
event RoundRequested(address indexed requester, bytes16 configDigest, uint32 epoch, uint8 round);
/**
* @notice address of the requester access controller contract
* @return requester access controller address
*/
function requesterAccessController()
external
view
returns (AccessControllerInterface)
{
return s_requesterAccessController;
}
/**
* @notice sets the requester access controller
* @param _requesterAccessController designates the address of the new requester access controller
*/
function setRequesterAccessController(AccessControllerInterface _requesterAccessController)
public
onlyOwner()
{
AccessControllerInterface oldController = s_requesterAccessController;
if (_requesterAccessController != oldController) {
s_requesterAccessController = AccessControllerInterface(_requesterAccessController);
emit RequesterAccessControllerSet(oldController, _requesterAccessController);
}
}
/**
* @notice immediately requests a new round
* @return the aggregatorRoundId of the next round. Note: The report for this round may have been
* transmitted (but not yet mined) *before* requestNewRound() was even called. There is *no*
* guarantee of causality between the request and the report at aggregatorRoundId.
*/
function requestNewRound() external returns (uint80) {
require(msg.sender == owner || s_requesterAccessController.hasAccess(msg.sender, msg.data),
"Only owner&requester can call");
HotVars memory hotVars = s_hotVars;
emit RoundRequested(
msg.sender,
hotVars.latestConfigDigest,
uint32(s_hotVars.latestEpochAndRound >> 8),
uint8(s_hotVars.latestEpochAndRound)
);
return hotVars.latestAggregatorRoundId + 1;
}
/*
* Transmission logic
*/
/**
* @notice indicates that a new report was transmitted
* @param aggregatorRoundId the round to which this report was assigned
* @param answer median of the observations attached this report
* @param transmitter address from which the report was transmitted
* @param observations observations transmitted with this report
* @param rawReportContext signature-replay-prevention domain-separation tag
*/
event NewTransmission(
uint32 indexed aggregatorRoundId,
int192 answer,
address transmitter,
int192[] observations,
bytes observers,
bytes32 rawReportContext
);
// decodeReport is used to check that the solidity and go code are using the
// same format. See TestOffchainAggregator.testDecodeReport and TestReportParsing
function decodeReport(bytes memory _report)
internal
pure
returns (
bytes32 rawReportContext,
bytes32 rawObservers,
int192[] memory observations
)
{
(rawReportContext, rawObservers, observations) = abi.decode(_report,
(bytes32, bytes32, int192[]));
}
// Used to relieve stack pressure in transmit
struct ReportData {
HotVars hotVars; // Only read from storage once
bytes observers; // ith element is the index of the ith observer
int192[] observations; // ith element is the ith observation
bytes vs; // jth element is the v component of the jth signature
bytes32 rawReportContext;
}
/*
* @notice details about the most recent report
* @return configDigest domain separation tag for the latest report
* @return epoch epoch in which the latest report was generated
* @return round OCR round in which the latest report was generated
* @return latestAnswer median value from latest report
* @return latestTimestamp when the latest report was transmitted
*/
function latestTransmissionDetails()
external
view
returns (
bytes16 configDigest,
uint32 epoch,
uint8 round,
int192 latestAnswer,
uint64 latestTimestamp
)
{
require(msg.sender == tx.origin, "Only callable by EOA");
return (
s_hotVars.latestConfigDigest,
uint32(s_hotVars.latestEpochAndRound >> 8),
uint8(s_hotVars.latestEpochAndRound),
s_transmissions[s_hotVars.latestAggregatorRoundId].answer,
s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp
);
}
// The constant-length components of the msg.data sent to transmit.
// See the "If we wanted to call sam" example on for example reasoning
// https://solidity.readthedocs.io/en/v0.7.2/abi-spec.html
uint16 private constant TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT =
4 + // function selector
32 + // word containing start location of abiencoded _report value
32 + // word containing location start of abiencoded _rs value
32 + // word containing start location of abiencoded _ss value
32 + // _rawVs value
32 + // word containing length of _report
32 + // word containing length _rs
32 + // word containing length of _ss
0; // placeholder
function expectedMsgDataLength(
bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss
) private pure returns (uint256 length)
{
// calldata will never be big enough to make this overflow
return uint256(TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT) +
_report.length + // one byte pure entry in _report
_rs.length * 32 + // 32 bytes per entry in _rs
_ss.length * 32 + // 32 bytes per entry in _ss
0; // placeholder
}
/**
* @notice transmit is called to post a new report to the contract
* @param _report serialized report, which the signatures are signing. See parsing code below for format. The ith element of the observers component must be the index in s_signers of the address for the ith signature
* @param _rs ith element is the R components of the ith signature on report. Must have at most maxNumOracles entries
* @param _ss ith element is the S components of the ith signature on report. Must have at most maxNumOracles entries
* @param _rawVs ith element is the the V component of the ith signature
*/
function transmit(
// NOTE: If these parameters are changed, expectedMsgDataLength and/or
// TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT need to be changed accordingly
bytes calldata _report,
bytes32[] calldata _rs, bytes32[] calldata _ss, bytes32 _rawVs // signatures
)
external
{
uint256 initialGas = gasleft(); // This line must come first
// Make sure the transmit message-length matches the inputs. Otherwise, the
// transmitter could append an arbitrarily long (up to gas-block limit)
// string of 0 bytes, which we would reimburse at a rate of 16 gas/byte, but
// which would only cost the transmitter 4 gas/byte. (Appendix G of the
// yellow paper, p. 25, for G_txdatazero and EIP 2028 for G_txdatanonzero.)
// This could amount to reimbursement profit of 36 million gas, given a 3MB
// zero tail.
require(msg.data.length == expectedMsgDataLength(_report, _rs, _ss),
"transmit message too long");
ReportData memory r; // Relieves stack pressure
{
r.hotVars = s_hotVars; // cache read from storage
bytes32 rawObservers;
(r.rawReportContext, rawObservers, r.observations) = abi.decode(
_report, (bytes32, bytes32, int192[])
);
// rawReportContext consists of:
// 11-byte zero padding
// 16-byte configDigest
// 4-byte epoch
// 1-byte round
bytes16 configDigest = bytes16(r.rawReportContext << 88);
require(
r.hotVars.latestConfigDigest == configDigest,
"configDigest mismatch"
);
uint40 epochAndRound = uint40(uint256(r.rawReportContext));
// direct numerical comparison works here, because
//
// ((e,r) <= (e',r')) implies (epochAndRound <= epochAndRound')
//
// because alphabetic ordering implies e <= e', and if e = e', then r<=r',
// so e*256+r <= e'*256+r', because r, r' < 256
require(r.hotVars.latestEpochAndRound < epochAndRound, "stale report");
require(_rs.length > r.hotVars.threshold, "not enough signatures");
require(_rs.length <= maxNumOracles, "too many signatures");
require(_ss.length == _rs.length, "signatures out of registration");
require(r.observations.length <= maxNumOracles,
"num observations out of bounds");
require(r.observations.length > 2 * r.hotVars.threshold,
"too few values to trust median");
// Copy signature parities in bytes32 _rawVs to bytes r.v
r.vs = new bytes(_rs.length);
for (uint8 i = 0; i < _rs.length; i++) {
r.vs[i] = _rawVs[i];
}
// Copy observer identities in bytes32 rawObservers to bytes r.observers
r.observers = new bytes(r.observations.length);
bool[maxNumOracles] memory seen;
for (uint8 i = 0; i < r.observations.length; i++) {
uint8 observerIdx = uint8(rawObservers[i]);
require(!seen[observerIdx], "observer index repeated");
seen[observerIdx] = true;
r.observers[i] = rawObservers[i];
}
Oracle memory transmitter = s_oracles[msg.sender];
require( // Check that sender is authorized to report
transmitter.role == Role.Transmitter &&
msg.sender == s_transmitters[transmitter.index],
"unauthorized transmitter"
);
// record epochAndRound here, so that we don't have to carry the local
// variable in transmit. The change is reverted if something fails later.
r.hotVars.latestEpochAndRound = epochAndRound;
}
{ // Verify signatures attached to report
bytes32 h = keccak256(_report);
bool[maxNumOracles] memory signed;
Oracle memory o;
for (uint i = 0; i < _rs.length; i++) {
address signer = ecrecover(h, uint8(r.vs[i])+27, _rs[i], _ss[i]);
o = s_oracles[signer];
require(o.role == Role.Signer, "address not authorized to sign");
require(!signed[o.index], "non-unique signature");
signed[o.index] = true;
}
}
{ // Check the report contents, and record the result
for (uint i = 0; i < r.observations.length - 1; i++) {
bool inOrder = r.observations[i] <= r.observations[i+1];
require(inOrder, "observations not sorted");
}
int192 median = r.observations[r.observations.length/2];
require(minAnswer <= median && median <= maxAnswer, "median is out of min-max range");
r.hotVars.latestAggregatorRoundId++;
s_transmissions[r.hotVars.latestAggregatorRoundId] =
Transmission(median, uint64(block.timestamp));
emit NewTransmission(
r.hotVars.latestAggregatorRoundId,
median,
msg.sender,
r.observations,
r.observers,
r.rawReportContext
);
// Emit these for backwards compatability with offchain consumers
// that only support legacy events
emit NewRound(
r.hotVars.latestAggregatorRoundId,
address(0x0), // use zero address since we don't have anybody "starting" the round here
block.timestamp
);
emit AnswerUpdated(
median,
r.hotVars.latestAggregatorRoundId,
block.timestamp
);
validateAnswer(r.hotVars.latestAggregatorRoundId, median);
}
s_hotVars = r.hotVars;
assert(initialGas < maxUint32);
reimburseAndRewardOracles(uint32(initialGas), r.observers);
}
/*
* v2 Aggregator interface
*/
/**
* @notice median from the most recent report
*/
function latestAnswer()
public
override
view
virtual
returns (int256)
{
return s_transmissions[s_hotVars.latestAggregatorRoundId].answer;
}
/**
* @notice timestamp of block in which last report was transmitted
*/
function latestTimestamp()
public
override
view
virtual
returns (uint256)
{
return s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp;
}
/**
* @notice Aggregator round (NOT OCR round) in which last report was transmitted
*/
function latestRound()
public
override
view
virtual
returns (uint256)
{
return s_hotVars.latestAggregatorRoundId;
}
/**
* @notice median of report from given aggregator round (NOT OCR round)
* @param _roundId the aggregator round of the target report
*/
function getAnswer(uint256 _roundId)
public
override
view
virtual
returns (int256)
{
if (_roundId > 0xFFFFFFFF) { return 0; }
return s_transmissions[uint32(_roundId)].answer;
}
/**
* @notice timestamp of block in which report from given aggregator round was transmitted
* @param _roundId aggregator round (NOT OCR round) of target report
*/
function getTimestamp(uint256 _roundId)
public
override
view
virtual
returns (uint256)
{
if (_roundId > 0xFFFFFFFF) { return 0; }
return s_transmissions[uint32(_roundId)].timestamp;
}
/*
* v3 Aggregator interface
*/
string constant private V3_NO_DATA_ERROR = "No data present";
/**
* @return answers are stored in fixed-point format, with this many digits of precision
*/
uint8 immutable public override decimals;
/**
* @notice aggregator contract version
*/
uint256 constant public override version = 4;
string internal s_description;
/**
* @notice human-readable description of observable this contract is reporting on
*/
function description()
public
override
view
virtual
returns (string memory)
{
return s_description;
}
/**
* @notice details for the given aggregator round
* @param _roundId target aggregator round (NOT OCR round). Must fit in uint32
* @return roundId _roundId
* @return answer median of report from given _roundId
* @return startedAt timestamp of block in which report from given _roundId was transmitted
* @return updatedAt timestamp of block in which report from given _roundId was transmitted
* @return answeredInRound _roundId
*/
function getRoundData(uint80 _roundId)
public
override
view
virtual
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
require(_roundId <= 0xFFFFFFFF, V3_NO_DATA_ERROR);
Transmission memory transmission = s_transmissions[uint32(_roundId)];
return (
_roundId,
transmission.answer,
transmission.timestamp,
transmission.timestamp,
_roundId
);
}
/**
* @notice aggregator details for the most recently transmitted report
* @return roundId aggregator round of latest report (NOT OCR round)
* @return answer median of latest report
* @return startedAt timestamp of block containing latest report
* @return updatedAt timestamp of block containing latest report
* @return answeredInRound aggregator round of latest report
*/
function latestRoundData()
public
override
view
virtual
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
roundId = s_hotVars.latestAggregatorRoundId;
// Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts.
// require(roundId != 0, V3_NO_DATA_ERROR);
Transmission memory transmission = s_transmissions[uint32(roundId)];
return (
roundId,
transmission.answer,
transmission.timestamp,
transmission.timestamp,
roundId
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface AccessControllerInterface {
function hasAccess(address user, bytes calldata data) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface AggregatorValidatorInterface {
function validate(
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title The Owned contract
* @notice A contract with helpers for basic contract ownership.
*/
contract Owned {
address payable public owner;
address private pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor() {
owner = msg.sender;
}
/**
* @dev Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address _to)
external
onlyOwner()
{
pendingOwner = _to;
emit OwnershipTransferRequested(owner, _to);
}
/**
* @dev Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @dev Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only callable by owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./AccessControllerInterface.sol";
import "./LinkTokenInterface.sol";
import "./Owned.sol";
/**
* @notice tracks administration of oracle-reward and gas-reimbursement parameters.
* @dev
* If you read or change this, be sure to read or adjust the comments. They
* track the units of the values under consideration, and are crucial to
* the readability of the operations it specifies.
* @notice
* Trust Model:
* Nothing in this contract prevents a billing admin from setting insane
* values for the billing parameters in setBilling. Oracles
* participating in this contract should regularly check that the
* parameters make sense. Similarly, the outstanding obligations of this
* contract to the oracles can exceed the funds held by the contract.
* Oracles participating in this contract should regularly check that it
* holds sufficient funds and stop interacting with it if funding runs
* out.
* This still leaves oracles with some risk due to TOCTOU issues.
* However, since the sums involved are pretty small (Ethereum
* transactions aren't that expensive in the end) and an oracle would
* likely stop participating in a contract it repeatedly lost money on,
* this risk is deemed acceptable. Oracles should also regularly
* withdraw any funds in the contract to prevent issues where the
* contract becomes underfunded at a later time, and different oracles
* are competing for the left-over funds.
* Finally, note that any change to the set of oracles or to the billing
* parameters will trigger payout of all oracles first (using the old
* parameters), a billing admin cannot take away funds that are already
* marked for payment.
*/
contract OffchainAggregatorBilling is Owned {
// Maximum number of oracles the offchain reporting protocol is designed for
uint256 constant internal maxNumOracles = 31;
// Parameters for oracle payments
struct Billing {
// Highest compensated gas price, in ETH-gwei uints
uint32 maximumGasPrice;
// If gas price is less (in ETH-gwei units), transmitter gets half the savings
uint32 reasonableGasPrice;
// Pay transmitter back this much LINK per unit eth spent on gas
// (1e-6LINK/ETH units)
uint32 microLinkPerEth;
// Fixed LINK reward for each observer, in LINK-gwei units
uint32 linkGweiPerObservation;
// Fixed reward for transmitter, in linkGweiPerObservation units
uint32 linkGweiPerTransmission;
}
Billing internal s_billing;
/**
* @return LINK token contract used for billing
*/
LinkTokenInterface immutable public LINK;
AccessControllerInterface internal s_billingAccessController;
// ith element is number of observation rewards due to ith process, plus one.
// This is expected to saturate after an oracle has submitted 65,535
// observations, or about 65535/(3*24*20) = 45 days, given a transmission
// every 3 minutes.
//
// This is always one greater than the actual value, so that when the value is
// reset to zero, we don't end up with a zero value in storage (which would
// result in a higher gas cost, the next time the value is incremented.)
// Calculations using this variable need to take that offset into account.
uint16[maxNumOracles] internal s_oracleObservationsCounts;
// Addresses at which oracles want to receive payments, by transmitter address
mapping (address /* transmitter */ => address /* payment address */)
internal
s_payees;
// Payee addresses which must be approved by the owner
mapping (address /* transmitter */ => address /* payment address */)
internal
s_proposedPayees;
// LINK-wei-denominated reimbursements for gas used by transmitters.
//
// This is always one greater than the actual value, so that when the value is
// reset to zero, we don't end up with a zero value in storage (which would
// result in a higher gas cost, the next time the value is incremented.)
// Calculations using this variable need to take that offset into account.
//
// Argument for overflow safety:
// We have the following maximum intermediate values:
// - 2**40 additions to this variable (epochAndRound is a uint40)
// - 2**32 gas price in ethgwei/gas
// - 1e9 ethwei/ethgwei
// - 2**32 gas since the block gas limit is at ~20 million
// - 2**32 (microlink/eth)
// And we have 2**40 * 2**32 * 1e9 * 2**32 * 2**32 < 2**166
// (we also divide in some places, but that only makes the value smaller)
// We can thus safely use uint256 intermediate values for the computation
// updating this variable.
uint256[maxNumOracles] internal s_gasReimbursementsLinkWei;
// Used for s_oracles[a].role, where a is an address, to track the purpose
// of the address, or to indicate that the address is unset.
enum Role {
// No oracle role has been set for address a
Unset,
// Signing address for the s_oracles[a].index'th oracle. I.e., report
// signatures from this oracle should ecrecover back to address a.
Signer,
// Transmission address for the s_oracles[a].index'th oracle. I.e., if a
// report is received by OffchainAggregator.transmit in which msg.sender is
// a, it is attributed to the s_oracles[a].index'th oracle.
Transmitter
}
struct Oracle {
uint8 index; // Index of oracle in s_signers/s_transmitters
Role role; // Role of the address which mapped to this struct
}
mapping (address /* signer OR transmitter address */ => Oracle)
internal s_oracles;
// s_signers contains the signing address of each oracle
address[] internal s_signers;
// s_transmitters contains the transmission address of each oracle,
// i.e. the address the oracle actually sends transactions to the contract from
address[] internal s_transmitters;
uint256 constant private maxUint16 = (1 << 16) - 1;
uint256 constant internal maxUint128 = (1 << 128) - 1;
constructor(
uint32 _maximumGasPrice,
uint32 _reasonableGasPrice,
uint32 _microLinkPerEth,
uint32 _linkGweiPerObservation,
uint32 _linkGweiPerTransmission,
address _link,
AccessControllerInterface _billingAccessController
)
{
setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
_linkGweiPerObservation, _linkGweiPerTransmission);
setBillingAccessControllerInternal(_billingAccessController);
LINK = LinkTokenInterface(_link);
uint16[maxNumOracles] memory counts; // See s_oracleObservationsCounts docstring
uint256[maxNumOracles] memory gas; // see s_gasReimbursementsLinkWei docstring
for (uint8 i = 0; i < maxNumOracles; i++) {
counts[i] = 1;
gas[i] = 1;
}
s_oracleObservationsCounts = counts;
s_gasReimbursementsLinkWei = gas;
}
/**
* @notice emitted when billing parameters are set
* @param maximumGasPrice highest gas price for which transmitter will be compensated
* @param reasonableGasPrice transmitter will receive reward for gas prices under this value
* @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
* @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
* @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
*/
event BillingSet(
uint32 maximumGasPrice,
uint32 reasonableGasPrice,
uint32 microLinkPerEth,
uint32 linkGweiPerObservation,
uint32 linkGweiPerTransmission
);
function setBillingInternal(
uint32 _maximumGasPrice,
uint32 _reasonableGasPrice,
uint32 _microLinkPerEth,
uint32 _linkGweiPerObservation,
uint32 _linkGweiPerTransmission
)
internal
{
s_billing = Billing(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
_linkGweiPerObservation, _linkGweiPerTransmission);
emit BillingSet(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
_linkGweiPerObservation, _linkGweiPerTransmission);
}
/**
* @notice sets billing parameters
* @param _maximumGasPrice highest gas price for which transmitter will be compensated
* @param _reasonableGasPrice transmitter will receive reward for gas prices under this value
* @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
* @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
* @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
* @dev access control provided by billingAccessController
*/
function setBilling(
uint32 _maximumGasPrice,
uint32 _reasonableGasPrice,
uint32 _microLinkPerEth,
uint32 _linkGweiPerObservation,
uint32 _linkGweiPerTransmission
)
external
{
AccessControllerInterface access = s_billingAccessController;
require(msg.sender == owner || access.hasAccess(msg.sender, msg.data),
"Only owner&billingAdmin can call");
payOracles();
setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
_linkGweiPerObservation, _linkGweiPerTransmission);
}
/**
* @notice gets billing parameters
* @param maximumGasPrice highest gas price for which transmitter will be compensated
* @param reasonableGasPrice transmitter will receive reward for gas prices under this value
* @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units
* @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units
* @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units
*/
function getBilling()
external
view
returns (
uint32 maximumGasPrice,
uint32 reasonableGasPrice,
uint32 microLinkPerEth,
uint32 linkGweiPerObservation,
uint32 linkGweiPerTransmission
)
{
Billing memory billing = s_billing;
return (
billing.maximumGasPrice,
billing.reasonableGasPrice,
billing.microLinkPerEth,
billing.linkGweiPerObservation,
billing.linkGweiPerTransmission
);
}
/**
* @notice emitted when a new access-control contract is set
* @param old the address prior to the current setting
* @param current the address of the new access-control contract
*/
event BillingAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current);
function setBillingAccessControllerInternal(AccessControllerInterface _billingAccessController)
internal
{
AccessControllerInterface oldController = s_billingAccessController;
if (_billingAccessController != oldController) {
s_billingAccessController = _billingAccessController;
emit BillingAccessControllerSet(
oldController,
_billingAccessController
);
}
}
/**
* @notice sets billingAccessController
* @param _billingAccessController new billingAccessController contract address
* @dev only owner can call this
*/
function setBillingAccessController(AccessControllerInterface _billingAccessController)
external
onlyOwner
{
setBillingAccessControllerInternal(_billingAccessController);
}
/**
* @notice gets billingAccessController
* @return address of billingAccessController contract
*/
function billingAccessController()
external
view
returns (AccessControllerInterface)
{
return s_billingAccessController;
}
/**
* @notice withdraws an oracle's payment from the contract
* @param _transmitter the transmitter address of the oracle
* @dev must be called by oracle's payee address
*/
function withdrawPayment(address _transmitter)
external
{
require(msg.sender == s_payees[_transmitter], "Only payee can withdraw");
payOracle(_transmitter);
}
/**
* @notice query an oracle's payment amount
* @param _transmitter the transmitter address of the oracle
*/
function owedPayment(address _transmitter)
public
view
returns (uint256)
{
Oracle memory oracle = s_oracles[_transmitter];
if (oracle.role == Role.Unset) { return 0; }
Billing memory billing = s_billing;
uint256 linkWeiAmount =
uint256(s_oracleObservationsCounts[oracle.index] - 1) *
uint256(billing.linkGweiPerObservation) *
(1 gwei);
linkWeiAmount += s_gasReimbursementsLinkWei[oracle.index] - 1;
return linkWeiAmount;
}
/**
* @notice emitted when an oracle has been paid LINK
* @param transmitter address from which the oracle sends reports to the transmit method
* @param payee address to which the payment is sent
* @param amount amount of LINK sent
*/
event OraclePaid(address transmitter, address payee, uint256 amount);
// payOracle pays out _transmitter's balance to the corresponding payee, and zeros it out
function payOracle(address _transmitter)
internal
{
Oracle memory oracle = s_oracles[_transmitter];
uint256 linkWeiAmount = owedPayment(_transmitter);
if (linkWeiAmount > 0) {
address payee = s_payees[_transmitter];
// Poses no re-entrancy issues, because LINK.transfer does not yield
// control flow.
require(LINK.transfer(payee, linkWeiAmount), "insufficient funds");
s_oracleObservationsCounts[oracle.index] = 1; // "zero" the counts. see var's docstring
s_gasReimbursementsLinkWei[oracle.index] = 1; // "zero" the counts. see var's docstring
emit OraclePaid(_transmitter, payee, linkWeiAmount);
}
}
// payOracles pays out all transmitters, and zeros out their balances.
//
// It's much more gas-efficient to do this as a single operation, to avoid
// hitting storage too much.
function payOracles()
internal
{
Billing memory billing = s_billing;
uint16[maxNumOracles] memory observationsCounts = s_oracleObservationsCounts;
uint256[maxNumOracles] memory gasReimbursementsLinkWei =
s_gasReimbursementsLinkWei;
address[] memory transmitters = s_transmitters;
for (uint transmitteridx = 0; transmitteridx < transmitters.length; transmitteridx++) {
uint256 reimbursementAmountLinkWei = gasReimbursementsLinkWei[transmitteridx] - 1;
uint256 obsCount = observationsCounts[transmitteridx] - 1;
uint256 linkWeiAmount =
obsCount * uint256(billing.linkGweiPerObservation) * (1 gwei) + reimbursementAmountLinkWei;
if (linkWeiAmount > 0) {
address payee = s_payees[transmitters[transmitteridx]];
// Poses no re-entrancy issues, because LINK.transfer does not yield
// control flow.
require(LINK.transfer(payee, linkWeiAmount), "insufficient funds");
observationsCounts[transmitteridx] = 1; // "zero" the counts.
gasReimbursementsLinkWei[transmitteridx] = 1; // "zero" the counts.
emit OraclePaid(transmitters[transmitteridx], payee, linkWeiAmount);
}
}
// "Zero" the accounting storage variables
s_oracleObservationsCounts = observationsCounts;
s_gasReimbursementsLinkWei = gasReimbursementsLinkWei;
}
function oracleRewards(
bytes memory observers,
uint16[maxNumOracles] memory observations
)
internal
pure
returns (uint16[maxNumOracles] memory)
{
// reward each observer-participant with the observer reward
for (uint obsIdx = 0; obsIdx < observers.length; obsIdx++) {
uint8 observer = uint8(observers[obsIdx]);
observations[observer] = saturatingAddUint16(observations[observer], 1);
}
return observations;
}
// This value needs to change if maxNumOracles is increased, or the accounting
// calculations at the bottom of reimburseAndRewardOracles change.
//
// To recalculate it, run the profiler as described in
// ../../profile/README.md, and add up the gas-usage values reported for the
// lines in reimburseAndRewardOracles following the "gasLeft = gasleft()"
// line. E.g., you will see output like this:
//
// 7 uint256 gasLeft = gasleft();
// 29 uint256 gasCostEthWei = transmitterGasCostEthWei(
// 9 uint256(initialGas),
// 3 gasPrice,
// 3 callDataGasCost,
// 3 gasLeft
// .
// .
// .
// 59 uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6;
// .
// .
// .
// 5047 s_gasReimbursementsLinkWei[txOracle.index] =
// 856 s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei +
// 26 uint256(billing.linkGweiPerTransmission) * (1 gwei);
//
// If those were the only lines to be accounted for, you would add up
// 29+9+3+3+3+59+5047+856+26=6035.
uint256 internal constant accountingGasCost = 6035;
// Uncomment the following declaration to compute the remaining gas cost after
// above gasleft(). (This must exist in a base class to OffchainAggregator, so
// it can't go in TestOffchainAggregator.)
//
// uint256 public gasUsedInAccounting;
// Gas price at which the transmitter should be reimbursed, in ETH-gwei/gas
function impliedGasPrice(
uint256 txGasPrice, // ETH-gwei/gas units
uint256 reasonableGasPrice, // ETH-gwei/gas units
uint256 maximumGasPrice // ETH-gwei/gas units
)
internal
pure
returns (uint256)
{
// Reward the transmitter for choosing an efficient gas price: if they manage
// to come in lower than considered reasonable, give them half the savings.
//
// The following calculations are all in units of gwei/gas, i.e. 1e-9ETH/gas
uint256 gasPrice = txGasPrice;
if (txGasPrice < reasonableGasPrice) {
// Give transmitter half the savings for coming in under the reasonable gas price
gasPrice += (reasonableGasPrice - txGasPrice) / 2;
}
// Don't reimburse a gas price higher than maximumGasPrice
return min(gasPrice, maximumGasPrice);
}
// gas reimbursement due the transmitter, in ETH-wei
//
// If this function is changed, accountingGasCost needs to change, too. See
// its docstring
function transmitterGasCostEthWei(
uint256 initialGas,
uint256 gasPrice, // ETH-gwei/gas units
uint256 callDataCost, // gas units
uint256 gasLeft
)
internal
pure
returns (uint128 gasCostEthWei)
{
require(initialGas >= gasLeft, "gasLeft cannot exceed initialGas");
uint256 gasUsed = // gas units
initialGas - gasLeft + // observed gas usage
callDataCost + accountingGasCost; // estimated gas usage
// gasUsed is in gas units, gasPrice is in ETH-gwei/gas units; convert to ETH-wei
uint256 fullGasCostEthWei = gasUsed * gasPrice * (1 gwei);
assert(fullGasCostEthWei < maxUint128); // the entire ETH supply fits in a uint128...
return uint128(fullGasCostEthWei);
}
/**
* @notice withdraw any available funds left in the contract, up to _amount, after accounting for the funds due to participants in past reports
* @param _recipient address to send funds to
* @param _amount maximum amount to withdraw, denominated in LINK-wei.
* @dev access control provided by billingAccessController
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
{
require(msg.sender == owner || s_billingAccessController.hasAccess(msg.sender, msg.data),
"Only owner&billingAdmin can call");
uint256 linkDue = totalLINKDue();
uint256 linkBalance = LINK.balanceOf(address(this));
require(linkBalance >= linkDue, "insufficient balance");
require(LINK.transfer(_recipient, min(linkBalance - linkDue, _amount)), "insufficient funds");
}
// Total LINK due to participants in past reports.
function totalLINKDue()
internal
view
returns (uint256 linkDue)
{
// Argument for overflow safety: We do all computations in
// uint256s. The inputs to linkDue are:
// - the <= 31 observation rewards each of which has less than
// 64 bits (32 bits for billing.linkGweiPerObservation, 32 bits
// for wei/gwei conversion). Hence 69 bits are sufficient for this part.
// - the <= 31 gas reimbursements, each of which consists of at most 166
// bits (see s_gasReimbursementsLinkWei docstring). Hence 171 bits are
// sufficient for this part
// In total, 172 bits are enough.
uint16[maxNumOracles] memory observationCounts = s_oracleObservationsCounts;
for (uint i = 0; i < maxNumOracles; i++) {
linkDue += observationCounts[i] - 1; // Stored value is one greater than actual value
}
Billing memory billing = s_billing;
// Convert linkGweiPerObservation to uint256, or this overflows!
linkDue *= uint256(billing.linkGweiPerObservation) * (1 gwei);
address[] memory transmitters = s_transmitters;
uint256[maxNumOracles] memory gasReimbursementsLinkWei =
s_gasReimbursementsLinkWei;
for (uint i = 0; i < transmitters.length; i++) {
linkDue += uint256(gasReimbursementsLinkWei[i]-1); // Stored value is one greater than actual value
}
}
/**
* @notice allows oracles to check that sufficient LINK balance is available
* @return availableBalance LINK available on this contract, after accounting for outstanding obligations. can become negative
*/
function linkAvailableForPayment()
external
view
returns (int256 availableBalance)
{
// there are at most one billion LINK, so this cast is safe
int256 balance = int256(LINK.balanceOf(address(this)));
// according to the argument in the definition of totalLINKDue,
// totalLINKDue is never greater than 2**172, so this cast is safe
int256 due = int256(totalLINKDue());
// safe from overflow according to above sizes
return int256(balance) - int256(due);
}
/**
* @notice number of observations oracle is due to be reimbursed for
* @param _signerOrTransmitter address used by oracle for signing or transmitting reports
*/
function oracleObservationCount(address _signerOrTransmitter)
external
view
returns (uint16)
{
Oracle memory oracle = s_oracles[_signerOrTransmitter];
if (oracle.role == Role.Unset) { return 0; }
return s_oracleObservationsCounts[oracle.index] - 1;
}
function reimburseAndRewardOracles(
uint32 initialGas,
bytes memory observers
)
internal
{
Oracle memory txOracle = s_oracles[msg.sender];
Billing memory billing = s_billing;
// Reward oracles for providing observations. Oracles are not rewarded
// for providing signatures, because signing is essentially free.
s_oracleObservationsCounts =
oracleRewards(observers, s_oracleObservationsCounts);
// Reimburse transmitter of the report for gas usage
require(txOracle.role == Role.Transmitter,
"sent by undesignated transmitter"
);
uint256 gasPrice = impliedGasPrice(
tx.gasprice / (1 gwei), // convert to ETH-gwei units
billing.reasonableGasPrice,
billing.maximumGasPrice
);
// The following is only an upper bound, as it ignores the cheaper cost for
// 0 bytes. Safe from overflow, because calldata just isn't that long.
uint256 callDataGasCost = 16 * msg.data.length;
// If any changes are made to subsequent calculations, accountingGasCost
// needs to change, too.
uint256 gasLeft = gasleft();
uint256 gasCostEthWei = transmitterGasCostEthWei(
uint256(initialGas),
gasPrice,
callDataGasCost,
gasLeft
);
// microLinkPerEth is 1e-6LINK/ETH units, gasCostEthWei is 1e-18ETH units
// (ETH-wei), product is 1e-24LINK-wei units, dividing by 1e6 gives
// 1e-18LINK units, i.e. LINK-wei units
// Safe from over/underflow, since all components are non-negative,
// gasCostEthWei will always fit into uint128 and microLinkPerEth is a
// uint32 (128+32 < 256!).
uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6;
// Safe from overflow, because gasCostLinkWei < 2**160 and
// billing.linkGweiPerTransmission * (1 gwei) < 2**64 and we increment
// s_gasReimbursementsLinkWei[txOracle.index] at most 2**40 times.
s_gasReimbursementsLinkWei[txOracle.index] =
s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei +
uint256(billing.linkGweiPerTransmission) * (1 gwei); // convert from linkGwei to linkWei
// Uncomment next line to compute the remaining gas cost after above gasleft().
// See OffchainAggregatorBilling.accountingGasCost docstring for more information.
//
// gasUsedInAccounting = gasLeft - gasleft();
}
/*
* Payee management
*/
/**
* @notice emitted when a transfer of an oracle's payee address has been initiated
* @param transmitter address from which the oracle sends reports to the transmit method
* @param current the payeee address for the oracle, prior to this setting
* @param proposed the proposed new payee address for the oracle
*/
event PayeeshipTransferRequested(
address indexed transmitter,
address indexed current,
address indexed proposed
);
/**
* @notice emitted when a transfer of an oracle's payee address has been completed
* @param transmitter address from which the oracle sends reports to the transmit method
* @param current the payeee address for the oracle, prior to this setting
*/
event PayeeshipTransferred(
address indexed transmitter,
address indexed previous,
address indexed current
);
/**
* @notice sets the payees for transmitting addresses
* @param _transmitters addresses oracles use to transmit the reports
* @param _payees addresses of payees corresponding to list of transmitters
* @dev must be called by owner
* @dev cannot be used to change payee addresses, only to initially populate them
*/
function setPayees(
address[] calldata _transmitters,
address[] calldata _payees
)
external
onlyOwner()
{
require(_transmitters.length == _payees.length, "transmitters.size != payees.size");
for (uint i = 0; i < _transmitters.length; i++) {
address transmitter = _transmitters[i];
address payee = _payees[i];
address currentPayee = s_payees[transmitter];
bool zeroedOut = currentPayee == address(0);
require(zeroedOut || currentPayee == payee, "payee already set");
s_payees[transmitter] = payee;
if (currentPayee != payee) {
emit PayeeshipTransferred(transmitter, currentPayee, payee);
}
}
}
/**
* @notice first step of payeeship transfer (safe transfer pattern)
* @param _transmitter transmitter address of oracle whose payee is changing
* @param _proposed new payee address
* @dev can only be called by payee address
*/
function transferPayeeship(
address _transmitter,
address _proposed
)
external
{
require(msg.sender == s_payees[_transmitter], "only current payee can update");
require(msg.sender != _proposed, "cannot transfer to self");
address previousProposed = s_proposedPayees[_transmitter];
s_proposedPayees[_transmitter] = _proposed;
if (previousProposed != _proposed) {
emit PayeeshipTransferRequested(_transmitter, msg.sender, _proposed);
}
}
/**
* @notice second step of payeeship transfer (safe transfer pattern)
* @param _transmitter transmitter address of oracle whose payee is changing
* @dev can only be called by proposed new payee address
*/
function acceptPayeeship(
address _transmitter
)
external
{
require(msg.sender == s_proposedPayees[_transmitter], "only proposed payees can accept");
address currentPayee = s_payees[_transmitter];
s_payees[_transmitter] = msg.sender;
s_proposedPayees[_transmitter] = address(0);
emit PayeeshipTransferred(_transmitter, currentPayee, msg.sender);
}
/*
* Helper functions
*/
function saturatingAddUint16(uint16 _x, uint16 _y)
internal
pure
returns (uint16)
{
return uint16(min(uint256(_x)+uint256(_y), maxUint16));
}
function min(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a < b) { return a; }
return b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
import "./SimpleWriteAccessController.sol";
/**
* @title SimpleReadAccessController
* @notice Gives access to:
* - any externally owned account (note that offchain actors can always read
* any contract storage regardless of onchain access control measures, so this
* does not weaken the access control while improving usability)
* - accounts explicitly added to an access list
* @dev SimpleReadAccessController is not suitable for access controlling writes
* since it grants any externally owned account access! See
* SimpleWriteAccessController for that.
*/
contract SimpleReadAccessController is SimpleWriteAccessController {
/**
* @notice Returns the access of an address
* @param _user The address to query
*/
function hasAccess(
address _user,
bytes memory _calldata
)
public
view
virtual
override
returns (bool)
{
return super.hasAccess(_user, _calldata) || _user == tx.origin;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Owned.sol";
import "./AccessControllerInterface.sol";
/**
* @title SimpleWriteAccessController
* @notice Gives access to accounts explicitly added to an access list by the
* controller's owner.
* @dev does not make any special permissions for externally, see
* SimpleReadAccessController for that.
*/
contract SimpleWriteAccessController is AccessControllerInterface, Owned {
bool public checkEnabled;
mapping(address => bool) internal accessList;
event AddedAccess(address user);
event RemovedAccess(address user);
event CheckAccessEnabled();
event CheckAccessDisabled();
constructor()
{
checkEnabled = true;
}
/**
* @notice Returns the access of an address
* @param _user The address to query
*/
function hasAccess(
address _user,
bytes memory
)
public
view
virtual
override
returns (bool)
{
return accessList[_user] || !checkEnabled;
}
/**
* @notice Adds an address to the access list
* @param _user The address to add
*/
function addAccess(address _user) external onlyOwner() {
addAccessInternal(_user);
}
function addAccessInternal(address _user) internal {
if (!accessList[_user]) {
accessList[_user] = true;
emit AddedAccess(_user);
}
}
/**
* @notice Removes an address from the access list
* @param _user The address to remove
*/
function removeAccess(address _user)
external
onlyOwner()
{
if (accessList[_user]) {
accessList[_user] = false;
emit RemovedAccess(_user);
}
}
/**
* @notice makes the access check enforced
*/
function enableAccessCheck()
external
onlyOwner()
{
if (!checkEnabled) {
checkEnabled = true;
emit CheckAccessEnabled();
}
}
/**
* @notice makes the access check unenforced
*/
function disableAccessCheck()
external
onlyOwner()
{
if (checkEnabled) {
checkEnabled = false;
emit CheckAccessDisabled();
}
}
/**
* @dev reverts if the caller does not have access
*/
modifier checkAccess() {
require(hasAccess(msg.sender, msg.data), "No access");
_;
}
}
| sets billing parameters _maximumGasPrice highest gas price for which transmitter will be compensated _reasonableGasPrice transmitter will receive reward for gas prices under this value _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units access control provided by billingAccessController/ | function setBilling(
uint32 _maximumGasPrice,
uint32 _reasonableGasPrice,
uint32 _microLinkPerEth,
uint32 _linkGweiPerObservation,
uint32 _linkGweiPerTransmission
)
external
{
AccessControllerInterface access = s_billingAccessController;
require(msg.sender == owner || access.hasAccess(msg.sender, msg.data),
"Only owner&billingAdmin can call");
payOracles();
setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth,
_linkGweiPerObservation, _linkGweiPerTransmission);
}
| 51,141 |
pragma experimental ABIEncoderV2;
pragma solidity 0.6.4;
// SPDX-License-Identifier: MIT
library EthAddressLib {
/**
* @dev returns the address used within the protocol to identify ETH
* @return the address assigned to ETH
*/
function ethAddress() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
// 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, 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;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a <= b ? a : b;
}
function abs(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return b - a;
}
return a - b;
}
}
// SPDX-License-Identifier: MIT
contract Exponential {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
using SafeMath for uint256;
function getExp(uint256 num, uint256 denom)
public
pure
returns (uint256 rational)
{
rational = num.mul(expScale).div(denom);
}
function getDiv(uint256 num, uint256 denom)
public
pure
returns (uint256 rational)
{
rational = num.mul(expScale).div(denom);
}
function addExp(uint256 a, uint256 b) public pure returns (uint256 result) {
result = a.add(b);
}
function subExp(uint256 a, uint256 b) public pure returns (uint256 result) {
result = a.sub(b);
}
function mulExp(uint256 a, uint256 b) public pure returns (uint256) {
uint256 doubleScaledProduct = a.mul(b);
uint256 doubleScaledProductWithHalfScale = halfExpScale.add(
doubleScaledProduct
);
return doubleScaledProductWithHalfScale.div(expScale);
}
function divExp(uint256 a, uint256 b) public pure returns (uint256) {
return getDiv(a, b);
}
function mulExp3(
uint256 a,
uint256 b,
uint256 c
) public pure returns (uint256) {
return mulExp(mulExp(a, b), c);
}
function mulScalar(uint256 a, uint256 scalar)
public
pure
returns (uint256 scaled)
{
scaled = a.mul(scalar);
}
function mulScalarTruncate(uint256 a, uint256 scalar)
public
pure
returns (uint256)
{
uint256 product = mulScalar(a, scalar);
return truncate(product);
}
function mulScalarTruncateAddUInt(
uint256 a,
uint256 scalar,
uint256 addend
) public pure returns (uint256) {
uint256 product = mulScalar(a, scalar);
return truncate(product).add(addend);
}
function divScalarByExpTruncate(uint256 scalar, uint256 divisor)
public
pure
returns (uint256)
{
uint256 fraction = divScalarByExp(scalar, divisor);
return truncate(fraction);
}
function divScalarByExp(uint256 scalar, uint256 divisor)
public
pure
returns (uint256)
{
uint256 numerator = expScale.mul(scalar);
return getExp(numerator, divisor);
}
function divScalar(uint256 a, uint256 scalar)
public
pure
returns (uint256)
{
return a.div(scalar);
}
function truncate(uint256 exp) public pure returns (uint256) {
return exp.div(expScale);
}
}
// 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.
*/
function decimals() external view returns (uint8);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
interface IFToken is IERC20 {
function mint(address user, uint256 amount) external returns (bytes memory);
function borrow(address borrower, uint256 borrowAmount)
external
returns (bytes memory);
function withdraw(
address payable withdrawer,
uint256 withdrawTokensIn,
uint256 withdrawAmountIn
) external returns (uint256, bytes memory);
function underlying() external view returns (address);
function accrueInterest() external;
function getAccountState(address account)
external
view
returns (
uint256,
uint256,
uint256
);
function MonitorEventCallback(
address who,
bytes32 funcName,
bytes calldata payload
) external;
//用户存借取还操作后的兑换率
function exchangeRateCurrent() external view returns (uint256 exchangeRate);
function repay(address borrower, uint256 repayAmount)
external
returns (uint256, bytes memory);
function borrowBalanceStored(address account)
external
view
returns (uint256);
function exchangeRateStored() external view returns (uint256 exchangeRate);
function liquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address fTokenCollateral
) external returns (bytes memory);
function borrowBalanceCurrent(address account) external returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function _reduceReserves(uint256 reduceAmount) external;
function _addReservesFresh(uint256 addAmount) external;
function cancellingOut(address striker)
external
returns (bool strikeOk, bytes memory strikeLog);
function APR() external view returns (uint256);
function APY() external view returns (uint256);
function calcBalanceOfUnderlying(address owner)
external
view
returns (uint256);
function borrowSafeRatio() external view returns (uint256);
function tokenCash(address token, address account)
external
view
returns (uint256);
function getBorrowRate() external view returns (uint256);
function addTotalCash(uint256 _addAmount) external;
function subTotalCash(uint256 _subAmount) external;
function totalCash() external view returns (uint256);
function totalReserves() external view returns (uint256);
function totalBorrows() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
interface IOracle {
function get(address token) external view returns (uint256, bool);
}
// 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 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
/**
* @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
enum RewardType {
DefaultType,
Deposit,
Borrow,
Withdraw,
Repay,
Liquidation,
TokenIn, //入金,为还款和存款的组合
TokenOut //出金, 为取款和借款的组合
}
// SPDX-License-Identifier: MIT
interface IBank {
function MonitorEventCallback(bytes32 funcName, bytes calldata payload)
external;
function deposit(address token, uint256 amount) external payable;
function borrow(address token, uint256 amount) external;
function withdraw(address underlying, uint256 withdrawTokens) external;
function withdrawUnderlying(address underlying, uint256 amount) external;
function repay(address token, uint256 amount) external payable;
function liquidateBorrow(
address borrower,
address underlyingBorrow,
address underlyingCollateral,
uint256 repayAmount
) external payable;
function tokenIn(address token, uint256 amountIn) external payable;
function tokenOut(address token, uint256 amountOut) external;
function cancellingOut(address token) external;
function paused() external view returns (bool);
}
// reward token pool interface (FOR)
interface IRewardPool {
function theForceToken() external view returns (address);
function bankController() external view returns (address);
function admin() external view returns (address);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
function withdraw() external;
function setTheForceToken(address _theForceToken) external;
function setBankController(address _bankController) external;
function reward(address who, uint256 amount) external;
}
/**
* @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;
}
// SPDX-License-Identifier: MIT
contract BankController is Exponential, Initializable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Market {
// 原生币种对应的 fToken 地址
address fTokenAddress;
// 币种是否可用
bool isValid;
// 该币种所拥有的质押能力
uint256 collateralAbility;
// 市场所参与的用户
mapping(address => bool) accountsIn;
// 该币种的清算奖励
uint256 liquidationIncentive;
}
// 原生币种地址 => 币种信息
mapping(address => Market) public markets;
address public bankEntryAddress; // bank主合约入口地址
address public theForceToken; // 奖励的FOR token地址
//返利百分比,根据用户存,借,取,还花费的gas返还对应价值比例的奖励token, 奖励FOR数量 = ETH价值 * rewardFactor / price(for), 1e18 scale
mapping(uint256 => uint256) public rewardFactors; // RewardType ==> rewardFactor (1e18 scale);
// 用户地址 =》 币种地址(用户参与的币种)
mapping(address => IFToken[]) public accountAssets;
IFToken[] public allMarkets;
address[] public allUnderlyingMarkets;
IOracle public oracle;
address public mulsig;
//FIXME: 统一权限管理
modifier auth {
require(
msg.sender == admin || msg.sender == bankEntryAddress,
"msg.sender need admin or bank"
);
_;
}
function setBankEntryAddress(address _newBank) external auth {
bankEntryAddress = _newBank;
}
function setTheForceToken(address _theForceToken) external auth {
theForceToken = _theForceToken;
}
function setRewardFactorByType(uint256 rewaradType, uint256 factor)
external
auth
{
rewardFactors[rewaradType] = factor;
}
function marketsContains(address fToken) public view returns (bool) {
uint256 len = allMarkets.length;
for (uint256 i = 0; i < len; ++i) {
if (address(allMarkets[i]) == fToken) {
return true;
}
}
return false;
}
uint256 public closeFactor;
address public admin;
address public proposedAdmin;
// 将FOR奖励池单独放到另外一个合约中
address public rewardPool;
uint256 public transferEthGasCost;
// @notice Borrow caps enforced by borrowAllowed for each token address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
// @notice Supply caps enforced by mintAllowed for each token address. Defaults to zero which corresponds to unlimited supplying.
mapping(address => uint) public supplyCaps;
// 原生token的存,借,取,取,还和清算配置设置
struct TokenConfig {
bool depositDisabled; //存款:true:禁用,false: 启用
bool borrowDisabled;// 借款
bool withdrawDisabled;// 取款
bool repayDisabled; //还款
bool liquidateBorrowDisabled;//清算
}
//underlying => TokenConfig
mapping (address => TokenConfig) public tokenConfigs;
// _setMarketBorrowSupplyCaps = _setMarketBorrowCaps + _setMarketSupplyCaps
function _setMarketBorrowSupplyCaps(address[] calldata tokens, uint[] calldata newBorrowCaps, uint[] calldata newSupplyCaps) external {
require(msg.sender == admin, "only admin can set borrow/supply caps");
uint numMarkets = tokens.length;
uint numBorrowCaps = newBorrowCaps.length;
uint numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps && numMarkets == numSupplyCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[tokens[i]] = newBorrowCaps[i];
supplyCaps[tokens[i]] = newSupplyCaps[i];
}
}
function setTokenConfig(
address t,
bool _depositDisabled,
bool _borrowDisabled,
bool _withdrawDisabled,
bool _repayDisabled,
bool _liquidateBorrowDisabled) external {
require(msg.sender == admin, "only admin can set token configs");
tokenConfigs[t] = TokenConfig(
_depositDisabled,
_borrowDisabled,
_withdrawDisabled,
_repayDisabled,
_liquidateBorrowDisabled
);
}
function initialize(address _mulsig) public initializer {
admin = msg.sender;
mulsig = _mulsig;
transferEthGasCost = 5000;
}
modifier onlyMulSig {
require(msg.sender == mulsig, "require admin");
_;
}
modifier onlyAdmin {
require(msg.sender == admin, "require admin");
_;
}
modifier onlyFToken(address fToken) {
require(marketsContains(fToken), "only supported fToken");
_;
}
event AddTokenToMarket(address underlying, address fToken);
function proposeNewAdmin(address admin_) external onlyMulSig {
proposedAdmin = admin_;
}
function claimAdministration() external {
require(msg.sender == proposedAdmin, "Not proposed admin.");
admin = proposedAdmin;
proposedAdmin = address(0);
}
// 获取原生 token 对应的 fToken 地址
function getFTokeAddress(address underlying) public view returns (address) {
return markets[underlying].fTokenAddress;
}
/**
* @notice Returns the assets an account has entered
返回该账户已经参与的币种
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account)
external
view
returns (IFToken[] memory)
{
IFToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
function checkAccountsIn(address account, IFToken fToken)
external
view
returns (bool)
{
return
markets[IFToken(address(fToken)).underlying()].accountsIn[account];
}
function userEnterMarket(IFToken fToken, address borrower) internal {
Market storage marketToJoin = markets[fToken.underlying()];
require(marketToJoin.isValid, "Market not valid");
if (marketToJoin.accountsIn[borrower]) {
return;
}
marketToJoin.accountsIn[borrower] = true;
accountAssets[borrower].push(fToken);
}
function transferCheck(
address fToken,
address src,
address dst,
uint256 transferTokens
) external onlyFToken(msg.sender) {
withdrawCheck(fToken, src, transferTokens);
userEnterMarket(IFToken(fToken), dst);
}
function withdrawCheck(
address fToken,
address withdrawer,
uint256 withdrawTokens
) public view returns (uint256) {
address underlying = IFToken(fToken).underlying();
require(
markets[underlying].isValid,
"Market not valid"
);
require(!tokenConfigs[underlying].withdrawDisabled, "withdraw disabled");
(uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity(
withdrawer,
IFToken(fToken),
withdrawTokens,
0
);
require(sumCollaterals >= sumBorrows, "Cannot withdraw tokens");
}
// 接收转账
function transferIn(
address account,
address underlying,
uint256 amount
) public payable {
require(msg.sender == bankEntryAddress || msg.sender == account, "auth failed");
if (underlying != EthAddressLib.ethAddress()) {
require(msg.value == 0, "ERC20 do not accecpt ETH.");
uint256 balanceBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(account, address(this), amount);
uint256 balanceAfter = IERC20(underlying).balanceOf(address(this));
require(
balanceAfter - balanceBefore == amount,
"TransferIn amount not valid"
);
// erc 20 => transferFrom
} else {
// 接收 eth 转账,已经通过 payable 转入
require(msg.value >= amount, "Eth value is not enough");
if (msg.value > amount) {
//send back excess ETH
uint256 excessAmount = msg.value.sub(amount);
//solium-disable-next-line
(bool result, ) = account.call{
value: excessAmount,
gas: transferEthGasCost
}("");
require(result, "Transfer of ETH failed");
}
}
}
// 向用户转账
function transferToUser(
address underlying,
address payable account,
uint256 amount
) external onlyFToken(msg.sender) {
require(
markets[IFToken(msg.sender).underlying()].isValid,
"TransferToUser not allowed"
);
transferToUserInternal(underlying, account, amount);
}
function transferToUserInternal(
address underlying,
address payable account,
uint256 amount
) internal {
if (underlying != EthAddressLib.ethAddress()) {
// erc 20
// ERC20(token).safeTransfer(user, _amount);
IERC20(underlying).safeTransfer(account, amount);
} else {
(bool result, ) = account.call{
value: amount,
gas: transferEthGasCost
}("");
require(result, "Transfer of ETH failed");
}
}
//1:1返还
function calcRewardAmount(
uint256 gasSpend,
uint256 gasPrice,
address _for
) public view returns (uint256) {
(uint256 _ethPrice, bool _ethValid) = fetchAssetPrice(
EthAddressLib.ethAddress()
);
(uint256 _forPrice, bool _forValid) = fetchAssetPrice(_for);
if (!_ethValid || !_forValid || IERC20(_for).decimals() != 18) {
return 0;
}
return gasSpend.mul(gasPrice).mul(_ethPrice).div(_forPrice);
}
//0.5 * 1e18, 表返还0.5ETH价值的FOR
//1.5 * 1e18, 表返还1.5倍ETH价值的FOR
function calcRewardAmountByFactor(
uint256 gasSpend,
uint256 gasPrice,
address _for,
uint256 factor
) public view returns (uint256) {
return calcRewardAmount(gasSpend, gasPrice, _for).mul(factor).div(1e18);
}
function setRewardPool(address _rewardPool) external onlyAdmin {
rewardPool = _rewardPool;
}
function setTransferEthGasCost(uint256 _transferEthGasCost)
external
onlyAdmin
{
transferEthGasCost = _transferEthGasCost;
}
function rewardForByType(
address account,
uint256 gasSpend,
uint256 gasPrice,
uint256 rewardType
) external auth {
/*
uint256 amount = calcRewardAmountByFactor(
gasSpend,
gasPrice,
theForceToken,
rewardFactors[rewardType]
);
amount = SafeMath.min(
amount,
IERC20(theForceToken).balanceOf(rewardPool)
);
if (amount > 0) {
IRewardPool(rewardPool).reward(account, amount);
}
*/
}
// 获取实际原生代币的余额
function getCashPrior(address underlying) public view returns (uint256) {
IFToken fToken = IFToken(getFTokeAddress(underlying));
return fToken.totalCash();
}
// 获取将要更新后的原生代币的余额(预判)
function getCashAfter(address underlying, uint256 transferInAmount)
external
view
returns (uint256)
{
return getCashPrior(underlying).add(transferInAmount);
}
function mintCheck(address underlying, address minter, uint256 amount) external {
require(
markets[IFToken(msg.sender).underlying()].isValid,
"MintCheck fails"
);
require(markets[underlying].isValid, "Market not valid");
require(!tokenConfigs[underlying].depositDisabled, "deposit disabled");
uint supplyCap = supplyCaps[underlying];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint totalSupply = IFToken(msg.sender).totalSupply();
uint _exchangeRate = IFToken(msg.sender).exchangeRateStored();
// 兑换率乘总发行ftoken数量,得到原生token数量
uint256 totalUnderlyingSupply = mulScalarTruncate(_exchangeRate, totalSupply);
uint nextTotalUnderlyingSupply = totalUnderlyingSupply.add(amount);
require(nextTotalUnderlyingSupply < supplyCap, "market supply cap reached");
}
if (!markets[underlying].accountsIn[minter]) {
userEnterMarket(IFToken(getFTokeAddress(underlying)), minter);
}
}
function borrowCheck(
address account,
address underlying,
address fToken,
uint256 borrowAmount
) external {
address underlying = IFToken(msg.sender).underlying();
require(
markets[underlying].isValid,
"BorrowCheck fails"
);
require(!tokenConfigs[underlying].borrowDisabled, "borrow disabled");
uint borrowCap = borrowCaps[underlying];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = IFToken(msg.sender).totalBorrows();
uint nextTotalBorrows = totalBorrows.add(borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
require(markets[underlying].isValid, "Market not valid");
(, bool valid) = fetchAssetPrice(underlying);
require(valid, "Price is not valid");
if (!markets[underlying].accountsIn[account]) {
userEnterMarket(IFToken(getFTokeAddress(underlying)), account);
}
// 校验用户流动性,liquidity
(uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity(
account,
IFToken(fToken),
0,
borrowAmount
);
require(sumBorrows > 0, "borrow value too low");
require(sumCollaterals >= sumBorrows, "insufficient liquidity");
}
function repayCheck(address underlying) external view {
require(markets[underlying].isValid, "Market not valid");
require(!tokenConfigs[underlying].repayDisabled, "repay disabled");
}
// 获取用户总体的存款和借款情况
function getTotalDepositAndBorrow(address account)
public
view
returns (uint256, uint256)
{
return getUserLiquidity(account, IFToken(0), 0, 0);
}
// 获取账户流动性
function getAccountLiquidity(address account)
public
view
returns (uint256 liquidity, uint256 shortfall)
{
(uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity(
account,
IFToken(0),
0,
0
);
// These are safe, as the underflow condition is checked first
if (sumCollaterals > sumBorrows) {
return (sumCollaterals - sumBorrows, 0);
} else {
return (0, sumBorrows - sumCollaterals);
}
}
// 不包含FToken的流动性
/*
function getAccountLiquidityExcludeDeposit(address account, address token)
public
view
returns (uint256, uint256)
{
IFToken fToken = IFToken(getFTokeAddress(token));
(uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity(
account,
fToken,
fToken.balanceOf(account), //用户的fToken数量
0
);
// These are safe, as the underflow condition is checked first
if (sumCollaterals > sumBorrows) {
return (sumCollaterals - sumBorrows, 0);
} else {
return (0, sumBorrows - sumCollaterals);
}
}
*/
// Get price of oracle
function fetchAssetPrice(address token)
public
view
returns (uint256, bool)
{
require(address(oracle) != address(0), "oracle not set");
return oracle.get(token);
}
function setOracle(address _oracle) external onlyAdmin {
oracle = IOracle(_oracle);
}
function _supportMarket(
IFToken fToken,
uint256 _collateralAbility,
uint256 _liquidationIncentive
) public onlyAdmin {
address underlying = fToken.underlying();
require(!markets[underlying].isValid, "martket existed");
markets[underlying] = Market({
isValid: true,
collateralAbility: _collateralAbility,
fTokenAddress: address(fToken),
liquidationIncentive: _liquidationIncentive
});
addTokenToMarket(underlying, address(fToken));
}
function addTokenToMarket(address underlying, address fToken) internal {
for (uint256 i = 0; i < allUnderlyingMarkets.length; i++) {
require(
allUnderlyingMarkets[i] != underlying,
"token exists"
);
require(allMarkets[i] != IFToken(fToken), "token exists");
}
allMarkets.push(IFToken(fToken));
allUnderlyingMarkets.push(underlying);
emit AddTokenToMarket(underlying, fToken);
}
function _setCollateralAbility(
address underlying,
uint256 newCollateralAbility
) external onlyAdmin {
require(markets[underlying].isValid, "Market not valid");
Market storage market = markets[underlying];
market.collateralAbility = newCollateralAbility;
}
function setCloseFactor(uint256 _closeFactor) external onlyAdmin {
closeFactor = _closeFactor;
}
// 设置某币种的交易状态,禁止存借取还,清算和转账。
function setMarketIsValid(address underlying, bool isValid) external onlyAdmin {
Market storage market = markets[underlying];
market.isValid = isValid;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() external view returns (IFToken[] memory) {
return allMarkets;
}
function seizeCheck(address cTokenCollateral, address cTokenBorrowed)
external
view
{
require(!IBank(bankEntryAddress).paused(), "system paused!");
require(
markets[IFToken(cTokenCollateral).underlying()].isValid &&
markets[IFToken(cTokenBorrowed).underlying()].isValid &&
marketsContains(cTokenCollateral) && marketsContains(cTokenBorrowed),
"Seize market not valid"
);
}
struct LiquidityLocals {
uint256 sumCollateral;
uint256 sumBorrows;
uint256 fTokenBalance;
uint256 borrowBalance;
uint256 exchangeRate;
uint256 oraclePrice;
uint256 collateralAbility;
uint256 collateral;
}
function getUserLiquidity(
address account,
IFToken fTokenNow,
uint256 withdrawTokens,
uint256 borrowAmount
) public view returns (uint256, uint256) {
// 用户参与的每个币种
IFToken[] memory assets = accountAssets[account];
LiquidityLocals memory vars;
// 对于每个币种
for (uint256 i = 0; i < assets.length; i++) {
IFToken asset = assets[i];
// 获取 fToken 的余额和兑换率
(vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset
.getAccountState(account);
// 该币种的质押率
vars.collateralAbility = markets[asset.underlying()]
.collateralAbility;
// 获取币种价格
(uint256 oraclePrice, bool valid) = fetchAssetPrice(
asset.underlying()
);
require(valid, "Price is not valid");
vars.oraclePrice = oraclePrice;
uint256 fixUnit = calcExchangeUnit(address(asset));
uint256 exchangeRateFixed = mulScalar(vars.exchangeRate, fixUnit);
vars.collateral = mulExp3(
vars.collateralAbility,
exchangeRateFixed,
vars.oraclePrice
);
vars.sumCollateral = mulScalarTruncateAddUInt(
vars.collateral,
vars.fTokenBalance,
vars.sumCollateral
);
vars.borrowBalance = vars.borrowBalance.mul(fixUnit);
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrows
);
// 借款和取款的时候,将当前要操作的数量,直接计算在账户流动性里面
if (asset == fTokenNow) {
// 取款
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.collateral,
withdrawTokens,
vars.sumBorrows
);
borrowAmount = borrowAmount.mul(fixUnit);
// 借款
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrows
);
}
}
return (vars.sumCollateral, vars.sumBorrows);
}
//不包含某一token的流动性
/*
function getUserLiquidityExcludeToken(
address account,
IFToken excludeToken,
IFToken fTokenNow,
uint256 withdrawTokens,
uint256 borrowAmount
) external view returns (uint256, uint256) {
// 用户参与的每个币种
IFToken[] memory assets = accountAssets[account];
LiquidityLocals memory vars;
// 对于每个币种
for (uint256 i = 0; i < assets.length; i++) {
IFToken asset = assets[i];
//不包含token
if (address(asset) == address(excludeToken)) {
continue;
}
// 获取 fToken 的余额和兑换率
(vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset
.getAccountState(account);
// 该币种的质押率
vars.collateralAbility = markets[asset.underlying()]
.collateralAbility;
// 获取币种价格
(uint256 oraclePrice, bool valid) = fetchAssetPrice(
asset.underlying()
);
require(valid, "Price is not valid");
vars.oraclePrice = oraclePrice;
uint256 fixUnit = calcExchangeUnit(address(asset));
uint256 exchangeRateFixed = mulScalar(
vars.exchangeRate,
fixUnit
);
vars.collateral = mulExp3(
vars.collateralAbility,
exchangeRateFixed,
vars.oraclePrice
);
vars.sumCollateral = mulScalarTruncateAddUInt(
vars.collateral,
vars.fTokenBalance,
vars.sumCollateral
);
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrows
);
// 借款和取款的时候,将当前要操作的数量,直接计算在账户流动性里面
if (asset == fTokenNow) {
// 取款
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.collateral,
withdrawTokens,
vars.sumBorrows
);
borrowAmount = borrowAmount.mul(fixUnit);
// 借款
vars.sumBorrows = mulScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrows
);
}
}
return (vars.sumCollateral, vars.sumBorrows);
}
*/
function tokenDecimals(address token) public view returns (uint256) {
return
token == EthAddressLib.ethAddress()
? 18
: uint256(IERC20(token).decimals());
}
//计算user的取款指定token的最大数量
/*
function calcMaxWithdrawAmount(address user, address token)
public
view
returns (uint256)
{
(uint256 depoistValue, uint256 borrowValue) = getTotalDepositAndBorrow(
user
);
if (depoistValue <= borrowValue) {
return 0;
}
uint256 netValue = subExp(depoistValue, borrowValue);
// redeemValue = netValue / collateralAblility;
uint256 redeemValue = divExp(
netValue,
markets[token].collateralAbility
);
(uint256 oraclePrice, bool valid) = fetchAssetPrice(token);
require(valid, "Price is not valid");
uint fixUnit = 10 ** SafeMath.abs(18, tokenDecimals(token));
uint256 redeemAmount = divExp(redeemValue, oraclePrice).div(fixUnit);
IFToken fToken = IFToken(getFTokeAddress(token));
redeemAmount = SafeMath.min(
redeemAmount,
fToken.calcBalanceOfUnderlying(user)
);
return redeemAmount;
}
function calcMaxBorrowAmount(address user, address token)
public
view
returns (uint256)
{
(
uint256 depoistValue,
uint256 borrowValue
) = getAccountLiquidityExcludeDeposit(user, token);
if (depoistValue <= borrowValue) {
return 0;
}
uint256 netValue = subExp(depoistValue, borrowValue);
(uint256 oraclePrice, bool valid) = fetchAssetPrice(token);
require(valid, "Price is not valid");
uint fixUnit = 10 ** SafeMath.abs(18, tokenDecimals(token));
uint256 borrowAmount = divExp(netValue, oraclePrice).div(fixUnit);
return borrowAmount;
}
function calcMaxBorrowAmountWithRatio(address user, address token)
public
view
returns (uint256)
{
IFToken fToken = IFToken(getFTokeAddress(token));
return
SafeMath.mul(calcMaxBorrowAmount(user, token), 1e18).div(fToken.borrowSafeRatio());
}
function calcMaxCashOutAmount(address user, address token)
public
view
returns (uint256)
{
return
addExp(
calcMaxWithdrawAmount(user, token),
calcMaxBorrowAmountWithRatio(user, token)
);
}
*/
function isFTokenValid(address fToken) external view returns (bool) {
return markets[IFToken(fToken).underlying()].isValid;
}
function liquidateBorrowCheck(
address fTokenBorrowed,
address fTokenCollateral,
address borrower,
address liquidator,
uint256 repayAmount
) external onlyFToken(msg.sender) {
address underlyingBorrowed = IFToken(fTokenBorrowed).underlying();
address underlyingCollateral = IFToken(fTokenCollateral).underlying();
require(!tokenConfigs[underlyingBorrowed].liquidateBorrowDisabled, "liquidateBorrow: liquidate borrow disabled");
require(!tokenConfigs[underlyingCollateral].liquidateBorrowDisabled, "liquidateBorrow: liquidate colleteral disabled");
(, uint256 shortfall) = getAccountLiquidity(borrower);
require(shortfall != 0, "Insufficient shortfall");
userEnterMarket(IFToken(fTokenCollateral), liquidator);
uint256 borrowBalance = IFToken(fTokenBorrowed).borrowBalanceStored(
borrower
);
uint256 maxClose = mulScalarTruncate(closeFactor, borrowBalance);
require(repayAmount <= maxClose, "Too much repay");
}
function calcExchangeUnit(address fToken) public view returns (uint256) {
uint256 fTokenDecimals = uint256(IFToken(fToken).decimals());
uint256 underlyingDecimals = IFToken(fToken).underlying() ==
EthAddressLib.ethAddress()
? 18
: uint256(IERC20(IFToken(fToken).underlying()).decimals());
return 10**SafeMath.abs(fTokenDecimals, underlyingDecimals);
}
function liquidateTokens(
address fTokenBorrowed,
address fTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256) {
(uint256 borrowPrice, bool borrowValid) = fetchAssetPrice(
IFToken(fTokenBorrowed).underlying()
);
(uint256 collateralPrice, bool collateralValid) = fetchAssetPrice(
IFToken(fTokenCollateral).underlying()
);
require(borrowValid && collateralValid, "Price not valid");
/*
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint256 exchangeRate = IFToken(fTokenCollateral).exchangeRateStored();
uint256 fixCollateralUnit = calcExchangeUnit(fTokenCollateral);
uint256 fixBorrowlUnit = calcExchangeUnit(fTokenBorrowed);
uint256 numerator = mulExp(
markets[IFToken(fTokenCollateral).underlying()]
.liquidationIncentive,
borrowPrice
);
exchangeRate = exchangeRate.mul(fixCollateralUnit);
actualRepayAmount = actualRepayAmount.mul(fixBorrowlUnit);
uint256 denominator = mulExp(collateralPrice, exchangeRate);
uint256 seizeTokens = mulScalarTruncate(
divExp(numerator, denominator),
actualRepayAmount
);
return seizeTokens;
}
function _setLiquidationIncentive(
address underlying,
uint256 _liquidationIncentive
) public onlyAdmin {
markets[underlying].liquidationIncentive = _liquidationIncentive;
}
struct ReserveWithdrawalLogStruct {
address token_address;
uint256 reserve_withdrawed;
uint256 cheque_token_value;
uint256 loan_interest_rate;
uint256 global_token_reserved;
}
function reduceReserves(
address underlying,
address payable account,
uint256 reduceAmount
) public onlyMulSig {
IFToken fToken = IFToken(getFTokeAddress(underlying));
fToken._reduceReserves(reduceAmount);
transferToUserInternal(underlying, account, reduceAmount);
fToken.subTotalCash(reduceAmount);
ReserveWithdrawalLogStruct memory rds = ReserveWithdrawalLogStruct(
underlying,
reduceAmount,
fToken.exchangeRateStored(),
fToken.getBorrowRate(),
fToken.tokenCash(underlying, address(this))
);
IBank(bankEntryAddress).MonitorEventCallback(
"ReserveWithdrawal",
abi.encode(rds)
);
}
function batchReduceReserves(
address[] calldata underlyings,
address payable account,
uint256[] calldata reduceAmounts
) external onlyMulSig {
require(underlyings.length == reduceAmounts.length, "length not match");
uint256 n = underlyings.length;
for (uint256 i = 0; i < n; i++) {
reduceReserves(underlyings[i], account, reduceAmounts[i]);
}
}
function batchReduceAllReserves(
address[] calldata underlyings,
address payable account
) external onlyMulSig {
uint256 n = underlyings.length;
for (uint i = 0; i < n; i++) {
IFToken fToken = IFToken(getFTokeAddress(underlyings[i]));
uint256 amount = SafeMath.min(fToken.totalReserves(), fToken.tokenCash(underlyings[i], address(this)));
if (amount > 0) {
reduceReserves(underlyings[i], account, amount);
}
}
}
function batchReduceAllReserves(
address payable account
) external onlyMulSig {
uint256 n = allUnderlyingMarkets.length;
for (uint i = 0; i < n; i++) {
address underlying = allUnderlyingMarkets[i];
IFToken fToken = IFToken(getFTokeAddress(underlying));
uint256 amount = SafeMath.min(fToken.totalReserves(), fToken.tokenCash(underlying, address(this)));
if (amount > 0) {
reduceReserves(underlying, account, amount);
}
}
}
struct ReserveDepositLogStruct {
address token_address;
uint256 reserve_funded;
uint256 cheque_token_value;
uint256 loan_interest_rate;
uint256 global_token_reserved;
}
function addReserves(address underlying, uint256 addAmount)
external
payable
{
IFToken fToken = IFToken(getFTokeAddress(underlying));
fToken._addReservesFresh(addAmount);
transferIn(msg.sender, underlying, addAmount);
fToken.addTotalCash(addAmount);
ReserveDepositLogStruct memory rds = ReserveDepositLogStruct(
underlying,
addAmount,
fToken.exchangeRateStored(),
fToken.getBorrowRate(),
fToken.tokenCash(underlying, address(this))
);
IBank(bankEntryAddress).MonitorEventCallback(
"ReserveDeposit",
abi.encode(rds)
);
}
} | reward token pool interface (FOR) | interface IRewardPool {
function theForceToken() external view returns (address);
function bankController() external view returns (address);
function admin() external view returns (address);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
function withdraw() external;
function setTheForceToken(address _theForceToken) external;
function setBankController(address _bankController) external;
function reward(address who, uint256 amount) external;
}
| 1,234,694 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./BToken.sol";
import "./BMath.sol";
import "../interfaces/IFlashLoanRecipient.sol";
/************************************************************************************************
Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f.
Subject to the GPL-3.0 license
*************************************************************************************************/
contract IPool is BToken, BMath {
/**
* @dev Token record data structure
* @param bound is token bound to pool
* @param ready has token been initialized
* @param lastDenormUpdate timestamp of last denorm change
* @param denorm denormalized weight
* @param desiredDenorm desired denormalized weight (used for incremental changes)
* @param index index of address in tokens array
* @param balance token balance
*/
struct Record {
bool bound;
bool ready;
uint40 lastDenormUpdate;
uint96 denorm;
uint96 desiredDenorm;
uint8 index;
uint256 balance;
}
/* --- EVENTS --- */
/** @dev Emitted when tokens are swapped. */
event LOG_SWAP(
address indexed caller,
address indexed tokenIn,
address indexed tokenOut,
uint256 tokenAmountIn,
uint256 tokenAmountOut
);
/** @dev Emitted when underlying tokens are deposited for pool tokens. */
event LOG_JOIN(
address indexed caller,
address indexed tokenIn,
uint256 tokenAmountIn
);
/** @dev Emitted when pool tokens are burned for underlying. */
event LOG_EXIT(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut
);
/** @dev Emitted when a token's weight updates. */
event LOG_DENORM_UPDATED(address indexed token, uint256 newDenorm);
/** @dev Emitted when a token's desired weight is set. */
event LOG_DESIRED_DENORM_SET(address indexed token, uint256 desiredDenorm);
/** @dev Emitted when a token is unbound from the pool. */
event LOG_TOKEN_REMOVED(address token);
/** @dev Emitted when a token is unbound from the pool. */
event LOG_TOKEN_ADDED(
address indexed token,
uint256 desiredDenorm,
uint256 minimumBalance
);
/** @dev Emitted when a token's minimum balance is updated. */
event LOG_MINIMUM_BALANCE_UPDATED(address token, uint256 minimumBalance);
/** @dev Emitted when a token reaches its minimum balance. */
event LOG_TOKEN_READY(address indexed token);
/** @dev Emitted when public trades are enabled or disabled. */
event LOG_PUBLIC_SWAP_TOGGLED(bool publicSwap);
/** @dev Emitted when the maximum tokens value is updated. */
event LOG_MAX_TOKENS_UPDATED(uint256 maxPoolTokens);
/** @dev Emitted when the swap fee is updated. */
event LOG_SWAP_FEE_UPDATED(uint256 swapFee);
/* --- Modifiers --- */
modifier _lock_ {
require(!_mutex, "ERR_REENTRY");
_mutex = true;
_;
_mutex = false;
}
modifier _control_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
_;
}
modifier _public_ {
require(_publicSwap, "ERR_NOT_PUBLIC");
_;
}
/* --- Storage --- */
bool internal _mutex;
// Account with CONTROL role. Able to modify the swap fee,
// adjust token weights, bind and unbind tokens and lock
// public swaps & joins.
address internal _controller;
// Contract that handles unbound tokens.
TokenUnbindHandler internal _unbindHandler;
// True if PUBLIC can call SWAP & JOIN functions
bool internal _publicSwap;
// `setSwapFee` requires CONTROL
uint256 internal _swapFee;
// Array of underlying tokens in the pool.
address[] internal _tokens;
// Internal records of the pool's underlying tokens
mapping(address => Record) internal _records;
// Total denormalized weight of the pool.
uint256 internal _totalWeight;
// Minimum balances for tokens which have been added without the
// requisite initial balance.
mapping(address => uint256) internal _minimumBalances;
// Maximum LP tokens that can be bound.
// Used in alpha to restrict the economic impact of a catastrophic
// failure. It can be gradually increased as the pool continues to
// not be exploited.
uint256 internal _maxPoolTokens;
/* --- Controls --- */
/**
* @dev Sets the controller address and the token name & symbol.
*
* Note: This saves on storage costs for multi-step pool deployment.
*
* @param controller Controller of the pool
* @param name Name of the pool token
* @param symbol Symbol of the pool token
*/
function configure(
address controller,
string calldata name,
string calldata symbol
) external {
require(_controller == address(0), "ERR_CONFIGURED");
require(controller != address(0), "ERR_NULL_ADDRESS");
_controller = controller;
// default fee is 2.5%
_swapFee = BONE / 40;
_initializeToken(name, symbol);
}
/**
* @dev Sets up the initial assets for the pool.
*
* Note: `tokenProvider` must have approved the pool to transfer the
* corresponding `balances` of `tokens`.
*
* @param tokens Underlying tokens to initialize the pool with
* @param balances Initial balances to transfer
* @param denorms Initial denormalized weights for the tokens
* @param tokenProvider Address to transfer the balances from
*/
function initialize(
address[] calldata tokens,
uint256[] calldata balances,
uint96[] calldata denorms,
address tokenProvider,
address unbindHandler
)
external
_control_
{
require(_tokens.length == 0, "ERR_INITIALIZED");
uint256 len = tokens.length;
require(len >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS");
require(len <= MAX_BOUND_TOKENS, "ERR_MAX_TOKENS");
require(balances.length == len && denorms.length == len, "ERR_ARR_LEN");
uint256 totalWeight = 0;
for (uint256 i = 0; i < len; i++) {
// _bind(tokens[i], balances[i], denorms[i]);
address token = tokens[i];
uint96 denorm = denorms[i];
uint256 balance = balances[i];
require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT");
require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE");
_records[token] = Record({
bound: true,
ready: true,
lastDenormUpdate: uint40(now),
denorm: denorm,
desiredDenorm: denorm,
index: uint8(i),
balance: balance
});
_tokens.push(token);
totalWeight = badd(totalWeight, denorm);
_pullUnderlying(token, tokenProvider, balance);
}
require(totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT");
_totalWeight = totalWeight;
_publicSwap = true;
emit LOG_PUBLIC_SWAP_TOGGLED(true);
_mintPoolShare(INIT_POOL_SUPPLY);
_pushPoolShare(tokenProvider, INIT_POOL_SUPPLY);
_unbindHandler = TokenUnbindHandler(unbindHandler);
}
/**
* @dev Sets the maximum number of pool tokens that can be minted.
*
* This value will be used in the alpha to limit the maximum damage
* that can be caused by a catastrophic error. It can be gradually
* increased as the pool continues to not be exploited.
*
* If it is set to 0, the limit will be removed.
*/
function setMaxPoolTokens(uint256 maxPoolTokens) external _control_ {
_maxPoolTokens = maxPoolTokens;
emit LOG_MAX_TOKENS_UPDATED(maxPoolTokens);
}
/* --- Configuration Actions --- */
/**
* @dev Set the swap fee.
* Note: Swap fee must be between 0.0001% and 10%
*/
function setSwapFee(uint256 swapFee) external _control_ {
require(swapFee >= MIN_FEE, "ERR_MIN_FEE");
require(swapFee <= MAX_FEE, "ERR_MAX_FEE");
_swapFee = swapFee;
emit LOG_SWAP_FEE_UPDATED(swapFee);
}
/* --- Token Management Actions --- */
/**
* @dev Sets the desired weights for the pool tokens, which
* will be adjusted over time as they are swapped.
*
* Note: This does not check for duplicate tokens or that the total
* of the desired weights is equal to the target total weight (25).
* Those assumptions should be met in the controller. Further, the
* provided tokens should only include the tokens which are not set
* for removal.
*/
function reweighTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms
)
external
_lock_
_control_
{
uint256 len = tokens.length;
require(desiredDenorms.length == len, "ERR_ARR_LEN");
for (uint256 i = 0; i < len; i++)
_setDesiredDenorm(tokens[i], desiredDenorms[i]);
}
/**
* @dev Update the underlying assets held by the pool and their associated
* weights. Tokens which are not currently bound will be gradually added
* as they are swapped in to reach the provided minimum balances, which must
* be an amount of tokens worth the minimum weight of the total pool value.
* If a currently bound token is not received in this call, the token's
* desired weight will be set to 0.
*/
function reindexTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms,
uint256[] calldata minimumBalances
)
external
_lock_
_control_
{
uint256 len = tokens.length;
require(
desiredDenorms.length == len && minimumBalances.length == len,
"ERR_ARR_LEN"
);
// This size may not be the same as the input size, as it is possible
// to temporarily exceed the index size while tokens are being phased in
// or out.
uint256 tLen = _tokens.length;
bool[] memory receivedIndices = new bool[](tLen);
// We need to read token records in two separate loops, so
// write them to memory to avoid duplicate storage reads.
Record[] memory records = new Record[](len);
// Read all the records from storage and mark which of the existing tokens
// were represented in the reindex call.
for (uint256 i = 0; i < len; i++) {
Record memory record = _records[tokens[i]];
if (record.bound) receivedIndices[record.index] = true;
records[i] = record;
}
// If any bound tokens were not sent in this call, set their desired weights to 0.
for (uint256 i = 0; i < tLen; i++) {
if (!receivedIndices[i]) {
_setDesiredDenorm(_tokens[i], 0);
}
}
for (uint256 i = 0; i < len; i++) {
address token = tokens[i];
// If an input weight is less than the minimum weight, use that instead.
uint96 denorm = desiredDenorms[i];
if (denorm < MIN_WEIGHT) denorm = uint96(MIN_WEIGHT);
if (!records[i].bound) {
// If the token is not bound, bind it.
_bind(token, minimumBalances[i], denorm);
} else {
_setDesiredDenorm(token, denorm);
}
}
}
/**
* @dev Updates the minimum balance for an uninitialized token.
* This becomes useful if a token's external price significantly
* rises after being bound, since the pool can not send a token
* out until it reaches the minimum balance.
*/
function setMinimumBalance(
address token,
uint256 minimumBalance
)
external
_control_
{
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
require(!record.ready, "ERR_READY");
_minimumBalances[token] = minimumBalance;
emit LOG_MINIMUM_BALANCE_UPDATED(token, minimumBalance);
}
/* --- Liquidity Provider Actions --- */
/**
* @dev Mint new pool tokens by providing the proportional amount of each
* underlying token's balance relative to the proportion of pool tokens minted.
*
* For any underlying tokens which are not initialized, the caller must provide
* the proportional share of the minimum balance for the token rather than the
* actual balance.
*/
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn)
external
_lock_
_public_
{
uint256 poolTotal = totalSupply();
uint256 ratio = bdiv(poolAmountOut, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
require(maxAmountsIn.length == _tokens.length, "ERR_ARR_LEN");
uint256 maxPoolTokens = _maxPoolTokens;
if (maxPoolTokens > 0) {
require(
badd(poolTotal, poolAmountOut) <= _maxPoolTokens,
"ERR_MAX_POOL_TOKENS"
);
}
for (uint256 i = 0; i < maxAmountsIn.length; i++) {
address t = _tokens[i];
(Record memory record, uint256 realBalance) = _getInputToken(t);
uint256 tokenAmountIn = bmul(ratio, record.balance);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN");
_updateInputToken(t, record, badd(realBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, t, tokenAmountIn);
_pullUnderlying(t, msg.sender, tokenAmountIn);
}
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
}
/**
* @dev Pay `tokenAmountIn` of `tokenIn` to mint at least `minPoolAmountOut`
* pool tokens.
*
* The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other
* underlying tokens. Thus a swap fee is charged against the input tokens.
*/
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut
)
external
_lock_
_public_
returns (uint256 poolAmountOut)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
require(tokenAmountIn != 0, "ERR_ZERO_IN");
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
poolAmountOut = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn,
_swapFee
);
uint256 maxPoolTokens = _maxPoolTokens;
if (maxPoolTokens > 0) {
require(
badd(_totalSupply, poolAmountOut) <= _maxPoolTokens,
"ERR_MAX_POOL_TOKENS"
);
}
require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT");
_updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return poolAmountOut;
}
/**
* @dev Pay up to `maxAmountIn` of `tokenIn` to mint exactly `poolAmountOut`.
*
* The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other
* underlying tokens. Thus a swap fee is charged against the input tokens.
*/
function joinswapPoolAmountOut(
address tokenIn,
uint256 poolAmountOut,
uint256 maxAmountIn
)
external
_lock_
_public_
returns (uint256 tokenAmountIn)
{
uint256 maxPoolTokens = _maxPoolTokens;
if (maxPoolTokens > 0) {
require(
badd(_totalSupply, poolAmountOut) <= _maxPoolTokens,
"ERR_MAX_POOL_TOKENS"
);
}
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
tokenAmountIn = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut,
_swapFee
);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
_updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return tokenAmountIn;
}
/**
* @dev Burns `poolAmountIn` pool tokens in exchange for the amounts of each
* underlying token's balance proportional to the ratio of tokens burned to
* total pool supply. The amount of each token transferred to the caller must
* be greater than or equal to the associated minimum output amount from the
* `minAmountsOut` array.
*/
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut)
external
_lock_
{
uint256 poolTotal = totalSupply();
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee);
uint256 ratio = bdiv(pAiAfterExitFee, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
_pullPoolShare(msg.sender, poolAmountIn);
_pushPoolShare(_controller, exitFee);
_burnPoolShare(pAiAfterExitFee);
require(minAmountsOut.length == _tokens.length, "ERR_ARR_LEN");
for (uint256 i = 0; i < minAmountsOut.length; i++) {
address t = _tokens[i];
Record memory record = _records[t];
if (record.ready) {
uint256 tokenAmountOut = bmul(ratio, record.balance);
require(tokenAmountOut != 0, "ERR_MATH_APPROX");
require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT");
_records[t].balance = bsub(record.balance, tokenAmountOut);
emit LOG_EXIT(msg.sender, t, tokenAmountOut);
_pushUnderlying(t, msg.sender, tokenAmountOut);
} else {
// If the token is not initialized, it can not exit the pool.
require(minAmountsOut[i] == 0, "ERR_OUT_NOT_READY");
}
}
}
/**
* @dev Burns `poolAmountIn` pool tokens in exchange for at least `minAmountOut`
* of `tokenOut`. Returns the number of tokens sent to the caller.
*
* The pool implicitly burns the tokens for all underlying tokens and swaps them
* to the desired output token. A swap fee is charged against the output tokens.
*/
function exitswapPoolAmountIn(
address tokenOut,
uint256 poolAmountIn,
uint256 minAmountOut
)
external
_lock_
returns (uint256 tokenAmountOut)
{
Record memory outRecord = _getOutputToken(tokenOut);
tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
_records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut);
_decreaseDenorm(outRecord, tokenOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_controller, exitFee);
return tokenAmountOut;
}
/**
* @dev Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`.
* Returns the number of pool tokens burned.
*
* The pool implicitly burns the tokens for all underlying tokens and swaps them
* to the desired output token. A swap fee is charged against the output tokens.
*/
function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
)
external
_lock_
returns (uint256 poolAmountIn)
{
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
poolAmountIn = calcPoolInGivenSingleOut(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountOut,
_swapFee
);
require(poolAmountIn != 0, "ERR_MATH_APPROX");
require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN");
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
_records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut);
_decreaseDenorm(outRecord, tokenOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_controller, exitFee);
return poolAmountIn;
}
/* --- Other --- */
/**
* @dev Absorb any tokens that have been sent to the pool.
* If the token is not bound, it will be sent to the unbound
* token handler.
*/
function gulp(address token) external _lock_ {
Record memory record = _records[token];
uint256 balance = IERC20(token).balanceOf(address(this));
if (record.bound) {
if (!record.ready) {
record.denorm = uint96(MIN_WEIGHT);
_updateInputToken(token, record, balance);
}
} else {
_pushUnderlying(token, address(_unbindHandler), balance);
_unbindHandler.handleUnbindToken(token, balance);
}
}
/* --- Flash Loan --- */
/**
* @dev Execute a flash loan, transferring `amount` of `token` to `recipient`.
* `amount` must be repaid with `swapFee` interest by the end of the transaction.
*
* @param recipient Must implement the IFlashLoanRecipient interface
* @param token Token to borrow
* @param amount Amount to borrow
* @param data Data to send to the recipient in `receiveFlashLoan` call
*/
function flashBorrow(
IFlashLoanRecipient recipient,
address token,
uint256 amount,
bytes calldata data
)
external
_lock_
{
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
uint256 balStart = IERC20(token).balanceOf(address(this));
require(balStart >= amount, "ERR_INSUFFICIENT_BAL");
_pushUnderlying(token, address(recipient), amount);
recipient.receiveFlashLoan(data);
uint256 balEnd = IERC20(token).balanceOf(address(this));
uint256 gained = bsub(balEnd, balStart);
uint256 fee = bmul(balStart, _swapFee);
require(
balEnd > balStart && fee >= gained,
"ERR_INSUFFICIENT_PAYMENT"
);
_records[token].balance = balEnd;
// If the payment brings the token above its minimum balance,
// clear the minimum and mark the token as ready.
if (!record.ready) {
uint256 minimumBalance = _minimumBalances[token];
if (balEnd >= minimumBalance) {
_minimumBalances[token] = 0;
_records[token].ready = true;
_records[token].denorm = uint96(MIN_WEIGHT);
_totalWeight = badd(_totalWeight, MIN_WEIGHT);
}
}
}
/* --- Token Swaps --- */
/**
* @dev Execute a token swap with a specified amount of input
* tokens and a minimum amount of output tokens.
* Note: Will throw if `tokenOut` is uninitialized.
*/
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
)
external
_lock_
_public_
returns (uint256 tokenAmountOut, uint256 spotPriceAfter)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
tokenAmountOut = calcOutGivenIn(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
realInBalance = badd(realInBalance, tokenAmountIn);
_updateInputToken(tokenIn, inRecord, realInBalance);
if (inRecord.ready) {
inRecord.balance = realInBalance;
}
// Update the in-memory record for the spotPriceAfter calculation,
// then update the storage record with the local balance.
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
_records[tokenOut].balance = outRecord.balance;
// If needed, update the output token's weight.
_decreaseDenorm(outRecord, tokenOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX_2");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
return (tokenAmountOut, spotPriceAfter);
}
/**
* @dev Trades at most `maxAmountIn` of `tokenIn` for exactly `tokenAmountOut`
* of `tokenOut`.
* Returns the actual input amount and the new spot price after the swap,
* which can not exceed `maxPrice`.
*/
function swapExactAmountOut(
address tokenIn,
uint256 maxAmountIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPrice
)
external
_lock_
_public_
returns (uint256 tokenAmountIn, uint256 spotPriceAfter)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
tokenAmountIn = calcInGivenOut(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountOut,
_swapFee
);
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
// Update the balance and (if necessary) weight of the input token.
realInBalance = badd(realInBalance, tokenAmountIn);
_updateInputToken(tokenIn, inRecord, realInBalance);
if (inRecord.ready) {
inRecord.balance = realInBalance;
}
// Update the in-memory record for the spotPriceAfter calculation,
// then update the storage record with the local balance.
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
_records[tokenOut].balance = outRecord.balance;
// If needed, update the output token's weight.
_decreaseDenorm(outRecord, tokenOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
return (tokenAmountIn, spotPriceAfter);
}
/* --- Config Queries --- */
/**
* @dev Check if swapping tokens and joining the pool is allowed.
*/
function isPublicSwap() external view returns (bool isPublic) {
isPublic = _publicSwap;
}
function getSwapFee() external view returns (uint256 swapFee) {
swapFee = _swapFee;
}
/**
* @dev Returns the controller address.
*/
function getController()
external
view
returns (address controller)
{
controller = _controller;
}
/* --- Token Queries --- */
function getMaxPoolTokens() external view returns (uint256) {
return _maxPoolTokens;
}
/**
* @dev Check if a token is bound to the pool.
*/
function isBound(address t) external view returns (bool) {
return _records[t].bound;
}
/**
* @dev Get the number of tokens bound to the pool.
*/
function getNumTokens() external
view
returns (uint256 num)
{
num = _tokens.length;
}
/**
* @dev Get all bound tokens.
*/
function getCurrentTokens()
external
view
returns (address[] memory tokens)
{
return _tokens;
}
/**
* @dev Returns the list of tokens which have a desired weight above 0.
* Tokens with a desired weight of 0 are set to be phased out of the pool.
*/
function getCurrentDesiredTokens()
external
view
returns (address[] memory tokens)
{
address[] memory tempTokens = _tokens;
tokens = new address[](tempTokens.length);
uint256 usedIndex = 0;
for (uint256 i = 0; i < tokens.length; i++) {
address token = tempTokens[i];
Record memory record = _records[token];
if (record.desiredDenorm > 0) {
tokens[usedIndex++] = token;
}
}
assembly { mstore(tokens, usedIndex) }
}
/**
* @dev Get the denormalized weight of a bound token.
*/
function getDenormalizedWeight(address token)
external
view
returns (uint256 denorm)
{
require(_records[token].bound, "ERR_NOT_BOUND");
denorm = _records[token].denorm;
}
/**
* @dev Get the record for a token bound to the pool.
*/
function getTokenRecord(address token)
external
view
returns (Record memory record)
{
record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
}
/**
* @dev Finds the first token which is initialized and
* returns the address of that token and the extrapolated
* value of the pool in that token.
*
* The value is extrapolated by multiplying the token's
* balance by the reciprocal of its normalized weight.
*/
function extrapolatePoolValueFromToken()
external
view
returns (address token, uint256 extrapolatedValue)
{
uint256 len = _tokens.length;
for (uint256 i = 0; i < len; i++) {
token = _tokens[i];
if (!_records[token].ready) continue;
extrapolatedValue = bmul(
_records[token].balance,
bdiv(_totalWeight, _records[token].denorm)
);
break;
}
require(extrapolatedValue > 0, "ERR_NONE_READY");
}
/**
* @dev Get the total denormalized weight of the pool.
*/
function getTotalDenormalizedWeight()
external
view
returns (uint256 totalDenorm)
{
totalDenorm = _totalWeight;
}
/**
* @dev Get the stored balance of a bound token.
*/
function getBalance(address token)
external
view
returns (uint256 balance)
{
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
balance = record.balance;
}
/**
* @dev Get the minimum balance of an uninitialized token.
* Note: Throws if the token is initialized.
*/
function getMinimumBalance(address token)
external
view
returns (uint256 minimumBalance)
{
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
require(!record.ready, "ERR_READY");
minimumBalance = _minimumBalances[token];
}
/**
* @dev Get the balance of a token which is used in price
* calculations. If the token is initialized, this is the
* stored balance; if not, this is the minimum balance.
*/
function getUsedBalance(address token)
external
view
returns (uint256 usedBalance)
{
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
if (!record.ready) {
usedBalance = _minimumBalances[token];
} else {
usedBalance = record.balance;
}
}
/* --- Price Queries --- */
/**
* @dev Get the spot price for `tokenOut` in terms of `tokenIn`.
*/
function getSpotPrice(address tokenIn, address tokenOut)
external
view
returns (uint256 spotPrice)
{
(Record memory inRecord,) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
return
calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
}
/* --- Pool Share Internal Functions --- */
function _pullPoolShare(address from, uint256 amount) internal {
_pull(from, amount);
}
function _pushPoolShare(address to, uint256 amount) internal {
_push(to, amount);
}
function _mintPoolShare(uint256 amount) internal {
_mint(amount);
}
function _burnPoolShare(uint256 amount) internal {
_burn(amount);
}
/* --- Underlying Token Internal Functions --- */
// 'Underlying' token-manipulation functions make external calls but are NOT locked
// You must `_lock_` or otherwise ensure reentry-safety
function _pullUnderlying(
address erc20,
address from,
uint256 amount
) internal {
(bool success, bytes memory data) = erc20.call(
abi.encodeWithSelector(
IERC20.transferFrom.selector,
from,
address(this),
amount
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"ERR_ERC20_FALSE"
);
}
function _pushUnderlying(
address erc20,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = erc20.call(
abi.encodeWithSelector(
IERC20.transfer.selector,
to,
amount
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"ERR_ERC20_FALSE"
);
}
/* --- Token Management Internal Functions --- */
/**
* @dev Bind a token by address without actually depositing a balance.
* The token will be unable to be swapped out until it reaches the minimum balance.
* Note: Token must not already be bound.
* Note: `minimumBalance` should represent an amount of the token which is worth
* the portion of the current pool value represented by the minimum weight.
* @param token Address of the token to bind
* @param minimumBalance minimum balance to reach before the token can be swapped out
* @param desiredDenorm Desired weight for the token.
*/
function _bind(
address token,
uint256 minimumBalance,
uint96 desiredDenorm
) internal {
require(!_records[token].bound, "ERR_IS_BOUND");
require(desiredDenorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT");
require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
require(minimumBalance >= MIN_BALANCE, "ERR_MIN_BALANCE");
_records[token] = Record({
bound: true,
ready: false,
lastDenormUpdate: 0,
denorm: 0,
desiredDenorm: desiredDenorm,
index: uint8(_tokens.length),
balance: 0
});
_tokens.push(token);
_minimumBalances[token] = minimumBalance;
emit LOG_TOKEN_ADDED(token, desiredDenorm, minimumBalance);
}
/**
* @dev Remove a token from the pool.
* Replaces the address in the tokens array with the last address,
* then removes it from the array.
* Note: This should only be called after the total weight has been adjusted.
* Note: Must be called in a function with:
* - _lock_ modifier to prevent reentrance
* - requirement that the token is bound
*/
function _unbind(address token) internal {
Record memory record = _records[token];
uint256 tokenBalance = record.balance;
// Swap the token-to-unbind with the last token,
// then delete the last token
uint256 index = record.index;
uint256 last = _tokens.length - 1;
// Only swap the token with the last token if it is not
// already at the end of the array.
if (index != last) {
_tokens[index] = _tokens[last];
_records[_tokens[index]].index = uint8(index);
}
_tokens.pop();
_records[token] = Record({
bound: false,
ready: false,
lastDenormUpdate: 0,
denorm: 0,
desiredDenorm: 0,
index: 0,
balance: 0
});
// transfer any remaining tokens out
_pushUnderlying(token, address(_unbindHandler), tokenBalance);
_unbindHandler.handleUnbindToken(token, tokenBalance);
emit LOG_TOKEN_REMOVED(token);
}
function _setDesiredDenorm(address token, uint96 desiredDenorm) internal {
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
// If the desired weight is 0, this will trigger a gradual unbinding of the token.
// Therefore the weight only needs to be above the minimum weight if it isn't 0.
require(
desiredDenorm >= MIN_WEIGHT || desiredDenorm == 0,
"ERR_MIN_WEIGHT"
);
require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
record.desiredDenorm = desiredDenorm;
_records[token].desiredDenorm = desiredDenorm;
emit LOG_DESIRED_DENORM_SET(token, desiredDenorm);
}
function _increaseDenorm(Record memory record, address token) internal {
// If the weight does not need to increase or the token is not
// initialized, don't do anything.
if (
record.denorm >= record.desiredDenorm ||
!record.ready ||
now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY
) return;
uint96 oldWeight = record.denorm;
uint96 denorm = record.desiredDenorm;
uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT);
uint256 diff = bsub(denorm, oldWeight);
if (diff > maxDiff) {
denorm = uint96(badd(oldWeight, maxDiff));
diff = maxDiff;
}
_totalWeight = badd(_totalWeight, diff);
require(_totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT");
// Update the in-memory denorm value for spot-price computations.
record.denorm = denorm;
// Update the storage record
_records[token].denorm = denorm;
_records[token].lastDenormUpdate = uint40(now);
emit LOG_DENORM_UPDATED(token, denorm);
}
function _decreaseDenorm(Record memory record, address token) internal {
// If the weight does not need to decrease, don't do anything.
if (
record.denorm <= record.desiredDenorm ||
!record.ready ||
now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY
) return;
uint96 oldWeight = record.denorm;
uint96 denorm = record.desiredDenorm;
uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT);
uint256 diff = bsub(oldWeight, denorm);
if (diff > maxDiff) {
denorm = uint96(bsub(oldWeight, maxDiff));
diff = maxDiff;
}
if (denorm <= MIN_WEIGHT) {
denorm = 0;
_totalWeight = bsub(_totalWeight, denorm);
// Because this is removing the token from the pool, the
// in-memory denorm value is irrelevant, as it is only used
// to calculate the new spot price, but the spot price calc
// will throw if it is passed 0 for the denorm.
_unbind(token);
} else {
_totalWeight = bsub(_totalWeight, diff);
// Update the in-memory denorm value for spot-price computations.
record.denorm = denorm;
// Update the stored denorm value
_records[token].denorm = denorm;
_records[token].lastDenormUpdate = uint40(now);
emit LOG_DENORM_UPDATED(token, denorm);
}
}
/**
* @dev Handles weight changes and initialization of an
* input token.
*
* If the token is not initialized and the new balance is
* still below the minimum, this will not do anything.
*
* If the token is not initialized but the new balance will
* bring the token above the minimum balance, this will
* mark the token as initialized, remove the minimum
* balance and set the weight to the minimum weight plus
* 1%.
*
*
* @param token Address of the input token
* @param record Token record with minimums applied to the balance
* and weight if the token was uninitialized.
*/
function _updateInputToken(
address token,
Record memory record,
uint256 realBalance
)
internal
{
if (!record.ready) {
// Check if the minimum balance has been reached
if (realBalance >= record.balance) {
// Remove the minimum balance record
_minimumBalances[token] = 0;
// Mark the token as initialized
_records[token].ready = true;
record.ready = true;
emit LOG_TOKEN_READY(token);
// Set the initial denorm value to the minimum weight times one plus
// the ratio of the increase in balance over the minimum to the minimum
// balance.
// weight = (1 + ((bal - min_bal) / min_bal)) * min_weight
uint256 additionalBalance = bsub(realBalance, record.balance);
uint256 balRatio = bdiv(additionalBalance, record.balance);
record.denorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio)));
_records[token].denorm = record.denorm;
_records[token].lastDenormUpdate = uint40(now);
_totalWeight = badd(_totalWeight, record.denorm);
} else {
uint256 realToMinRatio = bdiv(
bsub(record.balance, realBalance),
record.balance
);
uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio);
record.denorm = uint96(badd(MIN_WEIGHT, weightPremium));
}
// If the token is still not ready, do not adjust the weight.
} else {
// If the token is already initialized, update the weight (if any adjustment
// is needed).
_increaseDenorm(record, token);
}
// Regardless of whether the token is initialized, store the actual new balance.
_records[token].balance = realBalance;
}
/* --- Token Query Internal Functions --- */
/**
* @dev Get the record for a token which is being swapped in.
* The token must be bound to the pool. If the token is not
* initialized (meaning it does not have the minimum balance)
* this function will return the actual balance of the token
* which the pool holds, but set the record's balance and weight
* to the token's minimum balance and the pool's minimum weight.
* This allows the token swap to be priced correctly even if the
* pool does not own any of the tokens.
*/
function _getInputToken(address token)
internal
view
returns (Record memory record, uint256 realBalance)
{
record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
realBalance = record.balance;
// If the input token is not initialized, we use the minimum
// initial weight and minimum initial balance instead of the
// real values for price and output calculations.
if (!record.ready) {
record.balance = _minimumBalances[token];
uint256 realToMinRatio = bdiv(
bsub(record.balance, realBalance),
record.balance
);
uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio);
record.denorm = uint96(badd(MIN_WEIGHT, weightPremium));
}
}
function _getOutputToken(address token)
internal
view
returns (Record memory record)
{
record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
// Tokens which have not reached their minimum balance can not be
// swapped out.
require(record.ready, "ERR_OUT_NOT_READY");
}
}
interface TokenUnbindHandler {
/**
* @dev Receive `amount` of `token` from the pool.
*/
function handleUnbindToken(address token, uint256 amount) external;
} | Sets the controller address and the token name & symbol. Note: This saves on storage costs for multi-step pool deployment. controller Controller of the pool name Name of the pool token symbol Symbol of the pool token/ default fee is 2.5% | function configure(
address controller,
string calldata name,
string calldata symbol
) external {
require(_controller == address(0), "ERR_CONFIGURED");
require(controller != address(0), "ERR_NULL_ADDRESS");
_controller = controller;
_swapFee = BONE / 40;
_initializeToken(name, symbol);
}
| 2,560,652 |
/**
*Submitted for verification at Etherscan.io on 2021-02-09
*/
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface BPool {
function getCurrentTokens() external view returns (address[] memory tokens);
function getNormalizedWeight(address token) external view returns (uint256);
function getBalance(address token) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
interface ISmartBPool {
function bPool() external view returns (BPool);
function totalSupply() external view returns (uint256);
}
/************
@title IPriceOracle interface
@notice Interface for the Aave price oracle.*/
interface IPriceOracle {
/***********
@dev returns the asset price in ETH
*/
function getAssetPrice(address _asset) external view returns (uint256);
}
contract BConst {
uint256 public constant BONE = 10**18;
uint256 public constant MIN_BOUND_TOKENS = 2;
uint256 public constant MAX_BOUND_TOKENS = 8;
uint256 public constant MIN_FEE = BONE / 10**6;
uint256 public constant MAX_FEE = BONE / 10;
uint256 public constant EXIT_FEE = 0;
uint256 public constant MIN_WEIGHT = BONE;
uint256 public constant MAX_WEIGHT = BONE * 50;
uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint256 public constant MIN_BALANCE = BONE / 10**12;
uint256 public constant INIT_POOL_SUPPLY = BONE * 100;
uint256 public constant MIN_BPOW_BASE = 1 wei;
uint256 public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint256 public constant BPOW_PRECISION = BONE / 10**10;
uint256 public constant MAX_IN_RATIO = BONE / 2;
uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
contract BNum is BConst {
function btoi(uint256 a) internal pure returns (uint256) {
return a / BONE;
}
function bfloor(uint256 a) internal pure returns (uint256) {
return btoi(a) * BONE;
}
function badd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'ERR_ADD_OVERFLOW');
return c;
}
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool flag) = bsubSign(a, b);
require(!flag, 'ERR_SUB_UNDERFLOW');
return c;
}
function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) {
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, 'ERR_MUL_OVERFLOW');
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, 'ERR_MUL_OVERFLOW');
uint256 c2 = c1 / BONE;
return c2;
}
function bdiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, 'ERR_DIV_ZERO');
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, 'ERR_DIV_INTERNAL'); // bmul overflow
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, 'ERR_DIV_INTERNAL'); // badd require
uint256 c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint256 a, uint256 n) internal pure returns (uint256) {
uint256 z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint256 base, uint256 exp) internal pure returns (uint256) {
require(base >= MIN_BPOW_BASE, 'ERR_BPOW_BASE_TOO_LOW');
require(base <= MAX_BPOW_BASE, 'ERR_BPOW_BASE_TOO_HIGH');
uint256 whole = bfloor(exp);
uint256 remain = bsub(exp, whole);
uint256 wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(
uint256 base,
uint256 exp,
uint256 precision
) internal pure returns (uint256) {
// term 0:
uint256 a = exp;
(uint256 x, bool xneg) = bsubSign(base, BONE);
uint256 term = BONE;
uint256 sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BONE;
(uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
/** @title NaiveBalancerSmartPoolPriceProvider
* @notice Price provider for a balancer pool token
* - NAIVE CALCULATION, USE ONLY FOR PRICE FETCHING
* This implementation assumes the underlying pool on the smart pool is a standard Balancer Shared Pool
* - DON'T USE THIS ORACLE IF FUNDAMENTAL CHANGES ON THE UNDERLYING POOL ARE APPLIED
*/
contract NaiveBalancerSmartPoolPriceProvider is BNum {
ISmartBPool public pool;
address[] public tokens;
uint256[] public weights;
bool[] public isPeggedToEth;
uint8[] public decimals;
IPriceOracle public priceOracle;
/**
* BalancerSmartPoolPriceProvider constructor.
* @param _pool Balancer pool address.
* @param _isPeggedToEth For each token, true if it is pegged to ETH (token order determined by pool.getPool().getFinalTokens()).
* @param _decimals Number of decimals for each token (token order determined by pool.getPool().getFinalTokens()).
* @param _priceOracle Aave price oracle.
*/
constructor(
ISmartBPool _pool,
bool[] memory _isPeggedToEth,
uint8[] memory _decimals,
IPriceOracle _priceOracle
) public {
pool = _pool;
BPool underlyingBPool = _pool.bPool();
//Get token list
tokens = underlyingBPool.getCurrentTokens();
uint256 length = tokens.length;
//Validate contructor params
require(length >= 2 && length <= 3, 'ERR_INVALID_POOL_TOKENS_NUMBER');
require(_isPeggedToEth.length == length, 'ERR_INVALID_PEGGED_LENGTH');
require(_decimals.length == length, 'ERR_INVALID_DECIMALS_LENGTH');
for (uint8 i = 0; i < length; i++) {
require(_decimals[i] <= 18, 'ERR_INVALID_DECIMALS');
}
require(address(_priceOracle) != address(0), 'ERR_INVALID_PRICE_PROVIDER');
//Get token normalized weights
for (uint8 i = 0; i < length; i++) {
weights.push(underlyingBPool.getNormalizedWeight(tokens[i]));
}
isPeggedToEth = _isPeggedToEth;
decimals = _decimals;
priceOracle = _priceOracle;
}
/**
* Returns the token balance in ethers by multiplying its balance with its price in ethers.
* @param index Token index.
*/
function getEthBalanceByToken(uint256 index) internal view returns (uint256) {
uint256 pi = isPeggedToEth[index] ? BONE : uint256(priceOracle.getAssetPrice(tokens[index]));
require(pi > 0, 'ERR_NO_ORACLE_PRICE');
uint256 missingDecimals = 18 - decimals[index];
uint256 bi = bmul(pool.bPool().getBalance(tokens[index]), BONE * 10**(missingDecimals));
return bmul(bi, pi);
}
/**
* Calculates the price of the pool token using the formula of weighted arithmetic mean.
* @param ethTotals Balance of each token in ethers.
*/
function getArithmeticMean(uint256[] memory ethTotals) internal view returns (uint256) {
uint256 totalEth = 0;
uint256 length = tokens.length;
for (uint8 i = 0; i < length; i++) {
totalEth = badd(totalEth, ethTotals[i]);
}
return bdiv(totalEth, pool.totalSupply());
}
/**
* Returns the pool's token price.
* It calculates the price using Chainlink as an external price source and the pool's tokens balances using the weighted arithmetic mean formula.
*/
function latestAnswer() external view returns (uint256) {
//Get token balances in ethers
uint256[] memory ethTotals = new uint256[](tokens.length);
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
ethTotals[i] = getEthBalanceByToken(i);
}
return getArithmeticMean(ethTotals);
}
/**
* Returns Balancer pool address.
*/
function getPool() external view returns (ISmartBPool) {
return pool;
}
/**
* Returns all tokens.
*/
function getTokens() external view returns (address[] memory) {
return tokens;
}
/**
* Returns all tokens's weights.
*/
function getWeights() external view returns (uint256[] memory) {
return weights;
}
} | Returns all tokens./ | function getTokens() external view returns (address[] memory) {
return tokens;
}
| 7,869,561 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// website: www.defyswap.finance
//
/*
* @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 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;
}
}
//
/**
* @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() 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 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;
}
}
//
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
//
/**
* @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 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 () internal {
_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;
}
}
//
/**
* @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, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) internal _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 bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-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 override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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(),
_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 {ERC20-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 {ERC20-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 Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public virtual onlyOwner returns (bool) {
_mint(_msgSender(), amount);
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');
_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')
);
}
}
// DFYToken with Governance.
contract DfyToken is ERC20('DefySwap', 'DFY') {
mapping (address => bool) private _isRExcludedFromFee; // excluded list from receive
mapping (address => bool) private _isSExcludedFromFee; // excluded list from send
mapping (address => bool) private _isPair;
uint256 public _burnFee = 40;
uint256 public _ilpFee = 5;
uint256 public _devFee = 4;
uint256 public _maxTxAmount = 10 * 10**6 * 1e18;
uint256 public constant _maxSupply = 10 * 10**6 * 1e18;
address public BURN_VAULT;
address public ILP_VAULT;
address public defyMaster;
address public dev;
address public router;
event NewDeveloper(address);
event ExcludeFromFeeR(address);
event ExcludeFromFeeS(address);
event IncludeInFeeR(address);
event IncludeInFeeS(address);
event SetRouter(address);
event SetPair(address,bool);
event BurnFeeUpdated(uint256,uint256);
event IlpFeeUpdated(uint256,uint256);
event DevFeeUpdated(uint256,uint256);
event SetBurnVault(address);
event SetIlpVault(address);
event SetDefyMaster(address);
event Burn(uint256);
modifier onlyDev() {
require(msg.sender == owner() || msg.sender == dev , "Error: Require developer or Owner");
_;
}
modifier onlyMaster() {
require(msg.sender == defyMaster , "Error: Only DefyMaster");
_;
}
constructor(address _dev, address _bunVault, uint256 _initAmount) public {
require(_dev != address(0), 'DEFY: dev cannot be the zero address');
require(_bunVault != address(0), 'DEFY: burn vault cannot be the zero address');
dev = _dev;
BURN_VAULT = _bunVault;
defyMaster = msg.sender;
mint(msg.sender,_initAmount);
_isRExcludedFromFee[msg.sender] = true;
_isRExcludedFromFee[_bunVault] = true;
_isRExcludedFromFee[_dev] = true;
_isSExcludedFromFee[msg.sender] = true;
_isSExcludedFromFee[_bunVault] = true;
_isSExcludedFromFee[_dev] = true;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (DefyMaster).
function mint(address _to, uint256 _amount) public onlyMaster returns (bool) {
require(_maxSupply >= totalSupply().add(_amount) , "Error : Total Supply Reached" );
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
return true;
}
function mint(uint256 amount) public override onlyMaster returns (bool) {
require(_maxSupply >= totalSupply().add(amount) , "Error : Total Supply Reached" );
_mint(_msgSender(), amount);
_moveDelegates(address(0), _delegates[_msgSender()], amount);
return true;
}
// Exclude an account from receive fee
function excludeFromFeeR(address account) external onlyOwner {
require(!_isRExcludedFromFee[account], "Account is already excluded From receive Fee");
_isRExcludedFromFee[account] = true;
emit ExcludeFromFeeR(account);
}
// Exclude an account from send fee
function excludeFromFeeS(address account) external onlyOwner {
require(!_isSExcludedFromFee[account], "Account is already excluded From send Fee");
_isSExcludedFromFee[account] = true;
emit ExcludeFromFeeS(account);
}
// Include an account in receive fee
function includeInFeeR(address account) external onlyOwner {
require( _isRExcludedFromFee[account], "Account is not excluded From receive Fee");
_isRExcludedFromFee[account] = false;
emit IncludeInFeeR(account);
}
// Include an account in send fee
function includeInFeeS(address account) external onlyOwner {
require( _isSExcludedFromFee[account], "Account is not excluded From send Fee");
_isSExcludedFromFee[account] = false;
emit IncludeInFeeS(account);
}
function setRouter(address _router) external onlyOwner {
require(_router != address(0), 'DEFY: Router cannot be the zero address');
router = _router;
emit SetRouter(_router);
}
function setPair(address _pair, bool _status) external onlyOwner {
require(_pair != address(0), 'DEFY: Pair cannot be the zero address');
_isPair[_pair] = _status;
emit SetPair(_pair , _status);
}
function setBurnFee(uint256 burnFee) external onlyOwner() {
require(burnFee <= 80 , "Error : MaxBurnFee is 8%");
uint256 _previousBurnFee = _burnFee;
_burnFee = burnFee;
emit BurnFeeUpdated(_previousBurnFee,_burnFee);
}
function setDevFee(uint256 devFee) external onlyOwner() {
require(devFee <= 20 , "Error : MaxDevFee is 2%");
uint256 _previousDevFee = _devFee;
_devFee = devFee;
emit DevFeeUpdated(_previousDevFee,_devFee);
}
function setIlpFee(uint256 ilpFee) external onlyOwner() {
require(ilpFee <= 50 , "Error : MaxIlpFee is 5%");
uint256 _previousIlpFee = _ilpFee;
_ilpFee = ilpFee;
emit IlpFeeUpdated(_previousIlpFee,_ilpFee);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent >= 5 , "Error : Minimum maxTxLimit is 5%");
require(maxTxPercent <= 100 , "Error : Maximum maxTxLimit is 100%");
_maxTxAmount = totalSupply().mul(maxTxPercent).div(
10**2
);
}
function setDev(address _dev) external onlyDev {
require(dev != address(0), 'DEFY: dev cannot be the zero address');
_isRExcludedFromFee[dev] = false;
_isSExcludedFromFee[dev] = false;
dev = _dev ;
_isRExcludedFromFee[_dev] = true;
_isSExcludedFromFee[_dev] = true;
emit NewDeveloper(_dev);
}
function setBurnVault(address _burnVault) external onlyMaster {
_isRExcludedFromFee[BURN_VAULT] = false;
_isSExcludedFromFee[BURN_VAULT] = false;
BURN_VAULT = _burnVault ;
_isRExcludedFromFee[_burnVault] = true;
_isSExcludedFromFee[_burnVault] = true;
emit SetBurnVault(_burnVault);
}
function setIlpVault(address _ilpVault) external onlyOwner {
_isRExcludedFromFee[ILP_VAULT] = false;
_isSExcludedFromFee[ILP_VAULT] = false;
ILP_VAULT = _ilpVault;
_isRExcludedFromFee[_ilpVault] = true;
_isSExcludedFromFee[_ilpVault] = true;
emit SetIlpVault(_ilpVault);
}
function setMaster(address master) public onlyMaster {
require(master!= address(0), 'DEFY: DefyMaster cannot be the zero address');
defyMaster = master;
_isRExcludedFromFee[master] = true;
_isSExcludedFromFee[master] = true;
emit SetDefyMaster(master);
}
function isExcludedFromFee(address account) external view returns(bool Rfee , bool SFee) {
return (_isRExcludedFromFee[account] , _isSExcludedFromFee[account] );
}
function isPair(address account) external view returns(bool) {
return _isPair[account];
}
function burnToVault(uint256 amount) public {
_transfer(msg.sender, BURN_VAULT, amount);
}
// @notice Destroys `amount` tokens from `account`, reducing the total supply.
function burn(uint256 amount) public {
_burn(msg.sender, amount);
_moveDelegates(address(0), _delegates[msg.sender], amount);
emit Burn(amount);
}
function transferTaxFree(address recipient, uint256 amount) public returns (bool) {
require(_isPair[_msgSender()] || _msgSender() == router , "DFY: Only DefySwap Router or Defy pair");
super._transfer(_msgSender(), recipient, amount);
return true;
}
function transferFromTaxFree(address sender, address recipient, uint256 amount) public returns (bool) {
require(_isPair[_msgSender()] || _msgSender() == router , "DFY: Only DefySwap Router or Defy pair");
super._transfer(sender, recipient, amount);
super._approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
return true;
}
/// @dev overrides transfer function to meet tokenomics of DEFY
function _transfer(address sender, address recipient, uint256 amount) internal override {
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isSExcludedFromFee[sender] || _isRExcludedFromFee[recipient]) {
super._transfer(sender, recipient, amount);
}
else {
// A percentage of every transfer goes to Burn Vault ,ILP Vault & Dev
uint256 burnAmount = amount.mul(_burnFee).div(1000);
uint256 ilpAmount = amount.mul(_ilpFee).div(1000);
uint256 devAmount = amount.mul(_devFee).div(1000);
// Remainder of transfer sent to recipient
uint256 sendAmount = amount.sub(burnAmount).sub(ilpAmount).sub(devAmount);
require(amount == sendAmount + burnAmount + ilpAmount + devAmount , "DEFY Transfer: Fee value invalid");
super._transfer(sender, BURN_VAULT, burnAmount);
super._transfer(sender, ILP_VAULT, ilpAmount);
super._transfer(sender, dev, devAmount);
super._transfer(sender, recipient, sendAmount);
amount = sendAmount;
}
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DEFY::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DEFY::delegateBySig: invalid nonce");
require(now <= expiry, "DEFY::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, "DEFY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying DEFYs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "DEFY::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
//
/**
* @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');
}
}
}
// DefySTUB interface.
interface DefySTUB is IERC20 {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (DefyMaster).
function mint(address _to, uint256 _amount) external ;
function burn(address _from ,uint256 _amount) external ;
}
//BurnVault
contract BurnVault is Ownable {
DfyToken public defy;
address public defyMaster;
event SetDefyMaster(address);
event Burn(uint256);
modifier onlyDefy() {
require(msg.sender == owner() || msg.sender == defyMaster , "Error: Require developer or Owner");
_;
}
function setDefyMaster (address master) external onlyDefy{
defyMaster = master ;
emit SetDefyMaster(master);
}
function setDefy (address _defy) external onlyDefy{
defy = DfyToken(_defy);
}
function burn () public onlyDefy {
uint256 amount = defy.balanceOf(address(this));
defy.burn(amount);
emit Burn(amount);
}
function burnPortion (uint256 amount) public onlyDefy {
defy.burn(amount);
emit Burn(amount);
}
}
//ILP Interface.
interface ImpermanentLossProtection{
//IMPERMANENT LOSS PROTECTION ABI
function add(address _lpToken, IERC20 _token0, IERC20 _token1, bool _offerILP) external;
function set(uint256 _pid, IERC20 _token0,IERC20 _token1, bool _offerILP) external;
function getDepositValue(uint256 amount, uint256 _pid) external view returns (uint256 userDepValue);
function defyTransfer(address _to, uint256 _amount) external;
function getDefyPrice(uint256 _pid) external view returns (uint256 defyPrice);
}
// DefyMaster is the master of Defy. He can make Dfy and he is a fair guy.
// Have fun reading it. Hopefully it's bug-free. God bless.
contract DefyMaster is Ownable , ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below. (same as rewardDebt)
uint256 rewardDebtDR; // Reward debt Secondary reward. See explanation below.
uint256 depositTime; // Time when the user deposit LP tokens.
uint256 depVal; // LP token value at the deposit time.
//
// We do some fancy math here. Basically, any point in time, the amount of DFYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accDefyPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accDefyPerShare` (and `lastRewardTimestamp`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
DefySTUB stubToken; // STUB / Receipt Token for farmers.
uint256 allocPoint; // How many allocation points assigned to this pool. DFYs to distribute per Second.
uint256 allocPointDR; // How many allocation points assigned to this pool for Secondary Reward.
uint256 depositFee; // LP Deposit fee.
uint256 withdrawalFee; // LP Withdrawal fee
uint256 lastRewardTimestamp; // Last timestamp that DFYs distribution occurs.
uint256 lastRewardTimestampDR; // Last timestamp that Secondary Reward distribution occurs.
uint256 rewardEndTimestamp; // Reward ending Timestamp.
uint256 accDefyPerShare; // Accumulated DFYs per share, times 1e12. See below.
uint256 accSecondRPerShare; // Accumulated Second Reward Tokens per share, times 1e24. See below.
uint256 lpSupply; // Total Lp tokens Staked in farm.
bool impermanentLossProtection; // ILP availability
bool issueStub; // STUB Availability.
}
// The DFY TOKEN!
DfyToken public defy;
// Secondary Reward Token.
IERC20 public secondR;
// BurnVault.
BurnVault public burn_vault;
//ILP Contract
ImpermanentLossProtection public ilp;
// Dev address.
address public devaddr;
// Emergency Dev
address public emDev;
// Deposit/Withdrawal Fee address
address public feeAddress;
// DFY tokens created per second.
uint256 public defyPerSec;
// Secondary Reward distributed per second.
uint256 public secondRPerSec;
// Bonus muliplier for early dfy makers.
uint256 public BONUS_MULTIPLIER = 1;
//Max uint256
uint256 constant MAX_INT = type(uint256).max ;
// Seconds per burn cycle.
uint256 public SECONDS_PER_CYCLE = 365 * 2 days ;
// Max DFY Supply.
uint256 public constant MAX_SUPPLY = 10 * 10**6 * 1e18;
// Next minting cycle start timestamp.
uint256 public nextCycleTimestamp;
// The Timestamp when Secondary Reward mining ends.
uint256 public endTimestampDR = MAX_INT;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// Total allocation points for Dual Reward. Must be the sum of all Dual reward allocation points in all pools.
uint256 public totalAllocPointDR = 0;
// The Timestamp when DFY mining starts.
uint256 public startTimestamp;
modifier onlyDev() {
require(msg.sender == owner() || msg.sender == devaddr , "Error: Require developer or Owner");
_;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetFeeAddress(address newAddress);
event SetDevAddress(address newAddress);
event SetDFY(address dfy);
event SetSecondaryReward(address newToken);
event UpdateEmissionRate(uint256 defyPerSec);
event UpdateSecondaryEmissionRate(uint256 secondRPerSec);
event DFYOwnershipTransfer(address newOwner);
event RenounceEmDev();
event addPool(
uint256 indexed pid,
address lpToken,
uint256 allocPoint,
uint256 allocPointDR,
uint256 depositFee,
uint256 withdrawalFee,
bool offerILP,
bool issueStub,
uint256 rewardEndTimestamp);
event setPool(
uint256 indexed pid,
uint256 allocPoint,
uint256 allocPointDR,
uint256 depositFee,
uint256 withdrawalFee,
bool offerILP,
bool issueStub,
uint256 rewardEndTimestamp);
event UpdateStartTimestamp(uint256 newStartTimestamp);
constructor(
DfyToken _defy,
DefySTUB _stub,
BurnVault _burnvault,
address _devaddr,
address _emDev,
address _feeAddress,
uint256 _startTimestamp,
uint256 _initMint
) public {
require(_devaddr != address(0), 'DEFY: dev cannot be the zero address');
require(_feeAddress != address(0), 'DEFY: FeeAddress cannot be the zero address');
require(_startTimestamp >= block.timestamp , 'DEFY: Invalid start time');
defy = _defy;
burn_vault = _burnvault;
devaddr = _devaddr;
emDev = _emDev;
feeAddress = _feeAddress;
startTimestamp = _startTimestamp;
defyPerSec = (MAX_SUPPLY.sub(_initMint)).div(SECONDS_PER_CYCLE);
nextCycleTimestamp = startTimestamp.add(SECONDS_PER_CYCLE);
// staking pool
poolInfo.push(PoolInfo({
lpToken: _defy,
stubToken: _stub,
allocPoint: 400,
allocPointDR: 0,
depositFee: 0,
withdrawalFee: 0,
lastRewardTimestamp: startTimestamp,
lastRewardTimestampDR: startTimestamp,
rewardEndTimestamp: MAX_INT,
accDefyPerShare: 0,
accSecondRPerShare: 0,
lpSupply: 0,
impermanentLossProtection: false,
issueStub: true
}));
totalAllocPoint = 400;
}
function setImpermanentLossProtection(address _ilp)public onlyDev returns (bool){
require(_ilp != address(0), 'DEFY: ILP cannot be the zero address');
ilp = ImpermanentLossProtection(_ilp);
}
function setFeeAddress(address _feeAddress)public onlyDev returns (bool){
require(_feeAddress != address(0), 'DEFY: FeeAddress cannot be the zero address');
feeAddress = _feeAddress;
emit SetFeeAddress(_feeAddress);
return true;
}
function setDFY(DfyToken _dfy)public onlyDev returns (bool){
require(_dfy != DfyToken(0), 'DEFY: DFY cannot be the zero address');
defy = _dfy;
emit SetDFY(address(_dfy));
return true;
}
function setSecondaryReward(IERC20 _rewardToken)public onlyDev returns (bool){
require(_rewardToken != IERC20(0), 'DEFY: SecondaryReward cannot be the zero address');
secondR = _rewardToken;
emit SetSecondaryReward(address(_rewardToken));
return true;
}
function getUserInfo(uint256 pid, address userAddr)
public
view
returns(uint256 deposit, uint256 rewardDebt, uint256 rewardDebtDR, uint256 daysSinceDeposit, uint256 depVal)
{
UserInfo storage user = userInfo[pid][userAddr];
return (user.amount, user.rewardDebt, user.rewardDebtDR, _getDaysSinceDeposit(pid, userAddr), user.depVal);
}
//Time Functions
function getDaysSinceDeposit(uint256 pid, address userAddr)
external
view
returns (uint256 daysSinceDeposit)
{
return _getDaysSinceDeposit(pid, userAddr);
}
function _getDaysSinceDeposit(uint256 _pid, address _userAddr)
internal
view
returns (uint256)
{
UserInfo storage user = userInfo[_pid][_userAddr];
if (block.timestamp < user.depositTime){
return 0;
}else{
return (block.timestamp.sub(user.depositTime)) / 1 days;
}
}
function checkForIL(uint256 pid, address userAddr)
external
view
returns (uint256 extraDefy)
{
UserInfo storage user = userInfo[pid][userAddr];
return _checkForIL(pid, user);
}
function _checkForIL(uint256 _pid, UserInfo storage user)
internal
view
returns (uint256)
{
uint256 defyPrice = ilp.getDefyPrice(_pid);
uint256 currentVal = ilp.getDepositValue(user.amount, _pid);
if(currentVal < user.depVal){
uint256 difference = user.depVal.sub(currentVal);
return difference.div(defyPrice);
}else return 0;
}
function setStartTimestamp(uint256 sTimestamp) public onlyDev{
require(sTimestamp > block.timestamp, "Invalid Timestamp");
startTimestamp = sTimestamp;
emit UpdateStartTimestamp(sTimestamp);
}
function updateMultiplier(uint256 multiplierNumber) public onlyDev {
require(multiplierNumber != 0, " multiplierNumber should not be null");
BONUS_MULTIPLIER = multiplierNumber;
}
function updateEmissionRate(uint256 endTimestamp) external {
require(endTimestamp > ((block.timestamp).add(182 days)), "Minimum duration is 6 months");
require ( msg.sender == devaddr , "only dev!");
massUpdatePools();
SECONDS_PER_CYCLE = endTimestamp.sub(block.timestamp);
defyPerSec = MAX_SUPPLY.sub(defy.totalSupply()).div(SECONDS_PER_CYCLE);
nextCycleTimestamp = endTimestamp;
emit UpdateEmissionRate(defyPerSec);
}
function updateReward() internal {
uint256 burnAmount = defy.balanceOf(address(burn_vault));
defyPerSec = burnAmount.div(SECONDS_PER_CYCLE);
burn_vault.burn();
emit UpdateEmissionRate(defyPerSec);
}
function updateSecondReward(uint256 _reward, uint256 _endTimestamp) public onlyOwner{
require(_endTimestamp > block.timestamp , "invalid End timestamp");
massUpdatePools();
endTimestampDR = _endTimestamp;
secondRPerSec = 0;
massUpdatePools();
secondRPerSec = _reward.div((_endTimestamp).sub(block.timestamp));
emit UpdateSecondaryEmissionRate(secondRPerSec);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
// XXX DO NOT set ILP for non DFY pairs.
function add(
uint256 _allocPoint,
uint256 _allocPointDR,
IERC20 _lpToken,
DefySTUB _stub,
IERC20 _token0,
IERC20 _token1,
uint256 _depositFee,
uint256 _withdrawalFee,
bool _offerILP,
bool _issueSTUB,
uint256 _rewardEndTimestamp
) public onlyDev {
require(_depositFee <= 600, "Add : Max Deposit Fee is 6%");
require(_withdrawalFee <= 600, "Add : Max Deposit Fee is 6%");
require(_rewardEndTimestamp > block.timestamp , "Add: invalid rewardEndTimestamp");
massUpdatePools();
ilp.add(address(_lpToken), _token0, _token1, _offerILP);
uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
totalAllocPointDR = totalAllocPointDR.add(_allocPointDR);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
stubToken: _stub,
allocPoint: _allocPoint,
allocPointDR: _allocPointDR,
depositFee: _depositFee,
withdrawalFee: _withdrawalFee,
lastRewardTimestamp: lastRewardTimestamp,
lastRewardTimestampDR: lastRewardTimestamp,
rewardEndTimestamp: _rewardEndTimestamp,
accDefyPerShare: 0,
accSecondRPerShare: 0,
lpSupply: 0,
impermanentLossProtection: _offerILP,
issueStub: _issueSTUB
}));
emit addPool(poolInfo.length - 1, address(_lpToken), _allocPoint, _allocPointDR, _depositFee, _withdrawalFee, _offerILP, _issueSTUB, _rewardEndTimestamp);
}
// Update the given pool's DFY allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
uint256 _allocPointDR,
IERC20 _token0,
IERC20 _token1,
uint256 _depositFee,
uint256 _withdrawalFee,
bool _offerILP,
bool _issueSTUB,
uint256 _rewardEndTimestamp
) public onlyOwner {
require(_depositFee <= 600, "Add : Max Deposit Fee is 6%");
require(_withdrawalFee <= 600, "Add : Max Deposit Fee is 6%");
require(_rewardEndTimestamp > block.timestamp , "Add: invalid rewardEndTimestamp");
massUpdatePools();
ilp.set(_pid, _token0, _token1, _offerILP);
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
totalAllocPointDR = totalAllocPointDR.sub(poolInfo[_pid].allocPointDR).add(_allocPointDR);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].allocPointDR = _allocPointDR;
poolInfo[_pid].depositFee = _depositFee;
poolInfo[_pid].withdrawalFee = _withdrawalFee;
poolInfo[_pid].rewardEndTimestamp = _rewardEndTimestamp;
poolInfo[_pid].impermanentLossProtection = _offerILP;
poolInfo[_pid].issueStub = _issueSTUB;
emit setPool(_pid , _allocPoint, _allocPointDR, _depositFee, _withdrawalFee, _offerILP, _issueSTUB, _rewardEndTimestamp);
}
// Return reward multiplier over the given _from to _to Timestamp.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending DFYs on frontend.
function pendingDefy(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accDefyPerShare = pool.accDefyPerShare;
uint256 lpSupply = pool.lpSupply;
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0 && totalAllocPoint != 0) {
uint256 blockTimestamp;
if(block.timestamp < nextCycleTimestamp){
blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestamp = nextCycleTimestamp;
}
uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, blockTimestamp);
uint256 defyReward = multiplier.mul(defyPerSec).mul(pool.allocPoint).div(totalAllocPoint);
accDefyPerShare = accDefyPerShare.add(defyReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accDefyPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to see pending Secondary Reward on frontend.
function pendingSecondR(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSecondRPerShare = pool.accSecondRPerShare;
uint256 lpSupply = pool.lpSupply;
if (block.timestamp > pool.lastRewardTimestampDR && lpSupply != 0 && totalAllocPointDR != 0) {
uint256 blockTimestamp;
if(block.timestamp < endTimestampDR){
blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestamp = endTimestampDR;
}
uint256 multiplier = getMultiplier(pool.lastRewardTimestampDR, blockTimestamp);
uint256 secondRReward = multiplier.mul(secondRPerSec).mul(pool.allocPointDR).div(totalAllocPointDR);
accSecondRPerShare = accSecondRPerShare.add(secondRReward.mul(1e24).div(lpSupply));
}
return user.amount.mul(accSecondRPerShare).div(1e24).sub(user.rewardDebtDR);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
if (block.timestamp > nextCycleTimestamp){
nextCycleTimestamp = (block.timestamp).add(SECONDS_PER_CYCLE);
defyPerSec = 0;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
updateReward();
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePoolPb(uint256 _pid) public {
if (block.timestamp > nextCycleTimestamp){
massUpdatePools();
}
else {
updatePool(_pid);
}
}
function updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTimestamp && block.timestamp <= pool.lastRewardTimestampDR) {
return;
}
uint256 lpSupply = pool.lpSupply;
uint256 blockTimestamp;
if(block.timestamp < nextCycleTimestamp){
blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestamp = nextCycleTimestamp;
}
uint256 blockTimestampDR;
if(block.timestamp < endTimestampDR){
blockTimestampDR = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestampDR = endTimestampDR;
}
if (lpSupply == 0) {
pool.lastRewardTimestamp = blockTimestamp;
pool.lastRewardTimestampDR = blockTimestampDR;
return;
}
if (pool.allocPoint == 0 && pool.allocPointDR == 0) {
pool.lastRewardTimestamp = blockTimestamp;
pool.lastRewardTimestampDR = blockTimestampDR;
return;
}
uint256 defyReward = 0 ;
uint256 secondRReward = 0 ;
if(totalAllocPoint != 0){
uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, blockTimestamp);
defyReward = multiplier.mul(defyPerSec).mul(pool.allocPoint).div(totalAllocPoint);
}
if(totalAllocPointDR != 0){
uint256 multiplier = getMultiplier(pool.lastRewardTimestampDR, blockTimestampDR);
secondRReward = multiplier.mul(secondRPerSec).mul(pool.allocPointDR).div(totalAllocPointDR);
}
if(defyReward > 0 ){
defy.mint(address(this), defyReward);
}
pool.accDefyPerShare = pool.accDefyPerShare.add(defyReward.mul(1e12).div(lpSupply));
pool.accSecondRPerShare = pool.accSecondRPerShare.add(secondRReward.mul(1e24).div(lpSupply));
pool.lastRewardTimestamp = blockTimestamp;
pool.lastRewardTimestampDR = blockTimestampDR;
}
// Deposit LP tokens to DefyMaster for DFY allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePoolPb(_pid);
uint256 amount_ = _amount;
//If the LP token balance is lower than _amount,
//total LP tokens in the wallet will be deposited
if(amount_ > pool.lpToken.balanceOf(msg.sender)){
amount_ = pool.lpToken.balanceOf(msg.sender);
}
//check for ILP DFY
uint256 extraDefy = 0;
if(pool.impermanentLossProtection && user.amount > 0 && _getDaysSinceDeposit(_pid, msg.sender) >= 30){
extraDefy = _checkForIL(_pid, user);
}
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accDefyPerShare).div(1e12).sub(user.rewardDebt);
uint256 pendingDR = user.amount.mul(pool.accSecondRPerShare).div(1e24).sub(user.rewardDebtDR);
if(pending > 0) {
safeDefyTransfer(msg.sender, pending);
}
if(pendingDR > 0) {
safeSecondRTransfer(msg.sender, pendingDR);
}
if(extraDefy > 0 && extraDefy > pending){
ilp.defyTransfer(msg.sender, extraDefy.sub(pending));
}
}
if (amount_ > 0) {
uint256 before = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amount_);
uint256 _after = pool.lpToken.balanceOf(address(this));
amount_ = _after.sub(before); // Real amount of LP transfer to this address
if (pool.depositFee > 0) {
uint256 depositFee = amount_.mul(pool.depositFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
if (pool.issueStub){
pool.stubToken.mint(msg.sender, amount_.sub(depositFee));
}
user.amount = user.amount.add(amount_).sub(depositFee);
pool.lpSupply = pool.lpSupply.add(amount_).sub(depositFee);
} else {
user.amount = user.amount.add(amount_);
pool.lpSupply = pool.lpSupply.add(amount_);
if (pool.issueStub){
pool.stubToken.mint(msg.sender, amount_);
}
}
}
user.depVal = ilp.getDepositValue(user.amount, _pid);
user.depositTime = block.timestamp;
user.rewardDebt = user.amount.mul(pool.accDefyPerShare).div(1e12);
user.rewardDebtDR = user.amount.mul(pool.accSecondRPerShare).div(1e24);
emit Deposit(msg.sender, _pid, amount_);
}
// Withdraw LP tokens from DefyMaster.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0 , "withdraw: nothing to withdraw");
updatePoolPb(_pid);
uint256 amount_ = _amount;
//If the User LP token balance in farm is lower than _amount,
//total User LP tokens in the farm will be withdrawn
if(amount_ > user.amount){
amount_ = user.amount;
}
//ILP
uint256 extraDefy = 0;
if(pool.impermanentLossProtection && user.amount > 0 && _getDaysSinceDeposit(_pid, msg.sender) >= 30){
extraDefy = _checkForIL(_pid, user);
}
uint256 pending = user.amount.mul(pool.accDefyPerShare).div(1e12).sub(user.rewardDebt);
uint256 pendingDR = user.amount.mul(pool.accSecondRPerShare).div(1e24).sub(user.rewardDebtDR);
if(pending > 0) {
safeDefyTransfer(msg.sender, pending);
}
if(pendingDR > 0) {
safeSecondRTransfer(msg.sender, pendingDR);
}
if(extraDefy > 0 && extraDefy > pending){
ilp.defyTransfer(msg.sender, extraDefy.sub(pending));
}
if(amount_ > 0) {
if (pool.issueStub){
require(pool.stubToken.balanceOf(msg.sender) >= amount_ , "withdraw : No enough STUB tokens!");
pool.stubToken.burn(msg.sender, amount_);
}
if (pool.withdrawalFee > 0) {
uint256 withdrawalFee = amount_.mul(pool.withdrawalFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, withdrawalFee);
pool.lpToken.safeTransfer(address(msg.sender), amount_.sub(withdrawalFee));
} else {
pool.lpToken.safeTransfer(address(msg.sender), amount_);
}
user.amount = user.amount.sub(amount_);
pool.lpSupply = pool.lpSupply.sub(amount_);
}
user.depVal = ilp.getDepositValue(user.amount, _pid);
user.depositTime = block.timestamp;
user.rewardDebt = user.amount.mul(pool.accDefyPerShare).div(1e12);
user.rewardDebtDR = user.amount.mul(pool.accSecondRPerShare).div(1e24);
emit Withdraw(msg.sender, _pid, amount_);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
pool.lpSupply = pool.lpSupply.sub(user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
user.rewardDebtDR = 0;
}
// Safe defy transfer function, just in case if rounding error causes pool to not have enough DFYs.
function safeDefyTransfer(address _to, uint256 _amount) internal {
uint256 defyBal = defy.balanceOf(address(this));
bool successfulTansfer = false;
if (_amount > defyBal) {
successfulTansfer = defy.transfer(_to, defyBal);
} else {
successfulTansfer = defy.transfer(_to, _amount);
}
require(successfulTansfer, "safeDefyTransfer: transfer failed");
}
// Safe SecondR transfer function, just in case if rounding error causes pool to not have enough Secondary reward tokens.
function safeSecondRTransfer(address _to, uint256 _amount) internal {
uint256 secondRBal = secondR.balanceOf(address(this));
bool successfulTansfer = false;
if (_amount > secondRBal) {
successfulTansfer = secondR.transfer(_to, secondRBal);
} else {
successfulTansfer = secondR.transfer(_to, _amount);
}
require(successfulTansfer, "safeSecondRTransfer: transfer failed");
}
// only in an Emergency by emDev
function transferOwnerDfy(address _newOwner) external {
require (msg.sender == emDev , "only emergency dev");
defy.transferOwnership(_newOwner);
emit DFYOwnershipTransfer(_newOwner);
}
function renounceEmDev() external {
require (msg.sender == emDev , "only emergency dev");
emDev = address(0);
emit RenounceEmDev();
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(_devaddr != address(0), 'DEFY: dev cannot be the zero address');
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | Deposit LP tokens to DefyMaster for DFY allocation.If the LP token balance is lower than _amount,total LP tokens in the wallet will be deposited | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePoolPb(_pid);
uint256 amount_ = _amount;
if(amount_ > pool.lpToken.balanceOf(msg.sender)){
amount_ = pool.lpToken.balanceOf(msg.sender);
}
if(pool.impermanentLossProtection && user.amount > 0 && _getDaysSinceDeposit(_pid, msg.sender) >= 30){
extraDefy = _checkForIL(_pid, user);
}
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accDefyPerShare).div(1e12).sub(user.rewardDebt);
uint256 pendingDR = user.amount.mul(pool.accSecondRPerShare).div(1e24).sub(user.rewardDebtDR);
if(pending > 0) {
safeDefyTransfer(msg.sender, pending);
}
if(pendingDR > 0) {
safeSecondRTransfer(msg.sender, pendingDR);
}
if(extraDefy > 0 && extraDefy > pending){
ilp.defyTransfer(msg.sender, extraDefy.sub(pending));
}
}
if (amount_ > 0) {
uint256 before = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amount_);
uint256 _after = pool.lpToken.balanceOf(address(this));
if (pool.depositFee > 0) {
uint256 depositFee = amount_.mul(pool.depositFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
if (pool.issueStub){
pool.stubToken.mint(msg.sender, amount_.sub(depositFee));
}
user.amount = user.amount.add(amount_).sub(depositFee);
pool.lpSupply = pool.lpSupply.add(amount_).sub(depositFee);
user.amount = user.amount.add(amount_);
pool.lpSupply = pool.lpSupply.add(amount_);
if (pool.issueStub){
pool.stubToken.mint(msg.sender, amount_);
}
}
}
user.depVal = ilp.getDepositValue(user.amount, _pid);
user.depositTime = block.timestamp;
user.rewardDebt = user.amount.mul(pool.accDefyPerShare).div(1e12);
user.rewardDebtDR = user.amount.mul(pool.accSecondRPerShare).div(1e24);
emit Deposit(msg.sender, _pid, amount_);
}
| 7,244,273 |
./full_match/1/0x42AF47d643cb45D9a482AeD39c0973208f0CFAFF/sources/contracts/protocol/lib/Position.sol | Get the total tracked balance - total supply position unit _jasperVault Address of the JasperVault _component Address of the component return Notional tracked balance/ | function getDefaultTrackedBalance(
IJasperVault _jasperVault,
address _component
) internal view returns (uint256) {
int256 positionUnit = _jasperVault.getDefaultPositionRealUnit(
_component
);
return _jasperVault.totalSupply().preciseMul(positionUnit.toUint256());
}
| 4,962,942 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airline {
bytes32 name;
bool isRegistered;
bool hasPaidFee;
}
struct Flight {
bool isRegistered;
bytes32 flight;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
struct Insurance {
address passenger;
uint256 value;
bool isPaid;
bool isRegistered;
}
// Airline Variables:
address[] registeredAirlines;
mapping (address => Airline) airlines;
mapping (address => uint256) airlineBalances;
// Flight Variables:
mapping(bytes32 => Flight) private flights;
bytes32[] private flightKeys;
// Insurance Variables:
mapping(bytes32 => bytes32[]) passengerKeys; // Flight to passenger address
mapping(address => bytes32[]) insuranceKeys; // Passenger address to insurance key
mapping(bytes32 => Insurance) insurances;
mapping(address => uint256) insuranceBalances;
// Authorized Contracts:
mapping (address => bool) authorizedContracts;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(bytes32 name)
public
{
contractOwner = msg.sender;
// Create the first airline:
airlines[msg.sender] = Airline(name, true, false);
// Add to airline count:
registeredAirlines.push(msg.sender);
}
/********************************************************************************************/
/* 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");
_;
}
modifier requireContractAuthorized()
{
require(authorizedContracts[msg.sender], "Contract is unautorized");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
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;
}
function authorizeContract(address _address)
external
requireIsOperational
requireContractOwner
{
authorizedContracts[_address] = true;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address _address, bytes32 name)
external
requireIsOperational
requireContractAuthorized
{
// Register a new airline with provided information:
airlines[_address] = Airline(name, true, false);
registeredAirlines.push(_address);
}
/**
* @dev Get the number of airlines verified
*
*/
function getAirlineCount()
external
view
returns(uint)
{
return registeredAirlines.length;
}
function getRegisteredAirlines()
external
view
returns(address[] memory)
{
return registeredAirlines;
}
/**
* @dev Get the airline at the provided address
*
*/
function getAirline(address _address)
external
view
returns(bytes32, bool, bool)
{
Airline memory airline = airlines[_address];
return (airline.name, airline.isRegistered, airline.hasPaidFee);
}
/**
* @dev Pay the required airline fee
*
*/
function payAirlineFee(address _address, uint256 value)
external
requireIsOperational
requireContractAuthorized
{
airlineBalances[_address] = airlineBalances[_address].add(value);
airlines[_address].hasPaidFee = true;
}
function registerFlight(address airline, bytes32 flight, uint256 timestamp, uint8 status)
external
requireIsOperational
requireContractAuthorized
{
// Generate a flight key with provided information:
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey] = Flight(true, flight, status, timestamp, airline);
// Save the flight key:
flightKeys.push(flightKey);
}
function getFlight(bytes32 flight)
external
view
returns(bool, address, bytes32, uint256, uint8)
{
return _getFlight(flight);
}
function _getFlight(bytes32 _flight)
internal
view
returns(bool, address, bytes32, uint256, uint8)
{
// Pass in empty string to flights to get empty flight:
Flight memory flight = flights[bytes32(0)];
for(uint256 i = 0; i < flightKeys.length; i++) {
// Check if the passed in flight matches the flight at the flight key:
if (flights[flightKeys[i]].flight == _flight) {
flight = flights[flightKeys[i]];
break;
}
}
return (flight.isRegistered, flight.airline, flight.flight, flight.updatedTimestamp, flight.statusCode);
}
function getAllFlights()
external
view
returns(bytes32[] memory)
{
// Create an array for flight names:
bytes32[] memory flightNames = new bytes32[](flightKeys.length);
// Iterate through all flights and add the flight name:
for (uint256 i = 0; i < flightKeys.length; i++) {
flightNames[i] = (flights[flightKeys[i]].flight);
}
return flightNames;
}
function updateFlightStatus(bytes32 flightKey, uint8 statusCode)
external
requireIsOperational
requireContractAuthorized
{
flights[flightKey].statusCode = statusCode;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(address _address, uint256 value, bytes32 _flight)
external
requireIsOperational
requireContractAuthorized
{
bytes32 insuranceKey = getInsuranceKey(_address, _flight);
if(insurances[insuranceKey].isRegistered) {
insurances[insuranceKey].value = insurances[insuranceKey].value.add(value);
} else {
// Create a new insurance:
insurances[insuranceKey] = Insurance(_address, value, false, true);
passengerKeys[_flight].push(insuranceKey);
insuranceKeys[_address].push(insuranceKey);
}
// Update airlines balance:
address airline;
( , airline, , , ) = _getFlight(_flight);
airlineBalances[airline] = airlineBalances[airline].add(value);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(bytes32 flight, uint256 payoutFactor)
external
requireIsOperational
requireContractAuthorized
{
address airline;
( , airline, , , ) = _getFlight(flight);
for(uint256 i = 0; i < passengerKeys[flight].length; i++) {
bytes32 insuranceKey = passengerKeys[flight][i];
Insurance memory insurance = insurances[insuranceKey];
if (insurance.isPaid == false) {
uint256 value = insurance.value.mul(payoutFactor).div(100);
address passenger = insurance.passenger;
insurances[insuranceKey].isPaid = true;
insuranceBalances[passenger] = insuranceBalances[passenger].add(value);
airlineBalances[airline] = airlineBalances[airline].sub(value);
}
}
}
function getInsurance(address _address, bytes32 flight)
external
view
returns(address, uint256, bool, bool)
{
bytes32 insuranceKey = getInsuranceKey(_address, flight);
Insurance memory insurance = insurances[insuranceKey];
return(insurance.passenger, insurance.value, insurance.isPaid, insurance.isRegistered);
}
function getInsuranceBalance(address _address)
external
view
returns(uint256)
{
return insuranceBalances[_address];
}
function getAirlineBalance(address _address)
external
view
returns(uint256)
{
return airlineBalances[_address];
}
function pay(address _address, uint256 value)
external
requireIsOperational
requireContractAuthorized
{
insuranceBalances[_address] = insuranceBalances[_address].sub(value);
}
function getFlightKey(address airline, bytes32 flight, uint256 timestamp)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getInsuranceKey(address passenger, bytes32 flight)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(passenger, flight));
}
}
| Buy insurance for a flight/ Create a new insurance: | function buy(address _address, uint256 value, bytes32 _flight)
external
requireIsOperational
requireContractAuthorized
{
bytes32 insuranceKey = getInsuranceKey(_address, _flight);
if(insurances[insuranceKey].isRegistered) {
insurances[insuranceKey].value = insurances[insuranceKey].value.add(value);
insurances[insuranceKey] = Insurance(_address, value, false, true);
passengerKeys[_flight].push(insuranceKey);
insuranceKeys[_address].push(insuranceKey);
}
( , airline, , , ) = _getFlight(_flight);
airlineBalances[airline] = airlineBalances[airline].add(value);
}
| 14,027,149 |
pragma solidity >=0.5.0 <0.6.0;
import './CSFeatureRegistry.sol';
import './CSFeature.sol';
/**
* Required contract since CSFeatureRegistry has no add feature function
*/
contract TestRegistry is CSFeatureRegistry {
/// @notice constuctor
constructor (string memory _name, uint _h3Resolution, string memory _srs) public
CSFeatureRegistry(_name,_h3Resolution,_srs) {
name = "Test Registry";
}
/**
* Required function to add features
*/
function claimFeature (bytes15 dggsIndex,
bytes32 wkbHash)
public addFeature( dggsIndex, wkbHash, msg.sender)
returns (bytes32) {
CSFeature feature = new CSFeature(dggsIndex,wkbHash, msg.sender, h3Resolution);
bytes32 csc = feature.getFeatureCSC();
features[csc] = address(feature);
return csc;
}
}
| Required function to add features/ | function claimFeature (bytes15 dggsIndex,
bytes32 wkbHash)
public addFeature( dggsIndex, wkbHash, msg.sender)
returns (bytes32) {
CSFeature feature = new CSFeature(dggsIndex,wkbHash, msg.sender, h3Resolution);
bytes32 csc = feature.getFeatureCSC();
features[csc] = address(feature);
return csc;
}
| 12,622,381 |
./full_match/1/0x92344754a9060a52A634B3c6b8118f76baD1A448/sources/contracts/staking/LeverageStake.sol | Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned amount The underlying amount to be withdrawn | function withdraw(uint256 amount) internal {
_checkTx();
etf.invokeWithdraw(lendingPool, address(stETH), amount);
}
| 2,998,060 |
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.13;
/// @title The Nouns DAO logic version 1
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
// LICENSE
// NounsDAOLogicV1.sol is a modified version of Compound Lab's GovernorBravoDelegate.sol:
// https://github.com/compound-finance/compound-protocol/blob/b9b14038612d846b83f8a009a82c38974ff2dcfe/contracts/Governance/GovernorBravoDelegate.sol
//
// GovernorBravoDelegate.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license.
// With modifications by Nounders DAO.
//
// Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause
//
// MODIFICATIONS
// NounsDAOLogicV1 adds:
// - Proposal Threshold basis points instead of fixed number
// due to the Noun token's increasing supply
//
// - Quorum Votes basis points instead of fixed number
// due to the Noun token's increasing supply
//
// - Per proposal storing of fixed `proposalThreshold`
// and `quorumVotes` calculated using the Noun token's total supply
// at the block the proposal was created and the basis point parameters
//
// - `ProposalCreatedWithRequirements` event that emits `ProposalCreated` parameters with
// the addition of `proposalThreshold` and `quorumVotes`
//
// - Votes are counted from the block a proposal is created instead of
// the proposal's voting start block to align with the parameters
// stored with the proposal
//
// - Veto ability which allows `veteor` to halt any proposal at any stage unless
// the proposal is executed.
// The `veto(uint proposalId)` logic is a modified version of `cancel(uint proposalId)`
// A `vetoed` flag was added to the `Proposal` struct to support this.
//
// NounsDAOLogicV1 removes:
// - `initialProposalId` and `_initiate()` due to this being the
// first instance of the governance contract unlike
// GovernorBravo which upgrades GovernorAlpha
//
// - Value passed along using `timelock.executeTransaction{value: proposal.value}`
// in `execute(uint proposalId)`. This contract should not hold funds and does not
// implement `receive()` or `fallback()` functions.
//
import "./NounsDAOInterfaces.sol";
contract NounsDAOLogicV1 is NounsDAOStorageV1, NounsDAOEvents {
/// @notice The name of this contract
string public constant name = "Nouns DAO";
/// @notice The minimum setable proposal threshold
uint256 public constant MIN_PROPOSAL_THRESHOLD_BPS = 1; // 1 basis point or 0.01%
/// @notice The maximum setable proposal threshold
uint256 public constant MAX_PROPOSAL_THRESHOLD_BPS = 1_000; // 1,000 basis points or 10%
/// @notice The minimum setable voting period
uint256 public constant MIN_VOTING_PERIOD = 5_760; // About 24 hours
/// @notice The max setable voting period
uint256 public constant MAX_VOTING_PERIOD = 80_640; // About 2 weeks
/// @notice The min setable voting delay
uint256 public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint256 public constant MAX_VOTING_DELAY = 40_320; // About 1 week
/// @notice The minimum setable quorum votes basis points
uint256 public constant MIN_QUORUM_VOTES_BPS = 200; // 200 basis points or 2%
/// @notice The maximum setable quorum votes basis points
uint256 public constant MAX_QUORUM_VOTES_BPS = 2_000; // 2,000 basis points or 20%
/// @notice The maximum number of actions that can be included in a proposal
uint256 public constant proposalMaxOperations = 10; // 10 actions
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH =
keccak256("Ballot(uint256 proposalId,uint8 support)");
/**
* @notice Used to initialize the contract during delegator contructor
* @param timelock_ The address of the NounsDAOExecutor
* @param nouns_ The address of the NOUN tokens
* @param vetoer_ The address allowed to unilaterally veto proposals
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThresholdBPS_ The initial proposal threshold in basis points
* * @param quorumVotesBPS_ The initial quorum votes threshold in basis points
*/
function initialize(
address timelock_,
address nouns_,
address vetoer_,
uint256 votingPeriod_,
uint256 votingDelay_,
uint256 proposalThresholdBPS_,
uint256 quorumVotesBPS_
) public virtual {
require(
address(timelock) == address(0),
"NounsDAO::initialize: can only initialize once"
);
require(msg.sender == admin, "NounsDAO::initialize: admin only");
require(
timelock_ != address(0),
"NounsDAO::initialize: invalid timelock address"
);
require(
nouns_ != address(0),
"NounsDAO::initialize: invalid nouns address"
);
require(
votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD,
"NounsDAO::initialize: invalid voting period"
);
require(
votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY,
"NounsDAO::initialize: invalid voting delay"
);
require(
proposalThresholdBPS_ >= MIN_PROPOSAL_THRESHOLD_BPS &&
proposalThresholdBPS_ <= MAX_PROPOSAL_THRESHOLD_BPS,
"NounsDAO::initialize: invalid proposal threshold"
);
require(
quorumVotesBPS_ >= MIN_QUORUM_VOTES_BPS &&
quorumVotesBPS_ <= MAX_QUORUM_VOTES_BPS,
"NounsDAO::initialize: invalid proposal threshold"
);
emit VotingPeriodSet(votingPeriod, votingPeriod_);
emit VotingDelaySet(votingDelay, votingDelay_);
emit ProposalThresholdBPSSet(proposalThresholdBPS, proposalThresholdBPS_);
emit QuorumVotesBPSSet(quorumVotesBPS, quorumVotesBPS_);
timelock = INounsDAOExecutor(timelock_);
nouns = NounsTokenLike(nouns_);
vetoer = vetoer_;
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThresholdBPS = proposalThresholdBPS_;
quorumVotesBPS = quorumVotesBPS_;
}
struct ProposalTemp {
uint256 totalSupply;
uint256 proposalThreshold;
uint256 latestProposalId;
uint256 startBlock;
uint256 endBlock;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public returns (uint256) {
ProposalTemp memory temp;
temp.totalSupply = nouns.totalSupply();
temp.proposalThreshold = bps2Uint(proposalThresholdBPS, temp.totalSupply);
require(
nouns.getPriorVotes(msg.sender, block.number - 1) >
temp.proposalThreshold,
"NounsDAO::propose: proposer votes below proposal threshold"
);
require(
targets.length == values.length &&
targets.length == signatures.length &&
targets.length == calldatas.length,
"NounsDAO::propose: proposal function information arity mismatch"
);
require(targets.length != 0, "NounsDAO::propose: must provide actions");
require(
targets.length <= proposalMaxOperations,
"NounsDAO::propose: too many actions"
);
temp.latestProposalId = latestProposalIds[msg.sender];
if (temp.latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(temp.latestProposalId);
require(
proposersLatestProposalState != ProposalState.Active,
"NounsDAO::propose: one live proposal per proposer, found an already active proposal"
);
require(
proposersLatestProposalState != ProposalState.Pending,
"NounsDAO::propose: one live proposal per proposer, found an already pending proposal"
);
}
temp.startBlock = block.number + votingDelay;
temp.endBlock = temp.startBlock + votingPeriod;
proposalCount++;
Proposal storage newProposal = proposals[proposalCount];
newProposal.id = proposalCount;
newProposal.proposer = msg.sender;
newProposal.proposalThreshold = temp.proposalThreshold;
newProposal.quorumVotes = bps2Uint(quorumVotesBPS, temp.totalSupply);
newProposal.eta = 0;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startBlock = temp.startBlock;
newProposal.endBlock = temp.endBlock;
newProposal.forVotes = 0;
newProposal.againstVotes = 0;
newProposal.abstainVotes = 0;
newProposal.canceled = false;
newProposal.executed = false;
newProposal.vetoed = false;
latestProposalIds[newProposal.proposer] = newProposal.id;
/// @notice Maintains backwards compatibility with GovernorBravo events
emit ProposalCreated(
newProposal.id,
msg.sender,
targets,
values,
signatures,
calldatas,
newProposal.startBlock,
newProposal.endBlock,
description
);
/// @notice Updated event with `proposalThreshold` and `quorumVotes`
emit ProposalCreatedWithRequirements(
newProposal.id,
msg.sender,
targets,
values,
signatures,
calldatas,
newProposal.startBlock,
newProposal.endBlock,
newProposal.proposalThreshold,
newProposal.quorumVotes,
description
);
return newProposal.id;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
function queue(uint256 proposalId) external {
require(
state(proposalId) == ProposalState.Succeeded,
"NounsDAO::queue: proposal can only be queued if it is succeeded"
);
Proposal storage proposal = proposals[proposalId];
uint256 eta = block.timestamp + timelock.delay();
for (uint256 i = 0; i < proposal.targets.length; i++) {
queueOrRevertInternal(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
eta
);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) internal {
require(
!timelock.queuedTransactions(
keccak256(abi.encode(target, value, signature, data, eta))
),
"NounsDAO::queueOrRevertInternal: identical proposal action already queued at eta"
);
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
function execute(uint256 proposalId) external {
require(
state(proposalId) == ProposalState.Queued,
"NounsDAO::execute: proposal can only be executed if it is queued"
);
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold
* @param proposalId The id of the proposal to cancel
*/
function cancel(uint256 proposalId) external {
require(
state(proposalId) != ProposalState.Executed,
"NounsDAO::cancel: cannot cancel executed proposal"
);
Proposal storage proposal = proposals[proposalId];
require(
msg.sender == proposal.proposer ||
nouns.getPriorVotes(proposal.proposer, block.number - 1) <
proposal.proposalThreshold,
"NounsDAO::cancel: proposer above threshold"
);
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice Vetoes a proposal only if sender is the vetoer and the proposal has not been executed.
* @param proposalId The id of the proposal to veto
*/
function veto(uint256 proposalId) external {
require(vetoer != address(0), "NounsDAO::veto: veto power burned");
require(msg.sender == vetoer, "NounsDAO::veto: only vetoer");
require(
state(proposalId) != ProposalState.Executed,
"NounsDAO::veto: cannot veto executed proposal"
);
Proposal storage proposal = proposals[proposalId];
proposal.vetoed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalVetoed(proposalId);
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return targets
* @return values
* @return signatures
* @return calldatas
*/
function getActions(uint256 proposalId)
external
view
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
function getReceipt(uint256 proposalId, address voter)
external
view
returns (Receipt memory)
{
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
function state(uint256 proposalId) public view returns (ProposalState) {
require(
proposalCount >= proposalId,
"NounsDAO::state: invalid proposal id"
);
Proposal storage proposal = proposals[proposalId];
if (proposal.vetoed) {
return ProposalState.Vetoed;
} else if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (
proposal.forVotes <= proposal.againstVotes ||
proposal.forVotes < proposal.quorumVotes
) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta + timelock.GRACE_PERIOD()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
function castVote(uint256 proposalId, uint8 support) external {
emit VoteCast(
msg.sender,
proposalId,
support,
castVoteInternal(msg.sender, proposalId, support),
""
);
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) external {
emit VoteCast(
msg.sender,
proposalId,
support,
castVoteInternal(msg.sender, proposalId, support),
reason
);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainIdInternal(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(BALLOT_TYPEHASH, proposalId, support)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
"NounsDAO::castVoteBySig: invalid signature"
);
emit VoteCast(
signatory,
proposalId,
support,
castVoteInternal(signatory, proposalId, support),
""
);
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
function castVoteInternal(
address voter,
uint256 proposalId,
uint8 support
) internal returns (uint96) {
require(
state(proposalId) == ProposalState.Active,
"NounsDAO::castVoteInternal: voting is closed"
);
require(support <= 2, "NounsDAO::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(
receipt.hasVoted == false,
"NounsDAO::castVoteInternal: voter already voted"
);
/// @notice: Unlike GovernerBravo, votes are considered from the block the proposal was created in order to normalize quorumVotes and proposalThreshold metrics
uint96 votes = nouns.getPriorVotes(
voter,
proposal.startBlock - votingDelay
);
if (support == 0) {
proposal.againstVotes = proposal.againstVotes + votes;
} else if (support == 1) {
proposal.forVotes = proposal.forVotes + votes;
} else if (support == 2) {
proposal.abstainVotes = proposal.abstainVotes + votes;
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
function _setVotingDelay(uint256 newVotingDelay) external {
require(msg.sender == admin, "NounsDAO::_setVotingDelay: admin only");
require(
newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY,
"NounsDAO::_setVotingDelay: invalid voting delay"
);
uint256 oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay, votingDelay);
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
function _setVotingPeriod(uint256 newVotingPeriod) external {
require(msg.sender == admin, "NounsDAO::_setVotingPeriod: admin only");
require(
newVotingPeriod >= MIN_VOTING_PERIOD &&
newVotingPeriod <= MAX_VOTING_PERIOD,
"NounsDAO::_setVotingPeriod: invalid voting period"
);
uint256 oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold basis points
* @dev newProposalThresholdBPS must be greater than the hardcoded min
* @param newProposalThresholdBPS new proposal threshold
*/
function _setProposalThresholdBPS(uint256 newProposalThresholdBPS) external {
require(
msg.sender == admin,
"NounsDAO::_setProposalThresholdBPS: admin only"
);
require(
newProposalThresholdBPS >= MIN_PROPOSAL_THRESHOLD_BPS &&
newProposalThresholdBPS <= MAX_PROPOSAL_THRESHOLD_BPS,
"NounsDAO::_setProposalThreshold: invalid proposal threshold"
);
uint256 oldProposalThresholdBPS = proposalThresholdBPS;
proposalThresholdBPS = newProposalThresholdBPS;
emit ProposalThresholdBPSSet(oldProposalThresholdBPS, proposalThresholdBPS);
}
/**
* @notice Admin function for setting the quorum votes basis points
* @dev newQuorumVotesBPS must be greater than the hardcoded min
* @param newQuorumVotesBPS new proposal threshold
*/
function _setQuorumVotesBPS(uint256 newQuorumVotesBPS) external {
require(msg.sender == admin, "NounsDAO::_setQuorumVotesBPS: admin only");
require(
newQuorumVotesBPS >= MIN_QUORUM_VOTES_BPS &&
newQuorumVotesBPS <= MAX_QUORUM_VOTES_BPS,
"NounsDAO::_setProposalThreshold: invalid proposal threshold"
);
uint256 oldQuorumVotesBPS = quorumVotesBPS;
quorumVotesBPS = newQuorumVotesBPS;
emit QuorumVotesBPSSet(oldQuorumVotesBPS, quorumVotesBPS);
}
/**
* @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.
*/
function _setPendingAdmin(address newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "NounsDAO::_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(
msg.sender == pendingAdmin && msg.sender != address(0),
"NounsDAO::_acceptAdmin: pending admin only"
);
// 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);
}
/**
* @notice Changes vetoer address
* @dev Vetoer function for updating vetoer address
*/
function _setVetoer(address newVetoer) public {
require(msg.sender == vetoer, "NounsDAO::_setVetoer: vetoer only");
emit NewVetoer(vetoer, newVetoer);
vetoer = newVetoer;
}
/**
* @notice Burns veto priviledges
* @dev Vetoer function destroying veto power forever
*/
function _burnVetoPower() public {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == vetoer, "NounsDAO::_burnVetoPower: vetoer only");
_setVetoer(address(0));
}
/**
* @notice Current proposal threshold using Noun Total Supply
* Differs from `GovernerBravo` which uses fixed amount
*/
function proposalThreshold() public view returns (uint256) {
return bps2Uint(proposalThresholdBPS, nouns.totalSupply());
}
/**
* @notice Current quorum votes using Noun Total Supply
* Differs from `GovernerBravo` which uses fixed amount
*/
function quorumVotes() public view returns (uint256) {
return bps2Uint(quorumVotesBPS, nouns.totalSupply());
}
function bps2Uint(uint256 bps, uint256 number)
internal
pure
returns (uint256)
{
return (number * bps) / 10000;
}
function getChainIdInternal() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
| Internal function that caries out voting logic voter The voter that is casting their vote proposalId The id of the proposal to vote on support The support value for the vote. 0=against, 1=for, 2=abstain return The number of votes cast/ : Unlike GovernerBravo, votes are considered from the block the proposal was created in order to normalize quorumVotes and proposalThreshold metrics | function castVoteInternal(
address voter,
uint256 proposalId,
uint8 support
) internal returns (uint96) {
require(
state(proposalId) == ProposalState.Active,
"NounsDAO::castVoteInternal: voting is closed"
);
require(support <= 2, "NounsDAO::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(
receipt.hasVoted == false,
"NounsDAO::castVoteInternal: voter already voted"
);
uint96 votes = nouns.getPriorVotes(
voter,
proposal.startBlock - votingDelay
);
if (support == 0) {
proposal.againstVotes = proposal.againstVotes + votes;
proposal.forVotes = proposal.forVotes + votes;
proposal.abstainVotes = proposal.abstainVotes + votes;
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
| 12,735,786 |
// SPDX-License-Identifier: MIT
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
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/[email protected]
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/utils/[email protected]
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/token/ERC20/[email protected]
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/access/[email protected]
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 contracts/assets/ISoNetAsset.sol
pragma solidity =0.8.4;
interface ISoNetAsset is IERC20 {
function isSoNetAsset() external returns (bool);
function burn(uint256 amount) external returns (bool);
function burnFrom(address from, uint256 amount) external returns (bool);
}
// File contracts/assets/SOC.sol
pragma solidity =0.8.4;
contract SOC is ERC20, Ownable, ISoNetAsset {
bool public constant override isSoNetAsset = true;
address public treasury;
uint public globalBurnRate;
uint public globalTaxRate;
address public taxTo;
modifier onlyTreasury(){
require(msg.sender == treasury, 'only treasury');
_;
}
event NewTreasury(address newTreasury);
event NewGlobalBurnRate(uint newRate);
event NewGlobalTaxRate(uint newRate);
event NewTaxTo(address taxTo);
constructor(address recipient) ERC20("Social Network Cash", "SOC") Ownable() {
_mint(recipient, 10 ** decimals());
// 2%
globalBurnRate = 2e16;
}
function setTreasury(address _treasury) public onlyOwner {
treasury = _treasury;
emit NewTreasury(_treasury);
}
function setGlobalBurnRate(uint newRate) public onlyOwner {
require(newRate < 1e18);
globalBurnRate = newRate;
emit NewGlobalBurnRate(newRate);
}
function setGlobalTaxRate(uint newRate) public onlyOwner {
require(newRate < 1e18);
globalTaxRate = newRate;
emit NewGlobalTaxRate(newRate);
}
/// @notice we don't check `newTaxTo` is address(0)
function setTaxTo(address newTaxTo) public onlyOwner {
taxTo = newTaxTo;
emit NewTaxTo(newTaxTo);
}
function mint(address recipient_, uint256 amount_) public onlyTreasury returns (bool) {
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter > balanceBefore;
}
function spend(address sender, address recipient, uint amount, uint burnRate) public returns (bool){
if (amount == 0) {
return true;
}
if (burnRate == 0) {
burnRate = globalBurnRate;
} else {
require(burnRate >= globalBurnRate, 'lower burnRate');
}
uint burnAmount = amount * burnRate / 1e18;
burnFrom(sender, burnAmount);
amount -= burnAmount;
if (amount == 0) {
return true;
}
if (taxTo != recipient && globalTaxRate > 0) {
uint tax = amount * globalTaxRate / 1e18;
if (tax > 0) {
/// @notice SOC.transfer only returns true or revert, so we don't need to check return value
transferFrom(sender, taxTo, tax);
amount -= tax;
}
}
transferFrom(sender, recipient, amount);
return true;
}
function burn(uint256 amount) public override returns (bool) {
_burn(_msgSender(), amount);
return true;
}
function burnFrom(address account, uint256 amount) public override returns (bool){
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
return true;
}
} | we don't check `newTaxTo` is address(0) | function setTaxTo(address newTaxTo) public onlyOwner {
taxTo = newTaxTo;
emit NewTaxTo(newTaxTo);
}
| 1,646,166 |
/**
*Submitted for verification at Etherscan.io on 2021-03-14
*/
// 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);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev 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) {
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;
}
}
/**
* @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 {
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 default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three 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 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 this function is
* overloaded;
*
* 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 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 { }
}
interface IERC20Bulk {
function transferBulk(address[] calldata to, uint[] calldata tokens) external;
function approveBulk(address[] calldata spender, uint[] calldata tokens) external;
}
interface IERC223 {
function transfer(address _to, uint _value, bytes calldata _data) external returns (bool success);
}
interface IERC827 {
function approveAndCall(address _spender, uint256 _value, bytes memory _data) external returns (bool);
}
// https://github.com/ethereum/EIPs/issues/223
interface TokenFallback {
function tokenFallback(address _from, uint _value, bytes calldata _data) external;
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
interface TokenRecipientInterface {
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external;
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
/**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/
contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
}
interface IFungibleToken is IERC20, IERC827, IERC223, IERC20Bulk {
}
/**
* @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 ERC20Burnable is Context, ERC20 {
/**
* @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 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "BCUG: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
}
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
uint256 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-_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() + amount <= cap(), "ERC20Capped: cap exceeded");
}
}
}
/**
* @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 Pausable is Context {
/**
* @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.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual 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());
}
}
/**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/
abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
}
/**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* 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 BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | Get operation hash for multisig operation Nonce used to ensure that signature used only once. Use unique typehash for each operation./ | function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
| 7,986,800 |
./full_match/1/0x07b0bE8512417a8599a37DC74862Ccb79d2f1400/sources/contracts/TokenStaker.sol | Storage of set values Position of the value in the `values` array, plus 1 because index 0 means a value is not in the set. | function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
| 8,456,734 |
// File: contracts/Owned.sol
pragma solidity 0.6.7;
contract Owned {
address public owner = msg.sender;
event LogOwnershipTransferred(address indexed owner, address indexed newOwner);
modifier onlyOwner {
require(msg.sender == owner, "Sender must be owner");
_;
}
function setOwner(address _owner)
external
onlyOwner
{
require(_owner != address(0), "Owner cannot be zero address");
emit LogOwnershipTransferred(owner, _owner);
owner = _owner;
}
}
// File: contracts/thirdParty/ECDSA.sol
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
// Line 60 added to original source in accordance with recommendation on accepting signatures with 0/1 for v
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v < 27) v += 27;
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: contracts/interfaces/IERC777.sol
pragma solidity 0.6.7;
// As defined in https://eips.ethereum.org/EIPS/eip-777
interface IERC777 {
event Sent(address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data,
bytes operatorData);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator,address indexed holder);
event RevokedOperator(address indexed operator, address indexed holder);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address holder) external view returns (uint256);
function granularity() external view returns (uint256);
function defaultOperators() external view returns (address[] memory);
function isOperatorFor(address operator, address holder) external view returns (bool);
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function send(address to, uint256 amount, bytes calldata data) external;
function operatorSend(address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData) external;
function burn(uint256 amount, bytes calldata data) external;
function operatorBurn( address from, uint256 amount, bytes calldata data, bytes calldata operatorData) external;
}
// File: contracts/interfaces/IERC20.sol
pragma solidity 0.6.7;
// As described in https://eips.ethereum.org/EIPS/eip-20
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function name() external view returns (string memory); // optional method - see eip spec
function symbol() external view returns (string memory); // optional method - see eip spec
function decimals() external view returns (uint8); // optional method - see eip spec
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
}
// File: contracts/thirdParty/interfaces/IERC1820Registry.sol
// From open https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/introspection/IERC1820Registry.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// File: contracts/interfaces/IERC777Sender.sol
pragma solidity 0.6.7;
// As defined in the 'ERC777TokensSender And The tokensToSend Hook' section of https://eips.ethereum.org/EIPS/eip-777
interface IERC777Sender {
function tokensToSend(address operator, address from, address to, uint256 amount, bytes calldata data,
bytes calldata operatorData) external;
}
// File: contracts/interfaces/IERC777Recipient.sol
pragma solidity 0.6.7;
// As defined in the 'ERC777TokensRecipient And The tokensReceived Hook' section of https://eips.ethereum.org/EIPS/eip-777
interface IERC777Recipient {
function tokensReceived(address operator, address from, address to, uint256 amount, bytes calldata data,
bytes calldata operatorData) external;
}
// File: contracts/thirdParty/SafeMath.sol
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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.
*
* _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;
}
}
// File: contracts/libraries/LToken.sol
pragma solidity 0.6.7;
struct TokenState {
uint256 totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) approvals;
mapping(address => mapping(address => bool)) authorizedOperators;
address[] defaultOperators;
mapping(address => bool) defaultOperatorIsRevoked;
mapping(address => bool) minters;
}
library LToken {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Sent(address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data,
bytes operatorData);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed holder);
event RevokedOperator(address indexed operator, address indexed holder);
// Universal address as defined in Registry Contract Address section of https://eips.ethereum.org/EIPS/eip-1820
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// precalculated hashes - see https://github.com/ethereum/solidity/issues/4024
// keccak256("ERC777TokensSender")
bytes32 constant internal ERC777_TOKENS_SENDER_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant internal ERC777_TOKENS_RECIPIENT_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
modifier checkSenderNotOperator(address _operator) {
require(_operator != msg.sender, "Cannot be operator for self");
_;
}
function initState(TokenState storage _tokenState, uint8 _decimals, uint256 _initialSupply)
external
{
_tokenState.defaultOperators.push(address(this));
_tokenState.totalSupply = _initialSupply.mul(10**uint256(_decimals));
_tokenState.balances[msg.sender] = _tokenState.totalSupply;
}
function transferFrom(TokenState storage _tokenState, address _from, address _to, uint256 _value)
external
{
_tokenState.approvals[_from][msg.sender] = _tokenState.approvals[_from][msg.sender].sub(_value, "Amount not approved");
doSend(_tokenState, msg.sender, _from, _to, _value, "", "", false);
}
function approve(TokenState storage _tokenState, address _spender, uint256 _value)
external
{
require(_spender != address(0), "Cannot approve to zero address");
_tokenState.approvals[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
function authorizeOperator(TokenState storage _tokenState, address _operator)
checkSenderNotOperator(_operator)
external
{
if (_operator == address(this))
_tokenState.defaultOperatorIsRevoked[msg.sender] = false;
else
_tokenState.authorizedOperators[_operator][msg.sender] = true;
emit AuthorizedOperator(_operator, msg.sender);
}
function revokeOperator(TokenState storage _tokenState, address _operator)
checkSenderNotOperator(_operator)
external
{
if (_operator == address(this))
_tokenState.defaultOperatorIsRevoked[msg.sender] = true;
else
_tokenState.authorizedOperators[_operator][msg.sender] = false;
emit RevokedOperator(_operator, msg.sender);
}
function authorizeMinter(TokenState storage _tokenState, address _minter)
external
{
_tokenState.minters[_minter] = true;
}
function revokeMinter(TokenState storage _tokenState, address _minter)
external
{
_tokenState.minters[_minter] = false;
}
function doMint(TokenState storage _tokenState, address _to, uint256 _amount)
external
{
assert(_to != address(0));
_tokenState.totalSupply = _tokenState.totalSupply.add(_amount);
_tokenState.balances[_to] = _tokenState.balances[_to].add(_amount);
// From ERC777: The token contract MUST call the tokensReceived hook after updating the state.
receiveHook(address(this), address(0), _to, _amount, "", "", true);
emit Minted(address(this), _to, _amount, "", "");
emit Transfer(address(0), _to, _amount);
}
function doBurn(TokenState storage _tokenState, address _operator, address _from, uint256 _amount, bytes calldata _data,
bytes calldata _operatorData)
external
{
assert(_from != address(0));
// From ERC777: The token contract MUST call the tokensToSend hook before updating the state.
sendHook(_operator, _from, address(0), _amount, _data, _operatorData);
_tokenState.balances[_from] = _tokenState.balances[_from].sub(_amount, "Cannot burn more than balance");
_tokenState.totalSupply = _tokenState.totalSupply.sub(_amount);
emit Burned(_operator, _from, _amount, _data, _operatorData);
emit Transfer(_from, address(0), _amount);
}
function doSend(TokenState storage _tokenState, address _operator, address _from, address _to, uint256 _amount,
bytes memory _data, bytes memory _operatorData, bool _enforceERC777)
public
{
assert(_from != address(0));
require(_to != address(0), "Cannot send funds to 0 address");
// From ERC777: The token contract MUST call the tokensToSend hook before updating the state.
sendHook(_operator, _from, _to, _amount, _data, _operatorData);
_tokenState.balances[_from] = _tokenState.balances[_from].sub(_amount, "Amount exceeds available funds");
_tokenState.balances[_to] = _tokenState.balances[_to].add(_amount);
emit Sent(_operator, _from, _to, _amount, _data, _operatorData);
emit Transfer(_from, _to, _amount);
// From ERC777: The token contract MUST call the tokensReceived hook after updating the state.
receiveHook(_operator, _from, _to, _amount, _data, _operatorData, _enforceERC777);
}
function receiveHook(address _operator, address _from, address _to, uint256 _amount, bytes memory _data,
bytes memory _operatorData, bool _enforceERC777)
public
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(_to, ERC777_TOKENS_RECIPIENT_HASH);
if (implementer != address(0))
IERC777Recipient(implementer).tokensReceived(_operator, _from, _to, _amount, _data, _operatorData);
else if (_enforceERC777)
require(!isContract(_to), "Must be registered with ERC1820");
}
function sendHook(address _operator, address _from, address _to, uint256 _amount, bytes memory _data,
bytes memory _operatorData)
public
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(_from, ERC777_TOKENS_SENDER_HASH);
if (implementer != address(0))
IERC777Sender(implementer).tokensToSend(_operator, _from, _to, _amount, _data, _operatorData);
}
function isContract(address _account)
private
view
returns (bool isContract_)
{
uint256 size;
assembly {
size := extcodesize(_account)
}
isContract_ = size != 0;
}
}
// File: contracts/Token.sol
pragma solidity 0.6.7;
/**
* Implements ERC777 with ERC20 as defined in https://eips.ethereum.org/EIPS/eip-777, with minting support.
* NOTE: Minting is internal only: derive from this contract according to usage.
*/
contract Token is IERC777, IERC20 {
string private tokenName;
string private tokenSymbol;
uint8 constant private tokenDecimals = 18;
uint256 constant private tokenGranularity = 1;
TokenState public tokenState;
// Universal address as defined in Registry Contract Address section of https://eips.ethereum.org/EIPS/eip-1820
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// keccak256("ERC777Token")
bytes32 constant internal ERC777_TOKEN_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054;
// keccak256("ERC20Token")
bytes32 constant internal ERC20_TOKEN_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a;
event AuthorizedMinter(address minter);
event RevokedMinter(address minter);
constructor(string memory _name, string memory _symbol, uint256 _initialSupply)
internal
{
require(bytes(_name).length != 0, "Needs a name");
require(bytes(_symbol).length != 0, "Needs a symbol");
tokenName = _name;
tokenSymbol = _symbol;
LToken.initState(tokenState, tokenDecimals, _initialSupply);
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC777_TOKEN_HASH, address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKEN_HASH, address(this));
}
modifier onlyOperator(address _holder) {
require(isOperatorFor(msg.sender, _holder), "Not an operator");
_;
}
modifier onlyMinter {
require(tokenState.minters[msg.sender], "onlyMinter");
_;
}
function name()
external
view
override(IERC777, IERC20)
returns (string memory name_)
{
name_ = tokenName;
}
function symbol()
external
view
override(IERC777, IERC20)
returns (string memory symbol_)
{
symbol_ = tokenSymbol;
}
function decimals()
external
view
override
returns (uint8 decimals_)
{
decimals_ = tokenDecimals;
}
function granularity()
external
view
override
returns (uint256 granularity_)
{
granularity_ = tokenGranularity;
}
function balanceOf(address _holder)
external
override(IERC777, IERC20)
view
returns (uint256 balance_)
{
balance_ = tokenState.balances[_holder];
}
function transfer(address _to, uint256 _value)
external
override
returns (bool success_)
{
doSend(msg.sender, msg.sender, _to, _value, "", "", false);
success_ = true;
}
function transferFrom(address _from, address _to, uint256 _value)
external
override
returns (bool success_)
{
LToken.transferFrom(tokenState, _from, _to, _value);
success_ = true;
}
function approve(address _spender, uint256 _value)
external
override
returns (bool success_)
{
LToken.approve(tokenState, _spender, _value);
success_ = true;
}
function allowance(address _holder, address _spender)
external
view
override
returns (uint256 remaining_)
{
remaining_ = tokenState.approvals[_holder][_spender];
}
function defaultOperators()
external
view
override
returns (address[] memory)
{
return tokenState.defaultOperators;
}
function authorizeOperator(address _operator)
external
override
{
LToken.authorizeOperator(tokenState, _operator);
}
function revokeOperator(address _operator)
external
override
{
LToken.revokeOperator(tokenState, _operator);
}
function send(address _to, uint256 _amount, bytes calldata _data)
external
override
{
doSend(msg.sender, msg.sender, _to, _amount, _data, "", true);
}
function operatorSend(address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData)
external
override
onlyOperator(_from)
{
doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true);
}
function burn(uint256 _amount, bytes calldata _data)
external
override
{
doBurn(msg.sender, msg.sender, _amount, _data, "");
}
function operatorBurn(address _from, uint256 _amount, bytes calldata _data, bytes calldata _operatorData)
external
override
onlyOperator(_from)
{
doBurn(msg.sender, _from, _amount, _data, _operatorData);
}
function mint(address _to, uint256 _amount)
external
onlyMinter
{
LToken.doMint(tokenState, _to, _amount);
}
function totalSupply()
external
view
override(IERC777, IERC20)
returns (uint256 totalSupply_)
{
totalSupply_ = tokenState.totalSupply;
}
function isOperatorFor(address _operator, address _holder)
public
view
override
returns (bool isOperatorFor_)
{
isOperatorFor_ = (_operator == _holder || tokenState.authorizedOperators[_operator][_holder]
|| _operator == address(this) && !tokenState.defaultOperatorIsRevoked[_holder]);
}
function doSend(address _operator, address _from, address _to, uint256 _amount, bytes memory _data,
bytes memory _operatorData, bool _enforceERC777)
internal
virtual
{
LToken.doSend(tokenState, _operator, _from, _to, _amount, _data, _operatorData, _enforceERC777);
}
function doBurn(address _operator, address _from, uint256 _amount, bytes memory _data, bytes memory _operatorData)
internal
{
LToken.doBurn(tokenState, _operator, _from, _amount, _data, _operatorData);
}
function authorizeMinter(address _minter)
internal
{
LToken.authorizeMinter(tokenState, _minter);
emit AuthorizedMinter(_minter);
}
function revokeMinter(address _minter)
internal
{
LToken.revokeMinter(tokenState, _minter);
emit RevokedMinter(_minter);
}
}
// File: contracts/VOWToken.sol
pragma solidity 0.6.7;
/**
* ERC777/20 contract which also:
* - is owned
* - supports proxying of own tokens (only if signed correctly)
* - supports partner contracts, keyed by hash
* - supports minting (only by owner approved contracts)
* - has a USD price
*/
contract VOWToken is Token, IERC777Recipient, Owned {
mapping (bytes32 => bool) public proxyProofs;
uint256[2] public usdRate;
address public usdRateSetter;
mapping(bytes32 => address payable) public partnerContracts;
// precalculated hash - see https://github.com/ethereum/solidity/issues/4024
// keccak256("ERC777TokensRecipient")
bytes32 constant internal ERC777_TOKENS_RECIPIENT_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
event LogUSDRateSetterSet(address indexed usdRateSetter);
event LogUSDRateSet(uint256 numTokens, uint256 numUSD);
event LogProxiedTokens(address indexed from, address indexed to, uint256 amount, bytes data, uint256 nonce, bytes proof);
event LogPartnerContractSet(bytes32 indexed keyHash, address indexed partnerContract);
event LogMintPermissionSet(address indexed contractAddress, bool canMint);
constructor(string memory _name, string memory _symbol, uint256 _initialSupply, uint256[2] memory _initialUSDRate)
public
Token(_name, _symbol, _initialSupply)
{
doSetUSDRate(_initialUSDRate[0], _initialUSDRate[1]);
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC777_TOKENS_RECIPIENT_HASH, address(this));
}
modifier onlyUSDRateSetter() {
require(msg.sender == usdRateSetter, "onlyUSDRateSetter");
_;
}
modifier onlyOwnTokens {
require(msg.sender == address(this), "onlyOwnTokens");
_;
}
modifier addressNotNull(address _address) {
require(_address != address(0), "Address cannot be null");
_;
}
function tokensReceived(address /* _operator */, address /* _from */, address /* _to */, uint256 _amount,
bytes calldata _data, bytes calldata /* _operatorData */)
external
override
onlyOwnTokens
{
(address from, address to, uint256 amount, bytes memory data, uint256 nonce, bytes memory proof) =
abi.decode(_data, (address, address, uint256, bytes, uint256, bytes));
checkProxying(from, to, amount, data, nonce, proof);
if (_amount != 0)
this.send(from, _amount, "");
this.operatorSend(from, to, amount, data, _data);
emit LogProxiedTokens(from, to, amount, data, nonce, proof);
}
function setPartnerContract(bytes32 _keyHash, address payable _partnerContract)
external
onlyOwner
addressNotNull(_partnerContract)
{
require(_keyHash != bytes32(0), "Missing key hash");
partnerContracts[_keyHash] = _partnerContract;
emit LogPartnerContractSet(_keyHash, _partnerContract);
}
function setUSDRateSetter(address _usdRateSetter)
external
onlyOwner
addressNotNull(_usdRateSetter)
{
usdRateSetter = _usdRateSetter;
emit LogUSDRateSetterSet(_usdRateSetter);
}
function setUSDRate(uint256 _numTokens, uint256 _numUSD)
external
onlyUSDRateSetter
{
doSetUSDRate(_numTokens, _numUSD);
emit LogUSDRateSet(_numTokens, _numUSD);
}
function setMintPermission(address _contract, bool _canMint)
external
onlyOwner
addressNotNull(_contract)
{
if (_canMint)
authorizeMinter(_contract);
else
revokeMinter(_contract);
emit LogMintPermissionSet(_contract, _canMint);
}
function doSetUSDRate(uint256 _numTokens, uint256 _numUSD)
private
{
require(_numTokens != 0, "numTokens cannot be zero");
require(_numUSD != 0, "numUSD cannot be zero");
usdRate = [_numTokens, _numUSD];
}
function checkProxying(address _from, address _to, uint256 _amount, bytes memory _data, uint256 _nonce, bytes memory _proof)
private
{
require(!proxyProofs[keccak256(_proof)], "Proxy proof not unique");
proxyProofs[keccak256(_proof)] = true;
bytes32 hash = keccak256(abi.encodePacked(address(this), _from, _to, _amount, _data, _nonce));
address signer = ECDSA.recover(ECDSA.toEthSignedMessageHash(hash), _proof);
require(signer == _from, "Bad signer");
}
}
// File: contracts/VSCToken.sol
pragma solidity 0.6.7;
/**
* VSCToken is a VOWToken with:
* - a linked parent Vow token
* - tier 1 burn (with owner aproved exceptions)
* - tier 2 delegated lifting (only by owner approved contracts)
*/
contract VSCToken is VOWToken {
using SafeMath for uint256;
address public immutable vowContract;
mapping(address => bool) public canLift;
mapping(address => bool) public skipTier1Burn;
uint256[2] public tier1BurnVSC;
event LogTier1BurnVSCUpdated(uint256[2] ratio);
event LogLiftPermissionSet(address indexed liftingAddress, bool canLift);
event LogSkipTier1BurnSet(address indexed skipTier1BurnAddress, bool skipTier1Burn);
constructor(string memory _name, string memory _symbol, uint256[2] memory _initialVSCUSD, address _vowContract)
VOWToken(_name, _symbol, 0, _initialVSCUSD)
public
{
vowContract = _vowContract;
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC777_TOKENS_RECIPIENT_HASH, address(this));
tier1BurnVSC = [0, 1]; // Default to no burn: ie burn 0 VSC for every 1 VSC sent on tier 1
setSkipTier1Burn(address(this), true);
}
modifier onlyLifter() {
require(canLift[msg.sender], "onlyLifter");
_;
}
function setLiftPermission(address _liftingAddress, bool _canLift)
external
onlyOwner
addressNotNull(_liftingAddress)
{
canLift[_liftingAddress] = _canLift;
emit LogLiftPermissionSet(_liftingAddress, _canLift);
}
function setTier1BurnVSC(uint256 _numVSCBurned, uint256 _numVSCSent)
external
onlyOwner
{
require(_numVSCSent != 0, "Invalid burn ratio: div by zero");
require(_numVSCSent >= _numVSCBurned, "Invalid burn ratio: above 100%");
tier1BurnVSC = [_numVSCBurned, _numVSCSent];
emit LogTier1BurnVSCUpdated(tier1BurnVSC);
}
function lift(address _liftAccount, uint256 _amount, bytes calldata _data)
external
onlyLifter
{
address tier2ScalingManager = partnerContracts[keccak256(abi.encodePacked("FTScalingManager"))];
this.operatorSend(_liftAccount, tier2ScalingManager, _amount , _data, "");
}
function setSkipTier1Burn(address _skipTier1BurnAddress, bool _skipTier1Burn)
public
onlyOwner
addressNotNull(_skipTier1BurnAddress)
{
skipTier1Burn[_skipTier1BurnAddress] = _skipTier1Burn;
emit LogSkipTier1BurnSet(_skipTier1BurnAddress, _skipTier1Burn);
}
function doSend(address _operator, address _from, address _to, uint256 _amount, bytes memory _data,
bytes memory _operatorData, bool _enforceERC777)
internal
virtual
override
{
uint256 actualSendAmount = _amount;
if (!skipTier1Burn[_from] && !skipTier1Burn[_to]) {
uint256 burnAmount = _amount.mul(tier1BurnVSC[0]).div(tier1BurnVSC[1]);
doBurn(_operator, _from, burnAmount, _data, _operatorData);
actualSendAmount = actualSendAmount.sub(burnAmount);
}
super.doSend(_operator, _from, _to, actualSendAmount, _data, _operatorData, _enforceERC777);
}
}
// File: contracts/thirdParty/provableAPI_06.sol
// Source: https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol
// <provableAPI>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016-2019 Oraclize LTD
Copyright (c) 2019-2020 Provable Things Limited
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity > 0.6.1 < 0.7.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the provableAPI!
// Dummy contract only used to emit to end-user they are using wrong solc
abstract contract solcChecker {
/* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) virtual external;
}
interface ProvableI {
function cbAddress() external returns (address _cbAddress);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function getPrice(string calldata _datasource) external returns (uint _dsprice);
function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);
function getPrice(string calldata _datasource, uint _gasLimit) external returns (uint _dsprice);
function queryN(uint _timestamp, string calldata _datasource, bytes calldata _argN) external payable returns (bytes32 _id);
function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);
function query2(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);
}
interface OracleAddrResolverI {
function getAddress() external returns (address _address);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory _buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint _a, uint _b) private pure returns (uint _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return _buffer The original buffer.
*
*/
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint dest;
uint src;
uint len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return _buffer The original buffer.
*
*/
function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {
if (_value <= 23) {
_buf.append(uint8((_major << 5) | _value));
} else if (_value <= 0xFF) {
_buf.append(uint8((_major << 5) | 24));
_buf.appendInt(_value, 1);
} else if (_value <= 0xFFFF) {
_buf.append(uint8((_major << 5) | 25));
_buf.appendInt(_value, 2);
} else if (_value <= 0xFFFFFFFF) {
_buf.append(uint8((_major << 5) | 26));
_buf.appendInt(_value, 4);
} else if (_value <= 0xFFFFFFFFFFFFFFFF) {
_buf.append(uint8((_major << 5) | 27));
_buf.appendInt(_value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {
_buf.append(uint8((_major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {
encodeType(_buf, MAJOR_TYPE_INT, _value);
}
function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {
if (_value >= 0) {
encodeType(_buf, MAJOR_TYPE_INT, uint(_value));
} else {
encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));
}
}
function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);
_buf.append(_value);
}
function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);
_buf.append(bytes(_value));
}
function startArray(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingProvable {
using CBOR for Buffer.buffer;
ProvableI provable;
OracleAddrResolverI OAR;
uint constant day = 60 * 60 * 24;
uint constant week = 60 * 60 * 24 * 7;
uint constant month = 60 * 60 * 24 * 30;
byte constant proofType_NONE = 0x00;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
byte constant proofType_Android = 0x40;
byte constant proofType_TLSNotary = 0x10;
string provable_network_name;
uint8 constant networkID_auto = 0;
uint8 constant networkID_morden = 2;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_consensys = 161;
mapping(bytes32 => bytes32) provable_randomDS_args;
mapping(bytes32 => bool) provable_randomDS_sessionKeysHashVerified;
modifier provableAPI {
if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {
provable_setNetwork(networkID_auto);
}
if (address(provable) != OAR.getAddress()) {
provable = ProvableI(OAR.getAddress());
}
_;
}
modifier provable_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)));
bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName());
require(proofVerified);
_;
}
function provable_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {
_networkID; // NOTE: Silence the warning and remain backwards compatible
return provable_setNetwork();
}
function provable_setNetworkName(string memory _network_name) internal {
provable_network_name = _network_name;
}
function provable_getNetworkName() internal view returns (string memory _networkName) {
return provable_network_name;
}
function provable_setNetwork() internal returns (bool _networkSet) {
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet
OAR = OracleAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
provable_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet
OAR = OracleAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
provable_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet
OAR = OracleAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
provable_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet
OAR = OracleAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
provable_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet
OAR = OracleAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);
provable_setNetworkName("eth_goerli");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge
OAR = OracleAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide
OAR = OracleAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity
OAR = OracleAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
/**
* @dev The following `__callback` functions are just placeholders ideally
* meant to be defined in child contract when proofs are used.
* The function bodies simply silence compiler warnings.
*/
function __callback(bytes32 _myid, string memory _result) virtual public {
__callback(_myid, _result, new bytes(0));
}
function __callback(bytes32 _myid, string memory _result, bytes memory _proof) virtual public {
_myid; _result; _proof;
provable_randomDS_args[bytes32(0)] = bytes32(0);
}
function provable_getPrice(string memory _datasource) provableAPI internal returns (uint _queryPrice) {
return provable.getPrice(_datasource);
}
function provable_getPrice(string memory _datasource, uint _gasLimit) provableAPI internal returns (uint _queryPrice) {
return provable.getPrice(_datasource, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query{value: price}(0, _datasource, _arg);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query{value: price}(_timestamp, _datasource, _arg);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource,_gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query_withGasLimit{value: price}(_timestamp, _datasource, _arg, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query_withGasLimit{value: price}(0, _datasource, _arg, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query2{value: price}(0, _datasource, _arg1, _arg2);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query2{value: price}(_timestamp, _datasource, _arg1, _arg2);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query2_withGasLimit{value: price}(_timestamp, _datasource, _arg1, _arg2, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query2_withGasLimit{value: price}(0, _datasource, _arg1, _arg2, _gasLimit);
}
function provable_query(string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN{value: price}(0, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN{value: price}(_timestamp, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN{value: price}(0, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN{value: price}(_timestamp, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_setProof(byte _proofP) provableAPI internal {
return provable.setProofType(_proofP);
}
function provable_cbAddress() provableAPI internal returns (address _callbackAddress) {
return provable.cbAddress();
}
function getCodeSize(address _addr) view internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function provable_setCustomGasPrice(uint _gasPrice) provableAPI internal {
return provable.setCustomGasPrice(_gasPrice);
}
function provable_randomDS_getSessionPubKeyHash() provableAPI internal returns (bytes32 _sessionKeyHash) {
return provable.randomDS_getSessionPubKeyHash();
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(tmp[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) {
minLength = b.length;
}
for (uint i = 0; i < minLength; i ++) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
}
}
if (a.length < b.length) {
return -1;
} else if (a.length > b.length) {
return 1;
} else {
return 0;
}
}
function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if (h.length < 1 || n.length < 1 || (n.length > h.length)) {
return -1;
} else if (h.length > (2 ** 128 - 1)) {
return -1;
} else {
uint subindex = 0;
for (uint i = 0; i < h.length; i++) {
if (h[i] == n[0]) {
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {
subindex++;
}
if (subindex == n.length) {
return int(i);
}
}
}
return -1;
}
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function parseInt(string memory _a) internal pure returns (uint _parsedInt) {
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeString(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeBytes(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function provable_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10; // Convert from seconds to ledger timer ticks
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(uint8(_nbytes));
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = provable_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
/*
The following variables can be relaxed.
Check the relaxed random contract at https://github.com/oraclize/ethereum-examples
for an idea on how to override and replace commit hash variables.
*/
mstore(add(unonce, 0x20), xor(blockhash(sub(number(), 1)), xor(coinbase(), timestamp())))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = provable_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
provable_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function provable_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal {
provable_randomDS_args[_queryId] = _commitment;
}
function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);
sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs);
if (address(uint160(uint256(keccak256(_pubkey)))) == signer) {
return true;
} else {
(sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);
return (address(uint160(uint256(keccak256(_pubkey)))) == signer);
}
}
function provable_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {
bool sigok;
// Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2);
copyBytes(_proof, _sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1 + 65 + 32);
tosign2[0] = byte(uint8(1)); //role
copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (!sigok) {
return false;
}
// Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1 + 65);
tosign3[0] = 0xFE;
copyBytes(_proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2);
copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
function provable_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {
// Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) {
return 1;
}
bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName());
if (!proofVerified) {
return 2;
}
return 0;
}
function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {
bool match_ = true;
require(_prefix.length == _nRandomBytes);
for (uint256 i = 0; i< _nRandomBytes; i++) {
if (_content[i] != _prefix[i]) {
match_ = false;
}
}
return match_;
}
function provable_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {
// Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)
uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {
return false;
}
bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);
copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) {
return false;
}
// Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (provable_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete provable_randomDS_args[_queryId];
} else return false;
// Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
// Verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (!provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) {
provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = provable_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset);
}
return provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {
uint minLength = _length + _toOffset;
require(_to.length >= minLength); // Buffer too small. Should be a better way?
uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint j = 32 + _toOffset;
while (i < (32 + _fromOffset + _length)) {
assembly {
let tmp := mload(add(_from, i))
mstore(add(_to, j), tmp)
}
i += 32;
j += 32;
}
return _to;
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
Duplicate Solidity's ecrecover, but catching the CALL return value
*/
function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) {
/*
We do our own memory management here. Solidity uses memory offset
0x40 to store the current end of memory. We write past it (as
writes are memory extensions), but don't update the offset so
Solidity will reuse it. The memory used here is only needed for
this context.
FIXME: inline assembly can't access return values
*/
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, _hash)
mstore(add(size, 32), _v)
mstore(add(size, 64), _r)
mstore(add(size, 96), _s)
ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.
addr := mload(size)
}
return (ret, addr);
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
return (false, address(0));
}
/*
The signature format is a compact form of:
{bytes32 r}{bytes32 s}{uint8 v}
Compact means, uint8 is not padded to 32 bytes.
*/
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)))
/*
Alternative solution:
'byte' is not working due to the Solidity parser, so lets
use the second best option, 'and'
v := and(mload(add(_sig, 65)), 255)
*/
}
/*
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 (false, address(0));
}
return safer_ecrecover(_hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize(), sub(msize(), fmem))
}
}
}
// </provableAPI>
// File: contracts/libraries/LTokenManager.sol
pragma solidity 0.6.7;
library LTokenManager {
function decimalPriceToRate(string calldata _priceString)
external
pure
returns (uint256[2] memory rate_)
{
bool hasDp;
uint256 dp;
uint256 result;
uint256 oldResult;
bytes memory priceBytes = bytes(_priceString);
require(priceBytes.length != 0, "Empty string");
if (priceBytes[0] == "0" && priceBytes.length > 1)
require(priceBytes[1] == ".", "Bad format: leading zeros");
for (uint i = 0; i < priceBytes.length; i++) {
if (priceBytes[i] == "." && !hasDp) {
require(i < priceBytes.length - 1, "Bad format: expected mantissa");
hasDp = true;
} else if (uint8(priceBytes[i]) >= 48 && uint8(priceBytes[i]) <= 57) {
if (hasDp) dp++;
oldResult = result;
result = result * 10 + (uint8(priceBytes[i]) - 48);
if (oldResult > result || 10**dp < 10**(dp -1))
revert("Overflow");
}
else
revert("Bad character");
}
require(result != 0, "Zero value");
while (result % 10 == 0) {
result = result / 10;
dp--;
}
rate_ = [result, 10**dp];
}
}
// File: contracts/TokenManager.sol
pragma solidity 0.6.7;
contract TokenManager is Owned, usingProvable {
address public immutable token;
uint256 public provableUpdateInterval;
string public provableQuery;
byte public provableProofType;
uint256 public provableGasPrice;
uint256 public provableGasLimit;
bool public autoUpdate;
bytes32 private provableQueryID;
event LogFundsReceived(address indexed sender, uint256 amount);
event LogFundsRecovered(address recipient, uint256 amount);
event LogNewRateReceived(uint256[2] rate, bytes indexed proof, string status);
event LogNewQuery(uint256 cost, string status);
event LogProvableSettingsUpdated(uint256 interval, string query, byte proofType, uint256 gasPrice, uint256 gasLimit,
bool autoUpdate);
constructor(address _token)
internal
{
token = _token;
}
modifier onlyProvable() {
require(msg.sender == provable_cbAddress(), "Not Provable");
_;
}
modifier onlyCurrentQuery(bytes32 _id) {
require(provableQueryID == _id, "Bad ID");
_;
}
receive() external payable {
emit LogFundsReceived(msg.sender, msg.value);
}
// TODO: Consider removing gasPrice from here.
function updateProvableSettings(uint256 _interval, string calldata _query, byte _proofType, uint256 _gasPrice,
uint256 _gasLimit, bool _autoUpdate)
onlyOwner
external
{
provableUpdateInterval = _interval;
provableQuery = _query;
if (provableProofType != _proofType) {
provableProofType = _proofType;
provable_setProof(provableProofType);
}
autoUpdate = _autoUpdate;
updateProvableGasPrice(_gasPrice);
provableGasLimit = _gasLimit;
emit LogProvableSettingsUpdated(provableUpdateInterval, provableQuery, provableProofType, provableGasPrice,
provableGasLimit, autoUpdate);
}
function recoverFunds()
onlyOwner
external
{
uint256 balance = address(this).balance;
(bool success,) = msg.sender.call{value:balance}("");
require(success);
emit LogFundsRecovered(msg.sender, balance);
}
function updateExchangeRate()
external
payable
onlyOwner
{
if (msg.value > 0)
emit LogFundsReceived(msg.sender, msg.value);
doUpdateExchangeRate();
}
function updateProvableGasPrice(uint256 _gasPrice)
onlyOwner
public
{
if (provableGasPrice != _gasPrice) {
provableGasPrice = _gasPrice;
provable_setCustomGasPrice(provableGasPrice);
}
// TODO: Consider emitting a log.
}
function __callback(bytes32 _id, string memory _result, bytes memory _proof)
override
public
onlyProvable
{
try this.decimalPriceToRate(_id, _result) returns (uint256[2] memory rate) {
emit LogNewRateReceived(rate, _proof, "Success");
VOWToken(token).setUSDRate(rate[0], rate[1]);
if (autoUpdate)
doUpdateExchangeRate();
} catch Error(string memory reason) {
emit LogNewRateReceived([uint256(0),uint256(0)], _proof, reason);
}
}
function decimalPriceToRate(bytes32 _id, string memory _priceString)
public
view
onlyCurrentQuery(_id)
returns (uint256[2] memory rate_)
{
rate_ = LTokenManager.decimalPriceToRate(_priceString);
}
function doUpdateExchangeRate()
private
{
uint256 cost = provable_getPrice("URL", provableGasLimit);
if (cost > address(this).balance)
emit LogNewQuery(cost, "Query not sent, requires ETH");
else {
provableQueryID = provable_query(provableUpdateInterval, "URL", provableQuery, provableGasLimit);
emit LogNewQuery(cost, "Query sent, awaiting result...");
}
}
}
// File: contracts/VSCTokenManager.sol
pragma solidity 0.6.7;
contract VSCTokenManager is TokenManager, IERC777Recipient {
using SafeMath for uint256;
enum RatioType {
MerchantLockBurnVOW,
MerchantLockMintVSC,
Liquidity
}
address public immutable vowContract;
mapping(address => uint256[2]) public merchantVOWToVSCLock;
mapping(address => bool) public registeredMVD;
mapping(RatioType => uint256[2]) public ratios;
// Universal address as defined in Registry Contract Address section of https://eips.ethereum.org/EIPS/eip-1820
IERC1820Registry constant private ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// precalculated hash - see https://github.com/ethereum/solidity/issues/4024
// keccak256("ERC777TokensRecipient")
bytes32 constant private ERC777_TOKENS_RECIPIENT_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
event LogMVDRegistered(address indexed mvd);
event LogMVDDeregistered(address indexed mvd);
event LogRatioUpdated(uint256[2] ratio, RatioType ratioType);
event LogBurnAndMint(address indexed from, uint256 vowAmount, uint256 vscAmount);
event LogMerchantVOWLocked(address indexed mvd, address indexed merchant, uint256 lockedVOW, uint256 mintedVSC);
event LogMerchantVOWUnlocked(address indexed unlocker, address indexed merchant, uint256 unlockedVOW, uint256 returnedVSC);
constructor(address _token)
TokenManager(_token)
public
{
vowContract = VSCToken(_token).vowContract();
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC777_TOKENS_RECIPIENT_HASH, address(this));
ratios[RatioType.MerchantLockBurnVOW] = [1,5]; // ie: burn 1 VOW for every 5 VOW locked
ratios[RatioType.MerchantLockMintVSC] = [5,1]; // ie: mint 5 VSC for every 1 VSC
ratios[RatioType.Liquidity] = [984,1000]; // ie: expect a 1.6% burn on tier2, a liquidity ratio of 62.5
}
modifier mvdNotNull(address _mvd) {
require(_mvd != address(0), "MVD address cannot be null");
_;
}
function setRatio(uint256[2] calldata _ratio, RatioType _ratioType)
external
onlyOwner
{
require(_ratio[1] != 0, "Invalid ratio: div by zero");
if (_ratioType != RatioType.MerchantLockMintVSC)
require(_ratio[1] >= _ratio[0], "Invalid lock ratio: above 100%");
ratios[_ratioType] = _ratio;
emit LogRatioUpdated(_ratio, _ratioType);
}
function getLiquidityRatio()
external
view
returns (uint256[2] memory liquidity_)
{
liquidity_ = ratios[RatioType.Liquidity];
}
function registerMVD(address _mvd)
external
onlyOwner
mvdNotNull(_mvd)
{
registeredMVD[_mvd] = true;
emit LogMVDRegistered(_mvd);
}
function deregisterMVD(address _mvd)
external
onlyOwner
mvdNotNull(_mvd)
{
registeredMVD[_mvd] = false;
emit LogMVDDeregistered(_mvd);
}
function tokensReceived(address /* _operator */, address _from, address /* _to */, uint256 _amount, bytes calldata _data,
bytes calldata /* _operatorData */)
external
virtual
override
{
if (msg.sender == vowContract)
tokensReceivedVOW(_from, _data, _amount);
else if (msg.sender == token)
tokensReceivedThisVSC(_from, _data, _amount);
else
revert("Bad token");
}
function getVOWVSCRate()
public
view
returns (uint256 numVOW_, uint256 numVSC_)
{
VSCToken vscToken = VSCToken(token);
VOWToken vowToken = VOWToken(vowContract);
numVOW_ = vowToken.usdRate(0).mul(vscToken.usdRate(1));
numVSC_ = vowToken.usdRate(1).mul(vscToken.usdRate(0));
}
function tokensReceivedVOW(address _from, bytes memory _data, uint256 _amount)
private
{
if (registeredMVD[_from]) {
(address merchant, bytes memory data) = abi.decode(_data, (address, bytes));
doMerchantLock(_from, merchant, _amount, data);
return;
}
VOWToken(vowContract).burn(_amount, "");
(uint256 numVOW, uint256 numVSC) = getVOWVSCRate();
uint256 vscAmount = _amount.mul(numVSC).div(numVOW);
VSCToken(token).mint(_from, vscAmount);
emit LogBurnAndMint(_from, _amount, vscAmount);
}
function tokensReceivedThisVSC(address _from, bytes memory _data, uint256 _amount)
private
{
doMerchantUnlock(_from, abi.decode(_data, (address)), _amount);
}
function doMerchantLock(address _mvd, address _merchant, uint256 _vowAmount, bytes memory _data)
private
{
require(merchantVOWToVSCLock[_merchant][0] == 0, "Merchant is locked");
(uint256 numVOW, uint256 numVSC) = getVOWVSCRate();
uint256 burnAmount = _vowAmount.mul(ratios[RatioType.MerchantLockBurnVOW][0]).div(ratios[RatioType.MerchantLockBurnVOW][1]);
uint256 vscAmount = _vowAmount.mul(numVSC).mul(ratios[RatioType.MerchantLockMintVSC][0]).
div(numVOW.mul(ratios[RatioType.MerchantLockMintVSC][1]));
merchantVOWToVSCLock[_merchant][0] = _vowAmount.sub(burnAmount);
merchantVOWToVSCLock[_merchant][1] = vscAmount;
VOWToken(vowContract).burn(burnAmount, "");
VSCToken(token).mint(_mvd, vscAmount);
VSCToken(token).lift(_mvd, vscAmount, _data);
emit LogMerchantVOWLocked(_mvd, _merchant, merchantVOWToVSCLock[_merchant][0], vscAmount);
}
function doMerchantUnlock(address _unlocker, address _merchant, uint256 _vscAmount)
private
{
require(merchantVOWToVSCLock[_merchant][0] > 0, "No VOW to unlock");
require(merchantVOWToVSCLock[_merchant][1] == _vscAmount, "Incorrect VSC amount");
VSCToken(token).burn(_vscAmount, "");
VOWToken(vowContract).send(_merchant, merchantVOWToVSCLock[_merchant][0], "");
emit LogMerchantVOWUnlocked(_unlocker, _merchant, merchantVOWToVSCLock[_merchant][0], _vscAmount);
delete merchantVOWToVSCLock[_merchant];
}
}
// File: contracts/libraries/LOrdersDLL.sol
pragma solidity 0.6.7;
library LOrdersDLL {
using SafeMath for uint256;
struct EntriesDLL {
mapping(bytes32 => Entry) entries;
bytes32 head;
bytes32 tail;
}
struct Entry {
EntryData entryData;
bytes32 prevHash;
bytes32 nextHash;
}
struct EntryData {
address seller;
uint256 sellAmount; // in atto units
uint256 buyAmount; // in atto units
uint256 timestamp; // when the entry was submitted
}
function getPositionInOrderBook(EntriesDLL storage _dll, bytes32 _entryHash)
external
view
returns (uint256 position_)
{
bytes32 checkHash = _dll.head;
while(_entryHash != checkHash) {
require(checkHash != 0, "Entry not found");
checkHash = _dll.entries[checkHash].prevHash;
++position_;
}
}
// Split the DLL of entries: everything from the head to the splitEntry is separated from the DLL, the entry that is closer to
// the tail, if there is one, is now the head.
function splitBookDLLAtEntry(EntriesDLL storage _dll, bytes32 splitEntryHash)
external
{
Entry storage splitEntry = _dll.entries[splitEntryHash];
assert(splitEntry.entryData.timestamp != 0); // Entry must exist!
// Make splitEntry's previous entry the new head.
if (splitEntry.prevHash != 0)
_dll.entries[splitEntry.prevHash].nextHash = 0;
_dll.head = splitEntry.prevHash;
if (_dll.tail == splitEntryHash)
_dll.tail = 0;
splitEntry.prevHash = 0;
}
function addEntryForRemainder(EntriesDLL storage _dll, uint256 _lastEntryAmountBought, uint256 _lastEntryAmountSold,
Entry storage _lastEntry)
external
returns (bytes32 newHeadEntryHash_, uint256 remainingSellAmount_)
{
Entry memory remainderEntry;
remainderEntry.entryData = cloneEntryDataStruct(_lastEntry.entryData);
remainingSellAmount_ = remainderEntry.entryData.sellAmount.sub(_lastEntryAmountSold);
remainderEntry.entryData.sellAmount = remainingSellAmount_;
remainderEntry.entryData.buyAmount = remainderEntry.entryData.buyAmount.sub(_lastEntryAmountBought);
newHeadEntryHash_ = addEntryToHeadOfBookDLL(_dll, remainderEntry);
assert(_dll.entries[newHeadEntryHash_].entryData.timestamp == 0);
_dll.entries[newHeadEntryHash_] = remainderEntry;
}
function removeEntryFromBookDLL(EntriesDLL storage _dll, Entry storage _entryToRemove)
external
{
if (_entryToRemove.prevHash != 0) {
Entry storage prevEntry = _dll.entries[_entryToRemove.prevHash];
prevEntry.nextHash = _entryToRemove.nextHash;
} else
_dll.tail = _entryToRemove.nextHash;
if (_entryToRemove.nextHash != 0) {
Entry storage nextEntry = _dll.entries[_entryToRemove.nextHash];
nextEntry.prevHash = _entryToRemove.prevHash;
} else
_dll.head = _entryToRemove.prevHash;
}
function addEntryToOrderBook(EntriesDLL storage _dll, address _from, uint256 _amount, bytes calldata _params)
external
returns (bytes32 entryHash_)
{
EntryData memory entryData;
bytes32 expectedPrevHash;
(entryData.seller, entryData.sellAmount, entryData.buyAmount, expectedPrevHash) = abi.decode(_params,
(address, uint256, uint256, bytes32));
require(entryData.seller == _from, "From must match encoded seller");
require(entryData.sellAmount == _amount, "Amount must match encoded amount");
assert(entryData.buyAmount != 0);
entryData.timestamp = now;
entryHash_ = insertEntryIntoBookDLL(_dll, entryData, expectedPrevHash);
}
function findActualPrevHash(EntriesDLL storage _dll, uint256 _sellAmount, uint256 _buyAmount)
external
view
returns (bytes32 prevHash_)
{
EntryData memory entryData = EntryData(msg.sender, _sellAmount, _buyAmount, now);
prevHash_ = findActualPrevHash(_dll, _dll.head, entryData);
}
function addEntryToHeadOfBookDLL(EntriesDLL storage _dll, Entry memory newEntry)
private
returns (bytes32 newEntryHash)
{
newEntryHash = getEntryHash(newEntry.entryData);
if (_dll.head == 0)
_dll.tail = newEntryHash;
else
_dll.entries[_dll.head].nextHash = newEntryHash;
newEntry.prevHash = _dll.head;
newEntry.nextHash = 0;
_dll.head = newEntryHash;
}
function insertEntryIntoBookDLL(EntriesDLL storage _dll, EntryData memory _entryData, bytes32 _expectedPrevHash)
private
returns (bytes32 entryHash_)
{
bytes32 actualPrevHash = findActualPrevHash(_dll, _expectedPrevHash, _entryData);
entryHash_ = getEntryHash(_entryData);
require(_dll.entries[entryHash_].entryData.timestamp == 0, "Entry already in order book");
bytes32 nextHash;
if (actualPrevHash == 0) {
nextHash = _dll.tail;
_dll.tail = entryHash_;
} else {
Entry storage prevEntry = _dll.entries[actualPrevHash];
nextHash = prevEntry.nextHash;
prevEntry.nextHash = entryHash_;
}
if (nextHash == 0)
_dll.head = entryHash_;
else {
Entry storage nextEntry = _dll.entries[nextHash];
require(pricesOrTimestampsAreDifferent(_entryData, nextEntry.entryData), "Price at time not unique: retry");
nextEntry.prevHash = entryHash_;
}
Entry memory entry = Entry(_entryData, actualPrevHash, nextHash);
_dll.entries[entryHash_] = entry;
}
function findActualPrevHash(EntriesDLL storage _dll, bytes32 _expectedPrevHash, EntryData memory _entryData)
private
view
returns (bytes32)
{
Entry memory actualPrev = (_expectedPrevHash == 0) ? _dll.entries[_dll.tail] :
_dll.entries[_expectedPrevHash];
// If the price is greater than the prev entry & less than or equal to the next entry then the position is correct
if (priceIsGreaterThan(_entryData, actualPrev.entryData) &&
priceIsLessThanOrEqualTo(_entryData, _dll.entries[actualPrev.nextHash].entryData))
return _expectedPrevHash;
// If the price is less than or equal to the prev entry search down for the lowest equal or greater than entry
if (priceIsLessThanOrEqualTo(_entryData, actualPrev.entryData)) {
while (priceIsLessThanOrEqualTo(_entryData, actualPrev.entryData)) {
if (actualPrev.prevHash == 0) return 0;
actualPrev = _dll.entries[actualPrev.prevHash];
}
return getEntryHash(actualPrev.entryData);
}
// Otherwise search up whilst the price remains greater than the next entry
while (actualPrev.nextHash != 0 && priceIsGreaterThan(_entryData, actualPrev.entryData))
actualPrev = _dll.entries[actualPrev.nextHash];
return getEntryHash(actualPrev.entryData);
}
function getEntryHash(EntryData memory _entryData)
private
pure
returns (bytes32 entryHash_)
{
entryHash_ = keccak256(abi.encodePacked(_entryData.seller, _entryData.sellAmount, _entryData.buyAmount,
_entryData.timestamp));
}
function priceIsLessThanOrEqualTo(EntryData memory _entryData, EntryData memory _otherEntryData)
private
pure
returns (bool)
{
return _entryData.sellAmount.mul(_otherEntryData.buyAmount) <= _otherEntryData.sellAmount.mul(_entryData.buyAmount);
}
function priceIsGreaterThan(EntryData memory _entryData, EntryData memory _otherEntryData)
private
pure
returns (bool)
{
return _entryData.sellAmount.mul(_otherEntryData.buyAmount) > _otherEntryData.sellAmount.mul(_entryData.buyAmount);
}
function priceIsNotEqualTo(EntryData memory _entryData, EntryData memory _otherEntryData)
private
pure
returns (bool)
{
return _entryData.sellAmount.mul(_otherEntryData.buyAmount) != _otherEntryData.sellAmount.mul(_entryData.buyAmount);
}
function pricesOrTimestampsAreDifferent(EntryData memory _entryData, EntryData memory _otherEntryData)
private
pure
returns (bool areDifferent_)
{
areDifferent_ = _entryData.timestamp != _otherEntryData.timestamp;
if (!areDifferent_)
areDifferent_ = priceIsNotEqualTo(_entryData, _otherEntryData);
}
function cloneEntryDataStruct(EntryData storage _entryData)
private
view
returns (EntryData memory entryData_)
{
entryData_ = EntryData(_entryData.seller, _entryData.sellAmount, _entryData.buyAmount, _entryData.timestamp);
}
}
// File: contracts/libraries/LOrderBooks.sol
pragma solidity 0.6.7;
library LOrderBooks {
using SafeMath for uint256;
struct Market {
OrderBook vowToVSC;
uint256 lastFinalised;
uint256 period;
uint256 minimumVSCAmount;
uint8 mintVOWCounter;
Frozen frozen;
}
struct OrderBook {
LOrdersDLL.EntriesDLL dll;
FinalisedBook[] finalisedBooks;
bool isFrozen;
}
struct Frozen {
uint256 timestamp;
uint256 amountBurnedInTier2;
uint256 amountInIlliquidAccounts;
uint256 amountOfVSC;
}
struct FinalisedBook {
Frozen frozen; // Separate struct due to stack depth issue when decoding
uint256 amountMintedForBook;
uint256 amountBurnedForBook;
uint256[2] winningPrice;
bytes32 lastEntryHash; // The last "winner"
uint256 lastEntryAmountBought; // The amount bought by the last entry
uint256 lastEntryAmountSold; // The amount sold by the last entry
uint256 lastEntryTimestamp;
}
event LogOrderBookSplitWinner(address indexed vscContract, address indexed seller, bytes32 indexed lastEntryHash,
uint256 amountBought, bytes32 remainderEntryHash, uint256 remainingSellAmount);
modifier onlyAfterOrderBooksPeriod(Market storage _market) {
require(_market.lastFinalised.add(_market.period) <= now, "Not enough time elapsed");
_;
}
function getPositionInOrderBook(Market storage _market, bytes32 _entryHash)
external
view
returns (uint256 position_)
{
OrderBook storage orderBook = _market.vowToVSC;
position_ = LOrdersDLL.getPositionInOrderBook (orderBook.dll, _entryHash);
}
function addEntryToOrderBook(Market storage _market, address _from, uint256 _amount, bytes calldata _params)
external
returns (bytes32 entryHash_)
{
OrderBook storage orderBook = _market.vowToVSC;
entryHash_ = LOrdersDLL.addEntryToOrderBook(orderBook.dll, _from, _amount, _params);
}
function getAddEntryToOrderBookParams(Market storage _market, uint256 _sellAmount, uint256 _buyAmount)
external
view
returns (bytes memory params_)
{
OrderBook storage orderBook = _market.vowToVSC;
require(_sellAmount != 0, "Cannot sell zero");
require(_buyAmount != 0, "Cannot buy zero");
bytes32 prevHash = LOrdersDLL.findActualPrevHash(orderBook.dll, _sellAmount, _buyAmount);
params_ = abi.encode(msg.sender, _sellAmount, _buyAmount, prevHash);
}
function removeEntryFromOrderBook(Market storage _market, bytes32 _entryHash, address _from)
external
returns (uint256 amountToReturn_)
{
OrderBook storage orderBook = _market.vowToVSC;
LOrdersDLL.Entry storage entryToRemove = orderBook.dll.entries[_entryHash];
require(entryToRemove.entryData.timestamp != 0, "Entry not in order book");
require(entryToRemove.entryData.seller == _from, "Only order owner can remove");
(bool isFound, ) = isInAFinalisedBook(orderBook.finalisedBooks, _entryHash, entryToRemove.entryData);
require(!isFound, "Please call completeOrder");
LOrdersDLL.removeEntryFromBookDLL(orderBook.dll, entryToRemove);
amountToReturn_ = entryToRemove.entryData.sellAmount;
delete orderBook.dll.entries[_entryHash];
}
function completeEntryFromFinalisedBook(Market storage _market, bytes32 _entryHash, address _from)
external
returns (uint256 amountToReturn_)
{
OrderBook storage orderBook = _market.vowToVSC;
LOrdersDLL.Entry memory entryToComplete = orderBook.dll.entries[_entryHash];
require(entryToComplete.entryData.timestamp != 0, "Entry not in finalised book");
require(entryToComplete.entryData.seller == _from, "Only order owner can complete");
bool isFound;
(isFound, amountToReturn_) = isInAFinalisedBook(orderBook.finalisedBooks, _entryHash, entryToComplete.entryData);
require(isFound, "Please call removeOrder");
delete orderBook.dll.entries[_entryHash];
}
function freezeOrderBook(Market storage _market, uint256 _totalSupply, uint256 _amountBurnedInTier2,
uint256 _amountInIlliquidAccounts, uint256[2] calldata _liquidityRatio)
external
onlyAfterOrderBooksPeriod(_market)
returns(string memory noOrderBookReason_)
{
uint256 amountOfVSC;
amountOfVSC = getAmountOfVSCForOrderBook(_totalSupply, _amountBurnedInTier2, _amountInIlliquidAccounts,
_liquidityRatio, _market.minimumVSCAmount);
if (amountOfVSC == 0) {
noOrderBookReason_ = "No mint required";
_market.lastFinalised = now;
_market.mintVOWCounter = 0;
} else {
OrderBook storage orderBook = _market.vowToVSC;
require(orderBook.dll.head != 0, "No entries in order book");
_market.frozen.timestamp = now;
_market.frozen.amountBurnedInTier2 = _amountBurnedInTier2;
_market.frozen.amountInIlliquidAccounts = _amountInIlliquidAccounts;
_market.frozen.amountOfVSC = amountOfVSC;
orderBook.isFrozen = true;
}
}
function getFinaliseOrderBookParams(Market storage _market)
external
view
returns (bytes memory params_)
{
uint256 amountOfVSC = _market.frozen.amountOfVSC;
assert(amountOfVSC > 0);
FinalisedBook memory finalisedBook = getFinalisedBookWithLastEntry(_market.vowToVSC, amountOfVSC);
finalisedBook.frozen.timestamp = _market.frozen.timestamp;
bytes memory encodedFinalisedBook = encodeFinaliseOrderBookParams(finalisedBook);
params_ = abi.encode(address(this), encodedFinalisedBook);
}
function finaliseOrderBook(address _vscContract, Market storage _market, bytes calldata _encodedParams)
external
{
OrderBook storage frozenBook = _market.vowToVSC;
(address encoder, bytes memory encodedParams) = abi.decode(_encodedParams, (address, bytes));
require(encoder == address(this), "Wrong encoder");
(FinalisedBook memory finalisedBook) = decodeFinaliseOrderBookParams(encodedParams);
require(finalisedBook.frozen.timestamp == _market.frozen.timestamp, "Wrong encoded params");
finalisedBook.frozen = cloneFrozenStruct(_market.frozen);
frozenBook.finalisedBooks.push(finalisedBook);
LOrdersDLL.Entry storage lastEntry = frozenBook.dll.entries[finalisedBook.lastEntryHash];
LOrdersDLL.splitBookDLLAtEntry(frozenBook.dll, finalisedBook.lastEntryHash);
uint256 lastEntryAmountBought = finalisedBook.lastEntryAmountBought;
if (lastEntryAmountBought < lastEntry.entryData.buyAmount) {
(bytes32 newHeadEntryHash, uint256 remainingSellAmount) = LOrdersDLL.addEntryForRemainder(frozenBook.dll,
lastEntryAmountBought, finalisedBook.lastEntryAmountSold, lastEntry);
emit LogOrderBookSplitWinner(_vscContract, lastEntry.entryData.seller, finalisedBook.lastEntryHash, lastEntryAmountBought,
newHeadEntryHash, remainingSellAmount);
}
_market.mintVOWCounter = 0;
}
function getAmountOfVSCForOrderBook(uint256 _totalSupply, uint256 _amountBurnedInTier2, uint256 _amountInIlliquidAccounts,
uint256[2] memory _liquidityRatio, uint256 _minimumVSCAmount)
internal
pure
returns(uint256 amountOfVSC_)
{
if (_totalSupply == 0) return (0);
require(_totalSupply >= _amountInIlliquidAccounts, "Illiquid amount exceeds supply");
uint256 liquidSupply = _totalSupply.sub(_amountInIlliquidAccounts);
require(liquidSupply >= _amountBurnedInTier2, "Tier2 burn exceeds liquid supply");
uint256 expectedSupply = liquidSupply.mul(_liquidityRatio[0]).div(_liquidityRatio[1]);
uint256 actualSupply = liquidSupply.sub(_amountBurnedInTier2);
if (expectedSupply > actualSupply && expectedSupply.sub(actualSupply) >= _minimumVSCAmount)
amountOfVSC_ = expectedSupply.sub(actualSupply);
}
function getFinalisedBookWithLastEntry(OrderBook storage _orderBook, uint256 _amountOfVSC)
private
view
returns (FinalisedBook memory finalisedBook_)
{
finalisedBook_.amountMintedForBook = _amountOfVSC;
uint256 vscRemainingForUsersToBuy = _amountOfVSC;
uint256 vowBurnedForBook;
uint256 userBuysVSCAmount;
uint256 userSellsVOWAmount;
bytes32 entryHash = _orderBook.dll.head;
while (true) {
LOrdersDLL.Entry storage entry = _orderBook.dll.entries[entryHash];
LOrdersDLL.EntryData storage entryData = entry.entryData;
userBuysVSCAmount = entryData.buyAmount;
userSellsVOWAmount = entryData.sellAmount;
if (vscRemainingForUsersToBuy > userBuysVSCAmount) {
vscRemainingForUsersToBuy = vscRemainingForUsersToBuy.sub(userBuysVSCAmount);
vowBurnedForBook = vowBurnedForBook.add(userSellsVOWAmount);
entryHash = entry.prevHash;
require(entryHash != 0, "Not enough entries: unfreeze");
} else {
// We have found the last entry.
finalisedBook_.lastEntryTimestamp = entryData.timestamp;
break;
}
}
if (vscRemainingForUsersToBuy == userBuysVSCAmount) {
finalisedBook_.lastEntryAmountSold = userSellsVOWAmount;
finalisedBook_.amountBurnedForBook = vowBurnedForBook.add(userSellsVOWAmount);
} else {
uint256 partialSellAmount = vscRemainingForUsersToBuy.mul(userSellsVOWAmount).div(userBuysVSCAmount);
if (partialSellAmount == 0) {
// Special case for fractional remaining amount.
partialSellAmount = 1;
}
finalisedBook_.lastEntryAmountSold = partialSellAmount;
finalisedBook_.amountBurnedForBook = vowBurnedForBook.add(partialSellAmount);
}
finalisedBook_.lastEntryHash = entryHash;
finalisedBook_.winningPrice = [userSellsVOWAmount, userBuysVSCAmount];
finalisedBook_.lastEntryAmountBought = vscRemainingForUsersToBuy;
}
function encodeFinaliseOrderBookParams(FinalisedBook memory _finalisedBook)
private
pure
returns (bytes memory encodedParams_)
{
encodedParams_ = abi.encode(_finalisedBook.frozen.timestamp, _finalisedBook.amountMintedForBook,
_finalisedBook.amountBurnedForBook, _finalisedBook.winningPrice, _finalisedBook.lastEntryHash,
_finalisedBook.lastEntryAmountBought, _finalisedBook.lastEntryAmountSold, _finalisedBook.lastEntryTimestamp);
}
function decodeFinaliseOrderBookParams(bytes memory _encodedParams)
private
pure
returns (FinalisedBook memory book_)
{
(book_.frozen.timestamp, book_.amountMintedForBook, book_.amountBurnedForBook, book_.winningPrice, book_.lastEntryHash,
book_.lastEntryAmountBought, book_.lastEntryAmountSold, book_.lastEntryTimestamp) =
abi.decode(_encodedParams, (uint256, uint256, uint256, uint256[2], bytes32, uint256, uint256, uint256));
}
function cloneFrozenStruct(Frozen storage _frozen)
private
view
returns (Frozen memory frozen_)
{
frozen_ = Frozen(_frozen.timestamp, _frozen.amountBurnedInTier2, _frozen.amountInIlliquidAccounts, _frozen.amountOfVSC);
}
function isInAFinalisedBook(FinalisedBook[] storage _finalisedBooks, bytes32 _entryHash,
LOrdersDLL.EntryData memory _entryData)
private
view
returns (bool isFound_, uint256 lastEntryAmountBought_)
{
for (uint i = 0; i < _finalisedBooks.length; i++) {
FinalisedBook storage finalisedBook = _finalisedBooks[i];
if (_entryData.timestamp > finalisedBook.frozen.timestamp)
continue;
if (finalisedBook.lastEntryHash == _entryHash)
return (true, finalisedBook.lastEntryAmountBought);
// If entry is NOT the last entry, but has the same timestamp, then it is the partial remainder entry.
if (finalisedBook.lastEntryTimestamp == _entryData.timestamp)
continue;
// If entryPrice > winningPrice, then entry is a winner.
if (finalisedBook.winningPrice[0].mul(_entryData.buyAmount) < finalisedBook.winningPrice[1].mul(_entryData.sellAmount))
return (true, _entryData.buyAmount);
// If entryPrice < winningPrice, then entry is NOT a winner.
if (finalisedBook.winningPrice[0].mul(_entryData.buyAmount) != finalisedBook.winningPrice[1].mul(_entryData.sellAmount))
continue;
// If entryPrice == winningPrice, then entry is a winner IFF the entry timestamp was before that of the last winner.
if (finalisedBook.lastEntryTimestamp > _entryData.timestamp)
return (true, _entryData.buyAmount);
}
}
}
// File: contracts/OrderBooksManager.sol
pragma solidity 0.6.7;
contract OrderBooksManager is IERC777Recipient, Owned {
using SafeMath for uint256;
bytes32 constant VSC_TOKEN_MANAGER_KEY = keccak256(abi.encodePacked("VSCTokenManager"));
// Universal address as defined in Registry Contract Address section of https://eips.ethereum.org/EIPS/eip-1820
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// precalculated hash - see https://github.com/ethereum/solidity/issues/4024
// keccak256("ERC777TokensRecipient")
bytes32 constant internal ERC777_TOKENS_RECIPIENT_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
address public immutable vscContract;
address public immutable vowContract;
address public artosFTSM;
LOrderBooks.Market private market;
mapping (bytes => bool) private proofs;
event LogOrderBookPeriodUpdated(uint256 oldPeriod, uint256 newPeriod);
event LogOrderBookMinimumVSCAmountUpdated(uint256 oldAmount, uint256 newAmount);
event LogOrderBookEntryAdded(address indexed vscContract, address indexed from, bytes params, bytes32 indexed orderEntryHash);
event LogOrderBookEntryRemoved(address indexed vscContract, address indexed from, bytes32 indexed orderEntryHash,
uint256 returnedAmount);
event LogOrderBookEntryCompleted(address indexed vscContract, address indexed from, bytes32 indexed orderEntryHash,
uint256 returnedAmount);
event LogOrderBookFrozen(address indexed vscContract, uint256 timestamp, uint256 amountBurnedInTier2,
uint256 amountInIlliquidAccounts, uint256 amountOfVSC);
event LogOrderBookNotFrozen(address indexed vscContract, string reason);
event LogOrderBookUnfrozen(address indexed vscContract);
event LogOrderBookSplitWinner(address indexed vscContract, address indexed seller, bytes32 indexed lastEntryHash,
uint256 amountBought, bytes32 remainderEntryHash, uint256 remainingSellAmount);
event LogOrderBookFinalised(address indexed vscContract, uint256 amountBurnedForBook, uint256 amountMintedForBook,
uint256[2] winningPrice, bytes32 indexed lastEntryHash, uint256 lastEntryAmountBought, uint256 lastEntryTimestamp);
constructor(address _vscContract)
public
{
vowContract = VSCToken(_vscContract).vowContract();
vscContract = _vscContract;
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC777_TOKENS_RECIPIENT_HASH, address(this));
market.period = 30 days;
market.lastFinalised = now;
market.minimumVSCAmount = 1000; // 1 * 10^-15 VSC
}
modifier proxyCheck(address _from) {
require(msg.sender == _from || msg.sender == address(this), "Failed proxy check");
_;
}
modifier onlyRegisteredMVD(address _from) {
require(getVSCTokenManager().registeredMVD(_from), "Registered MVD only");
_;
}
modifier onlyWhenBookIsFrozen() {
require(market.vowToVSC.isFrozen, "Order book not frozen");
_;
}
modifier onlyWhenBookIsNotFrozen() {
require(!market.vowToVSC.isFrozen, "Order book is frozen");
_;
}
function getPositionInOrderBook(bytes32 _entryHash)
external
view
returns (uint256 position_)
{
position_ = LOrderBooks.getPositionInOrderBook(market, _entryHash);
}
function setOrderBooksPeriod(uint256 _orderBooksPeriod)
external
onlyOwner
{
require(_orderBooksPeriod != 0, "Cannot set 0 period");
emit LogOrderBookPeriodUpdated(market.period, _orderBooksPeriod);
market.period = _orderBooksPeriod;
}
function setOrderBooksMinimumVSCAmount(uint256 _amount)
external
onlyOwner
{
emit LogOrderBookMinimumVSCAmountUpdated(market.minimumVSCAmount, _amount);
market.minimumVSCAmount = _amount;
}
function tokensReceived(address /* _operator */, address _from, address /* _to */, uint256 _amount, bytes calldata _data,
bytes calldata /* _operatorData */)
external
override
{
// If we just minted to ourselves as a result of finalising the order book then ignore.
if (_from == address(0)) return;
if (_amount == 0) {
require(msg.sender == vscContract, "Cannot proxy for unknown token");
(bool success,) = address(this).call(_data);
require(success, "Execution failed");
} else {
require(msg.sender == vowContract, "Can only add entry with VOW");
addOrderBookEntry(_from, _amount, _data);
}
}
function freezeOrderBook(address _from, uint256 _amountBurnedInTier2, uint256 _amountInIlliquidAccounts)
onlyRegisteredMVD(_from)
proxyCheck(_from)
onlyWhenBookIsNotFrozen
external
{
VSCTokenManager vscTokenManager = getVSCTokenManager();
string memory notFrozenReason = LOrderBooks.freezeOrderBook(market, VSCToken(vscContract).totalSupply(),
_amountBurnedInTier2, _amountInIlliquidAccounts, vscTokenManager.getLiquidityRatio());
if (bytes(notFrozenReason).length != 0)
emit LogOrderBookNotFrozen(vscContract, notFrozenReason);
else {
LOrderBooks.Frozen storage frozen = market.frozen;
emit LogOrderBookFrozen(vscContract, frozen.timestamp, frozen.amountBurnedInTier2, frozen.amountInIlliquidAccounts,
frozen.amountOfVSC);
}
}
function unfreezeOrderBook(address _from)
onlyRegisteredMVD(_from)
proxyCheck(_from)
onlyWhenBookIsFrozen
external
{
market.vowToVSC.isFrozen = false;
emit LogOrderBookUnfrozen(vscContract);
}
function getFinaliseOrderBookParams()
onlyWhenBookIsFrozen
external
view
returns (bytes memory encodedParams_)
{
encodedParams_ = LOrderBooks.getFinaliseOrderBookParams(market);
}
function finaliseOrderBook(address _from, bytes calldata _encodedParams)
onlyRegisteredMVD(_from)
proxyCheck(_from)
onlyWhenBookIsFrozen
external
{
LOrderBooks.finaliseOrderBook(vscContract, market, _encodedParams);
LOrderBooks.OrderBook storage orderBook = market.vowToVSC;
LOrderBooks.FinalisedBook storage finalisedBook = orderBook.finalisedBooks[orderBook.finalisedBooks.length.sub(1)];
VSCToken(vscContract).mint(address(this), finalisedBook.amountMintedForBook);
VOWToken(vowContract).burn(finalisedBook.amountBurnedForBook, "");
orderBook.isFrozen = false;
market.lastFinalised = now;
emit LogOrderBookFinalised(vscContract, finalisedBook.amountBurnedForBook, finalisedBook.amountMintedForBook,
finalisedBook.winningPrice, finalisedBook.lastEntryHash, finalisedBook.lastEntryAmountBought,
finalisedBook.lastEntryTimestamp);
}
function getAddEntryToOrderBookParams(uint256 _sellAmount, uint256 _buyAmount)
onlyWhenBookIsNotFrozen
external
view
returns (bytes memory encodedOrderBookSaleParams_)
{
return LOrderBooks.getAddEntryToOrderBookParams(market, _sellAmount, _buyAmount);
}
function removeOrder(address _from, bytes32 _orderBookEntryHash)
proxyCheck(_from)
onlyWhenBookIsNotFrozen
external
{
uint256 amountToReturn = LOrderBooks.removeEntryFromOrderBook(market, _orderBookEntryHash, _from);
VOWToken(vowContract).send(_from, amountToReturn, "");
emit LogOrderBookEntryRemoved(vscContract, _from, _orderBookEntryHash, amountToReturn);
}
function completeOrder(address _from, bytes32 _orderBookEntryHash)
proxyCheck(_from)
onlyWhenBookIsNotFrozen
external
{
uint256 amountToReturn = LOrderBooks.completeEntryFromFinalisedBook(market, _orderBookEntryHash, _from);
VSCToken(vscContract).send(_from, amountToReturn, "");
emit LogOrderBookEntryCompleted(vscContract, _from, _orderBookEntryHash, amountToReturn);
}
function getVSCTokenManager()
private
view
returns (VSCTokenManager vscTokenManager_)
{
vscTokenManager_ = VSCTokenManager(VSCToken(vscContract).partnerContracts(VSC_TOKEN_MANAGER_KEY));
}
function addOrderBookEntry(address _from, uint256 _amount, bytes memory _params)
onlyWhenBookIsNotFrozen
private
{
bytes32 orderEntryHash = LOrderBooks.addEntryToOrderBook(market, _from, _amount,
_params);
emit LogOrderBookEntryAdded(vscContract, _from, _params, orderEntryHash);
}
} | Returns the address that signed a hashed message (`hash`) with `signature`. This address can then be used for verification purposes. The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: this function rejects them by requiring the `s` value to be in the lower half order, and the `v` value to be either 27 or 28. IMPORTANT: `hash` _must_ be the result of a hash operation for the verification to be secure: it is possible to craft signatures that recover to arbitrary addresses for non-hashed data. A safe way to ensure this is by receiving a hash of the original message (which may otherwise be too long), and then calling {toEthSignedMessageHash} on it./ Check the signature length ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. solhint-disable-next-line no-inline-assembly EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature unique. Appendix F in the Ethereum Yellow paper (https:ethereum.github.io/yellowpaper/paper.pdf), defines the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most signatures from current libraries generate a unique signature with an s-value in the lower half order. If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept these malleable signatures as well. | function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v < 27) v += 27;
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
| 1,986,048 |
/**
*Submitted for verification at Etherscan.io on 2020-11-17
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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);
constructor () internal {
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");
_;
}
}
abstract contract NKTContract {
function balanceOf(address account) external view virtual returns (uint256);
function transfer(address recipient, uint256 amount) external virtual returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external virtual returns (bool);
}
abstract contract NKTStoreContract {
function getStoreBalance() external virtual returns (uint256);
function giveReward(address recipient, uint256 amount) external virtual returns (bool);
function withdrawAll(address recipient) external virtual returns (bool);
}
contract NKTStaker is Ownable {
using SafeMath for uint256;
NKTContract private _mainTokenContract; // main token contract
NKTStoreContract private _storeWalletContract; // store wallet contract
mapping (address => uint256) private _stakedBalances; // map for stacked balances
mapping (address => uint256) private _rewards; // map for rewards
address private _devWallet; // dev wallet address
address[] private _stakers; // staker's array
uint256 private _totalStackedAmount = 0; // total stacked amount
uint256 private _minStakeAmount = 20e18; // min stackable amount
uint256 private _rewardPeriod = 3600; // seconds of a day
uint256 private _rewardPortion = 100; // reward portion = 1/100
uint256 private _rewardFee = 98; // reward fee 98%, rest for dev 2%
uint256 private _taxFee = 2; // tax fee for transaction
uint256 private _minRewardPeriod = 3600; // min reward period = 1 hour (3600s)
uint256 private _lastTimestamp; // last timestamp that distributed rewards
// Events
event Staked(address staker, uint256 amount);
event Unstaked(address staker, uint256 amount);
event Claim(address staker, uint256 amount);
constructor (NKTContract mainTokenContract, address devWallet) public {
_mainTokenContract = mainTokenContract;
_devWallet = devWallet;
}
function stake(uint256 amount) external {
require(
amount >= _minStakeAmount,
"Too small amount"
);
require(
_mainTokenContract.transferFrom(
_msgSender(),
address(this),
amount
),
"Stake failed"
);
uint256 taxAmount = amount.mul(_taxFee).div(100);
uint256 stackedAmount = amount.sub(taxAmount);
if(_stakers.length == 0)
_lastTimestamp = uint256(now);
if(_stakedBalances[_msgSender()] == 0)
_stakers.push(_msgSender());
_stakedBalances[_msgSender()] = _stakedBalances[_msgSender()].add(stackedAmount);
_totalStackedAmount = _totalStackedAmount.add(stackedAmount);
emit Staked(_msgSender(), stackedAmount);
}
function unstake(uint256 amount) external {
require(
_stakedBalances[_msgSender()] >= amount,
"Unstake amount exceededs the staked amount."
);
require(
_mainTokenContract.transfer(
_msgSender(),
amount
),
"Unstake failed"
);
_stakedBalances[_msgSender()] = _stakedBalances[_msgSender()].sub(amount);
_totalStackedAmount = _totalStackedAmount.sub(amount);
if(_stakedBalances[_msgSender()] == 0) {
for(uint i=0; i<_stakers.length; i++) {
if(_stakers[i] == _msgSender()) {
_stakers[i] = _stakers[_stakers.length-1];
_stakers.pop();
break;
}
}
}
emit Unstaked(_msgSender(), amount);
uint256 rewardsAmount = _rewards[_msgSender()];
if(rewardsAmount > 0) {
require(
_storeWalletContract.giveReward(_msgSender(), rewardsAmount),
"Claim failed."
);
_rewards[_msgSender()] = 0;
emit Claim(_msgSender(), rewardsAmount);
}
}
function claim(uint256 amount) external {
require(
_rewards[_msgSender()] >= amount,
"Claim amount exceededs the pendnig rewards."
);
require(
_storeWalletContract.giveReward(_msgSender(), amount),
"Claim failed."
);
_rewards[_msgSender()] = _rewards[_msgSender()].sub(amount);
emit Claim(_msgSender(), amount);
}
function endStake() external {
uint256 rewardsAmount = _rewards[_msgSender()];
if(rewardsAmount > 0) {
require(
_storeWalletContract.giveReward(_msgSender(), rewardsAmount),
"Claim failed."
);
_rewards[_msgSender()] = 0;
emit Claim(_msgSender(), rewardsAmount);
}
uint256 unstakeAmount = _stakedBalances[_msgSender()];
if(unstakeAmount > 0) {
require(
_mainTokenContract.transfer(
_msgSender(),
unstakeAmount
),
"Unstake failed"
);
_stakedBalances[_msgSender()] = 0;
_totalStackedAmount = _totalStackedAmount.sub(unstakeAmount);
for(uint i=0; i<_stakers.length; i++) {
if(_stakers[i] == _msgSender()) {
_stakers[i] = _stakers[_stakers.length-1];
_stakers.pop();
break;
}
}
emit Unstaked(_msgSender(), unstakeAmount);
}
}
function calcRewards() external {
uint256 currentTimestamp = uint256(now);
uint256 diff = currentTimestamp.sub(_lastTimestamp);
if(diff >= _rewardPeriod) {
uint256 rewardDays = diff.div(_rewardPeriod);
uint256 offsetTimestamp = diff.sub(_rewardPeriod.mul(rewardDays));
uint256 _storeBalance = _storeWalletContract.getStoreBalance();
for(uint j=0; j<rewardDays; j++) {
uint256 _totalRewardsAmount = _storeBalance.div(_rewardPortion);
if(_totalRewardsAmount > 0) {
uint256 _rewardForStaker = _totalRewardsAmount.mul(_rewardFee).div(100);
uint256 _rewardForDev = _totalRewardsAmount.sub(_rewardForStaker);
for(uint i=0; i<_stakers.length; i++) {
if(_stakers[i] != address(0)) {
_rewards[_stakers[i]] = _rewards[_stakers[i]].add(_stakedBalances[_stakers[i]].mul(_rewardForStaker).div(_totalStackedAmount));
}
}
if(_rewardForDev > 0)
_storeWalletContract.giveReward(_devWallet, _rewardForDev);
}
_storeBalance = _storeBalance.sub(_totalRewardsAmount);
}
_lastTimestamp = currentTimestamp.sub(offsetTimestamp);
}
}
function withdrawAllFromStore(address recipient) external onlyOwner returns (bool) {
require(
recipient != address(0) && recipient != address(this),
"Should be valid address."
);
_storeWalletContract.withdrawAll(recipient);
}
/**
* Get store wallet
*/
function getStoreWalletContract() external view returns (address) {
return address(_storeWalletContract);
}
/**
* Get total stacked amount
*/
function getTotalStackedAmount() external view returns (uint256) {
return _totalStackedAmount;
}
/**
* Get reward amount of staker
*/
function getRewardOfAccount(address staker) external view returns (uint256) {
return _rewards[staker];
}
/**
* Get stacked amount of staker
*/
function getStakeAmountOfAccount(address staker) external view returns (uint256) {
return _stakedBalances[staker];
}
/**
* Get min stake amount
*/
function getMinStakeAmount() external view returns (uint256) {
return _minStakeAmount;
}
/**
* Get rewards period
*/
function getRewardPeriod() external view returns (uint256) {
return _rewardPeriod;
}
/**
* Get rewards portion
*/
function getRewardPortion() external view returns (uint256) {
return _rewardPortion;
}
/**
* Get last timestamp that countdown for rewards started
*/
function getLastTimestamp() external view returns (uint256) {
return _lastTimestamp;
}
/**
* Get staker count
*/
function getStakerCount() external view returns (uint256) {
return _stakers.length;
}
/**
* Get rewards fee
*/
function getRewardFee() external view returns (uint256) {
return _rewardFee;
}
/**
* Set store wallet contract address
*/
function setStoreWalletContract(NKTStoreContract storeWalletContract) external onlyOwner returns (bool) {
require(address(storeWalletContract) != address(0), 'store wallet contract should not be zero address.');
_storeWalletContract = storeWalletContract;
return true;
}
/**
* Set reward period
*/
function setRewardPeriod(uint256 rewardPeriod) external onlyOwner returns (bool) {
require(rewardPeriod >= _minRewardPeriod, 'reward period should be above min reward period.');
_rewardPeriod = rewardPeriod;
return true;
}
/**
* Set rewards portion in store balance.
* ex: 1000 => rewardsAmount of one period equals storeAmount.div(1000)
*/
function setRewardPortion(uint256 rewardPortion) external onlyOwner returns (bool) {
require(rewardPortion >= 1, 'reward portion should be above 1');
_rewardPortion = rewardPortion;
return true;
}
/**
* Set rewards portion for stakers in rewards amount.
* ex: 98 => 98% (2% for dev)
*/
function setRewardFee(uint256 rewardFee) external onlyOwner returns (bool) {
require(rewardFee >= 96 && rewardFee <= 100, 'reward fee should be in 96 ~ 100' );
_rewardFee = rewardFee;
_taxFee = uint256(100).sub(_rewardFee);
return true;
}
} | Set reward period/ | function setRewardPeriod(uint256 rewardPeriod) external onlyOwner returns (bool) {
require(rewardPeriod >= _minRewardPeriod, 'reward period should be above min reward period.');
_rewardPeriod = rewardPeriod;
return true;
}
| 2,093,056 |
./partial_match/42/0x85B362211394C55bef04AE6cCC3F61971B91F053/sources/FarmProRata.sol | uint lastTurboUpdate var globale | function turboUpdate() private onlyOwner {
uint timeDiff;
uint _now = now;
uint rewardsAmount;
uint amountperLp = rewardsAmount.mul(pointMultiplier).div(totalTokens);
totalDivPoints = totalDivPoints.add(amountperLp);
lastTurboUpdate = now;
}
| 8,945,497 |
pragma solidity ^0.4.11;
contract SimpleAuction {
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
address public beneficiary;
uint public auctionStart;
uint public biddingTime;
// Current state of the auction.
address public highestBidder;
uint public highestBid;
// Allowed withdrawals of previous bids
mapping(address => uint) pendingReturns;
// Set to true at the end, disallows any change
bool ended;
// Events that will be fired on changes.
event HighestBidIncreased(address bidder, uint amount);
event AuctionEnded(address winner, uint amount);
// The following is a so-called natspec comment,
// recognizable by the three slashes.
// It will be shown when the user is asked to
// confirm a transaction.
/// Create a simple auction with `_biddingTime`
/// seconds bidding time on behalf of the
/// beneficiary address `_beneficiary`.
function SimpleAuction() {
beneficiary = 0x7Ef6fA8683491521223Af5A69b923E771fF2e73A;
auctionStart = now;
biddingTime = 7 days;
}
/// Bid on the auction with the value sent
/// together with this transaction.
/// The value will only be refunded if the
/// auction is not won.
function bid() payable {
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
// Revert the call if the bidding
// period is over.
require(now <= (auctionStart + biddingTime));
// If the bid is not higher, send the
// money back.
require(msg.value > highestBid);
if (highestBidder != 0) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it could execute an untrusted contract.
// It is always safer to let the recipients
// withdraw their money themselves.
pendingReturns[highestBidder] += highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
HighestBidIncreased(msg.sender, msg.value);
}
/// Withdraw a bid that was overbid.
function withdraw() returns (bool) {
uint amount = pendingReturns[msg.sender];
if (amount > 0) {
// It is important to set this to zero because the recipient
// can call this function again as part of the receiving call
// before `send` returns.
pendingReturns[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// No need to call throw here, just reset the amount owing
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
/// End the auction and send the highest bid
/// to the beneficiary.
function auctionEnd() {
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
// 1. Conditions
require(now >= (auctionStart + biddingTime)); // auction did not yet end
require(!ended); // this function has already been called
// 2. Effects
ended = true;
AuctionEnded(highestBidder, highestBid);
// 3. Interaction
beneficiary.transfer(highestBid);
}
} | Create a simple auction with `_biddingTime` seconds bidding time on behalf of the beneficiary address `_beneficiary`. | function SimpleAuction() {
beneficiary = 0x7Ef6fA8683491521223Af5A69b923E771fF2e73A;
auctionStart = now;
biddingTime = 7 days;
}
| 15,077,740 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20Snapshot.sol";
contract Myobu is ERC20Snapshot {
address public override DAO; // solhint-disable-line
address public override myobuSwap;
bool private antiLiqBot;
constructor(address payable addr1) MyobuBase(addr1) {
setFees(Fees(10, 10, 10, 10));
}
modifier onlySupportedPair(address pair) {
require(taxedPair(pair), "Pair is not supported");
_;
}
modifier onlyMyobuswapOnAntiLiq() {
require(!antiLiqBot || _msgSender() == myobuSwap, "Use MyobuSwap");
_;
}
modifier checkDeadline(uint256 deadline) {
require(block.timestamp <= deadline, "Transaction expired");
_;
}
function setDAO(address newDAO) external onlyOwner {
DAO = newDAO;
emit DAOChanged(newDAO);
}
function setMyobuSwap(address newMyobuSwap) external onlyOwner {
myobuSwap = newMyobuSwap;
emit MyobuSwapChanged(newMyobuSwap);
}
function snapshot() external returns (uint256) {
require(_msgSender() == owner() || _msgSender() == DAO);
return _snapshot();
}
function setAntiLiqBot(bool setTo) external virtual onlyOwner {
antiLiqBot = setTo;
}
function noFeeAddLiquidityETH(LiquidityETHParams calldata params)
external
payable
override
onlySupportedPair(params.pair)
checkDeadline(params.deadline)
onlyMyobuswapOnAntiLiq
lockTheSwap
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
_transfer(_msgSender(), address(this), params.amountTokenOrLP);
uint256 beforeBalance = address(this).balance - msg.value;
(amountToken, amountETH, liquidity) = IUniswapV2Router(
_routerFor[params.pair]
).addLiquidityETH{value: msg.value}(
address(this),
params.amountTokenOrLP,
params.amountTokenMin,
params.amountETHMin,
params.to,
block.timestamp
);
// router refunds to this address, refund all back to sender
if (address(this).balance > beforeBalance) {
payable(_msgSender()).transfer(
address(this).balance - beforeBalance
);
}
emit LiquidityAddedETH(params.pair, amountToken, amountETH, liquidity);
}
function noFeeRemoveLiquidityETH(LiquidityETHParams calldata params)
external
override
onlySupportedPair(params.pair)
checkDeadline(params.deadline)
lockTheSwap
returns (uint256 amountToken, uint256 amountETH)
{
MyobuLib.transferTokens(
params.pair,
_msgSender(),
address(this),
params.amountTokenOrLP
);
(amountToken, amountETH) = IUniswapV2Router(_routerFor[params.pair])
.removeLiquidityETH(
address(this),
params.amountTokenOrLP,
params.amountTokenMin,
params.amountETHMin,
params.to,
block.timestamp
);
emit LiquidityRemovedETH(
params.pair,
amountToken,
amountETH,
params.amountTokenOrLP
);
}
function noFeeAddLiquidity(AddLiquidityParams calldata params)
external
override
onlySupportedPair(params.pair)
checkDeadline(params.deadline)
onlyMyobuswapOnAntiLiq
lockTheSwap
returns (
uint256 amountMyobu,
uint256 amountToken,
uint256 liquidity
)
{
address token = MyobuLib.tokenFor(params.pair);
uint256 beforeBalance = IERC20(token).balanceOf(address(this));
_transfer(_msgSender(), address(this), params.amountToken);
MyobuLib.transferTokens(
token,
_msgSender(),
address(this),
params.amountTokenB
);
(amountToken, amountMyobu, liquidity) = IUniswapV2Router(
_routerFor[params.pair]
).addLiquidity(
token,
address(this),
params.amountTokenB,
params.amountToken,
params.amountTokenBMin,
params.amountTokenMin,
params.to,
block.timestamp
);
// router refunds to this address, refund all back to sender
uint256 currentBalance = IERC20(token).balanceOf(address(this));
if (currentBalance > beforeBalance) {
IERC20(token).transfer(
_msgSender(),
currentBalance - beforeBalance
);
}
emit LiquidityAdded(params.pair, amountMyobu, amountToken, liquidity);
}
function noFeeRemoveLiquidity(RemoveLiquidityParams calldata params)
external
override
onlySupportedPair(params.pair)
checkDeadline(params.deadline)
lockTheSwap
returns (uint256 amountMyobu, uint256 amountToken)
{
MyobuLib.transferTokens(
params.pair,
_msgSender(),
address(this),
params.amountLP
);
(amountToken, amountMyobu) = IUniswapV2Router(_routerFor[params.pair])
.removeLiquidity(
MyobuLib.tokenFor(params.pair),
address(this),
params.amountLP,
params.amountTokenBMin,
params.amountTokenMin,
params.to,
block.timestamp
);
emit LiquidityRemoved(
params.pair,
amountMyobu,
amountToken,
params.amountLP
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Utils/Arrays.sol";
import "./Utils/Counters.sol";
import "./MyobuBase.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it
* return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this
* function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
*
* Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
* alternative consider {ERC20Votes}.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is MyobuBase {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping(address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = getCurrentSnapshotId();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Get the current snapshotId
*/
function getCurrentSnapshotId() public view virtual returns (uint256) {
return _currentSnapshotId.current();
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId)
public
view
virtual
returns (uint256)
{
(bool snapshotted, uint256 value) = _valueAt(
snapshotId,
_accountBalanceSnapshots[account]
);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId)
public
view
virtual
returns (uint256)
{
(bool snapshotted, uint256 value) = _valueAt(
snapshotId,
_totalSupplySnapshots
);
return snapshotted ? value : totalSupply();
}
// Update balance and/or total supply snapshots before the values are modified. This is implemented
// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// mint
_updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
// burn
_updateAccountSnapshot(from);
_updateTotalSupplySnapshot();
} else {
// transfer
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
}
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private
view
returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
require(
snapshotId <= getCurrentSnapshotId(),
"ERC20Snapshot: nonexistent id"
);
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue)
private
{
uint256 currentId = getCurrentSnapshotId();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids)
private
view
returns (uint256)
{
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "./Utils/MyobuLib.sol";
import "./Utils/Ownable.sol";
import "./Interfaces/IUniswapV2Router.sol";
import "./Interfaces/IUniswapV2Factory.sol";
import "./Interfaces/IUniswapV2Pair.sol";
import "./Interfaces/IMyobu.sol";
abstract contract MyobuBase is IMyobu, Ownable, ERC20 {
uint256 internal constant MAX = type(uint256).max;
uint256 private constant SUPPLY = 1000000000000 * 10**9;
string internal constant NAME = unicode"Myōbu";
string internal constant SYMBOL = "MYOBU";
uint8 internal constant DECIMALS = 9;
// pair => router
mapping(address => address) internal _routerFor;
mapping(address => bool) private taxedTransfer;
Fees private fees;
address payable internal _taxAddress;
IUniswapV2Router internal uniswapV2Router;
address internal uniswapV2Pair;
bool private tradingOpen;
bool private liquidityAdded;
bool private inSwap;
bool private swapEnabled;
modifier lockTheSwap() {
inSwap = true;
_;
inSwap = false;
}
constructor(address payable addr1) ERC20(NAME, SYMBOL) {
_taxAddress = addr1;
_mint(_msgSender(), SUPPLY);
}
function decimals() public pure virtual override returns (uint8) {
return DECIMALS;
}
function taxedPair(address pair)
public
view
virtual
override
returns (bool)
{
return _routerFor[pair] != address(0);
}
// Transfer tokens without emmiting events from an address to this address, used for taking fees
function transferFee(address from, uint256 amount) internal {
_balances[from] -= amount;
_balances[address(this)] += amount;
}
function takeFee(
address from,
uint256 amount,
uint256 teamFee
) internal returns (uint256) {
if (teamFee == 0) return 0;
uint256 tTeam = MyobuLib.percentageOf(amount, teamFee);
transferFee(from, tTeam);
emit FeesTaken(tTeam);
return tTeam;
}
function _transfer(
address from,
address to,
uint256 amount
) internal virtual override {
// If no fee, it is 0 which will take no fee
uint256 _teamFee;
if (from != owner() && to != owner()) {
if (swapEnabled && !inSwap) {
if (taxedPair(from) && !taxedPair(to)) {
require(tradingOpen);
_teamFee = fees.buyFee;
} else if (taxedTransfer[from] || taxedTransfer[to]) {
_teamFee = fees.transferFee;
} else if (taxedPair(to)) {
require(tradingOpen);
require(amount <= (balanceOf(to) * fees.impact) / 100);
swapTokensForEth(balanceOf(address(this)));
sendETHToFee(address(this).balance);
_teamFee = fees.sellFee;
}
}
}
uint256 fee = takeFee(from, amount, _teamFee);
super._transfer(from, to, amount - fee);
}
function swapTokensForEth(uint256 tokenAmount) internal lockTheSwap {
MyobuLib.swapForETH(uniswapV2Router, tokenAmount, address(this));
}
function sendETHToFee(uint256 amount) internal {
_taxAddress.transfer(amount);
}
function openTrading() external virtual onlyOwner {
require(liquidityAdded);
tradingOpen = true;
}
function addDEX(address pair, address router) public virtual onlyOwner {
require(!taxedPair(pair), "DEX already exists");
address tokenFor = MyobuLib.tokenFor(pair);
_routerFor[pair] = router;
_approve(address(this), router, MAX);
IERC20(tokenFor).approve(router, MAX);
IERC20(pair).approve(router, MAX);
}
function removeDEX(address pair) external virtual onlyOwner {
require(taxedPair(pair), "DEX does not exist");
address tokenFor = MyobuLib.tokenFor(pair);
address router = _routerFor[pair];
delete _routerFor[pair];
_approve(address(this), router, 0);
IERC20(tokenFor).approve(router, 0);
IERC20(pair).approve(router, 0);
}
function addLiquidity() external virtual onlyOwner lockTheSwap {
IUniswapV2Router _uniswapV2Router = IUniswapV2Router(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
addDEX(uniswapV2Pair, address(_uniswapV2Router));
MyobuLib.addLiquidityETH(
uniswapV2Router,
balanceOf(address(this)),
address(this).balance,
owner()
);
liquidityAdded = true;
}
function setTaxAddress(address payable newTaxAddress) external onlyOwner {
_taxAddress = newTaxAddress;
emit TaxAddressChanged(newTaxAddress);
}
function setTaxedTransferFor(address[] calldata taxedTransfer_)
external
virtual
onlyOwner
{
for (uint256 i; i < taxedTransfer_.length; i++) {
taxedTransfer[taxedTransfer_[i]] = true;
}
emit TaxedTransferAddedFor(taxedTransfer_);
}
function removeTaxedTransferFor(address[] calldata notTaxed)
external
virtual
onlyOwner
{
for (uint256 i; i < notTaxed.length; i++) {
taxedTransfer[notTaxed[i]] = false;
}
emit TaxedTransferRemovedFor(notTaxed);
}
function manualswap() external onlyOwner {
swapTokensForEth(balanceOf(address(this)));
}
function manualsend() external onlyOwner {
sendETHToFee(address(this).balance);
}
function setSwapRouter(IUniswapV2Router newRouter) external onlyOwner {
require(liquidityAdded, "Add liquidity before doing this");
address weth = uniswapV2Router.WETH();
address newPair = IUniswapV2Factory(newRouter.factory()).getPair(
address(this),
weth
);
require(
newPair != address(0),
"WETH Pair does not exist for that router"
);
require(taxedPair(newPair), "The pair must be a taxed pair");
(uint256 reservesOld, , ) = IUniswapV2Pair(uniswapV2Pair).getReserves();
(uint256 reservesNew, , ) = IUniswapV2Pair(newPair).getReserves();
require(
reservesNew > reservesOld,
"New pair must have more WETH Reserves"
);
uniswapV2Router = newRouter;
uniswapV2Pair = newPair;
}
function setFees(Fees memory newFees) public onlyOwner {
require(
newFees.impact != 0 && newFees.impact <= 100,
"Impact must be greater than 0 and under or equal to 100"
);
require(
newFees.buyFee < 15 &&
newFees.sellFee < 15 &&
newFees.transferFee <= newFees.sellFee,
"Fees for a buy / sell must be under 15"
);
fees = newFees;
if (newFees.buyFee + newFees.sellFee == 0) {
swapEnabled = false;
} else {
swapEnabled = true;
}
emit FeesChanged(newFees);
}
function currentFees() external view override returns (Fees memory) {
return fees;
}
// solhint-disable-next-line
receive() external payable virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element)
internal
view
returns (uint256)
{
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
interface IMyobu is IERC20 {
event DAOChanged(address newDAOContract);
event MyobuSwapChanged(address newMyobuSwap);
function DAO() external view returns (address); // solhint-disable-line
function myobuSwap() external view returns (address);
event TaxAddressChanged(address newTaxAddress);
event TaxedTransferAddedFor(address[] addresses);
event TaxedTransferRemovedFor(address[] addresses);
event FeesTaken(uint256 teamFee);
event FeesChanged(Fees newFees);
struct Fees {
uint256 impact;
uint256 buyFee;
uint256 sellFee;
uint256 transferFee;
}
function currentFees() external view returns (Fees memory);
struct LiquidityETHParams {
address pair;
address to;
uint256 amountTokenOrLP;
uint256 amountTokenMin;
uint256 amountETHMin;
uint256 deadline;
}
event LiquidityAddedETH(
address pair,
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function noFeeAddLiquidityETH(LiquidityETHParams calldata params)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
event LiquidityRemovedETH(
address pair,
uint256 amountToken,
uint256 amountETH,
uint256 amountRemoved
);
function noFeeRemoveLiquidityETH(LiquidityETHParams calldata params)
external
returns (uint256 amountToken, uint256 amountETH);
struct AddLiquidityParams {
address pair;
address to;
uint256 amountToken;
uint256 amountTokenB;
uint256 amountTokenMin;
uint256 amountTokenBMin;
uint256 deadline;
}
event LiquidityAdded(
address pair,
uint256 amountMyobu,
uint256 amountToken,
uint256 liquidity
);
function noFeeAddLiquidity(AddLiquidityParams calldata params)
external
returns (
uint256 amountMyobu,
uint256 amountToken,
uint256 liquidity
);
struct RemoveLiquidityParams {
address pair;
address to;
uint256 amountLP;
uint256 amountTokenMin;
uint256 amountTokenBMin;
uint256 deadline;
}
event LiquidityRemoved(
address pair,
uint256 amountMyobu,
uint256 amountToken,
uint256 liquidity
);
function noFeeRemoveLiquidity(RemoveLiquidityParams calldata params)
external
returns (uint256 amountMyobu, uint256 amountToken);
function taxedPair(address pair) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 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.8.0;
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
// solhint-disable-next-line
function WETH() external pure returns (address);
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 removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapV2Router is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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() external 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) external 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: MIT
pragma solidity ^0.8.0;
import "../Interfaces/IUniswapV2Router.sol";
import "../Interfaces/IUniswapV2Pair.sol";
import "../Interfaces/IERC20.sol";
library MyobuLib {
/**
* @dev Calculates the percentage of a number
* @param number: The number to calculate the percentage of
* @param percentage: The percentage of the number to return
* @return The percentage of a number
*/
function percentageOf(uint256 number, uint256 percentage)
internal
pure
returns (uint256)
{
return (number * percentage) / 100;
}
/**
* @dev Swaps an amount of tokens for ETH
* @param uniswapV2Router: The uniswap router to trade through
* @param amount: The amount of tokens to swap
* @param to: The address to send the recieved tokens to
* @return The amount of ETH recieved
*/
function swapForETH(
IUniswapV2Router uniswapV2Router,
uint256 amount,
address to
) internal returns (uint256) {
uint256 startingBalance = to.balance;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
to,
block.timestamp
);
return to.balance - startingBalance;
}
/**
* @dev Adds liquidity for the token in ETH
* @param uniswapV2Router: The uniswap router to add liquidity through
* @param amountToken: The amount of tokens to add liquidity with
* @param amountETH: The amount of ETH to add liquidity with
* @param to: The address to send the recieved LP tokens to
*/
function addLiquidityETH(
IUniswapV2Router uniswapV2Router,
uint256 amountToken,
uint256 amountETH,
address to
) internal {
uniswapV2Router.addLiquidityETH{value: amountETH}(
address(this),
amountToken,
0,
0,
to,
block.timestamp
);
}
/**
* @param token: The address of the token to transfer
* @param from: The sender of the tokens
* @param to: The receiver of the tokens
* @param amount: The amount of tokens to transfer
*/
function transferTokens(
address token,
address from,
address to,
uint256 amount
) internal {
IERC20(token).transferFrom(from, to, amount);
}
/**
* @dev Returns the token for a Uniswap V2 Pair
*/
function tokenFor(address pair) internal view returns (address) {
return IUniswapV2Pair(pair).token0();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Interfaces/IERC20.sol";
import "./Interfaces/IERC20Metadata.sol";
import "./Utils/Context.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 Contracts guidelines: functions revert
* instead 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) internal _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 default 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"
);
unchecked {
_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"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This 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"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 {} // solhint-disable-line
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {} // solhint-disable-line
}
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
/**
* @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);
}
| Creates a new snapshot and returns its snapshot id. Emits a {Snapshot} event that contains the same id. {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a set of accounts, for example using {AccessControl}, or it may be open to the public. [WARNING] ==== While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, you must consider that it can potentially be used by attackers in two ways. First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs section above. We haven't measured the actual numbers; if this is something you're interested in please reach out to us. ====/ | function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = getCurrentSnapshotId();
emit Snapshot(currentId);
return currentId;
}
| 9,932,061 |
pragma solidity 0.4.20;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed burner, uint256 value);
}
// ----------------------------------------------------------------------------
// VIOLET ERC20 Standard Token
// ----------------------------------------------------------------------------
contract VLTToken is ERC20Interface {
using SafeMath for uint256;
address public owner = msg.sender;
bytes32 public symbol;
bytes32 public name;
uint8 public decimals;
uint256 public _totalSupply;
mapping(address => uint256) internal balances;
mapping(address => mapping (address => uint256)) internal allowed;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function VLTToken() public {
symbol = "VAI";
name = "VIOLET";
decimals = 18;
_totalSupply = 250000000 * 10**uint256(decimals);
balances[owner] = _totalSupply;
Transfer(address(0), owner, _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 the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @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) {
// allow sending 0 tokens
if (_value == 0) {
Transfer(msg.sender, _to, _value); // Follow the spec to louch the event when transfer 0
return;
}
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev 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) {
// allow sending 0 tokens
if (_value == 0) {
Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0
return;
}
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
_totalSupply = _totalSupply.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
/**
* Destroy tokens from other account
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool) {
require(_value <= balances[_from]); // Check if the targeted balance is enough
require(_value <= allowed[_from][msg.sender]); // Check allowed allowance
balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance
_totalSupply = _totalSupply.sub(_value); // Update totalSupply
Burn(_from, _value);
Transfer(_from, address(0), _value);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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.
*/
function Ownable() 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) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ViolaCrowdsale
* @dev ViolaCrowdsale reserves token from supply when eth is received
* funds will be forwarded after the end of crowdsale. Tokens will be claimable
* within 7 days after crowdsale ends.
*/
contract ViolaCrowdsale is Ownable {
using SafeMath for uint256;
enum State { Deployed, PendingStart, Active, Paused, Ended, Completed }
//Status of contract
State public status = State.Deployed;
// The token being sold
VLTToken public violaToken;
//For keeping track of whitelist address. cap >0 = whitelisted
mapping(address=>uint) public maxBuyCap;
//For checking if address passed KYC
mapping(address => bool)public addressKYC;
//Total wei sum an address has invested
mapping(address=>uint) public investedSum;
//Total violaToken an address is allocated
mapping(address=>uint) public tokensAllocated;
//Total violaToken an address purchased externally is allocated
mapping(address=>uint) public externalTokensAllocated;
//Total bonus violaToken an address is entitled after vesting
mapping(address=>uint) public bonusTokensAllocated;
//Total bonus violaToken an address purchased externally is entitled after vesting
mapping(address=>uint) public externalBonusTokensAllocated;
//Store addresses that has registered for crowdsale before (pushed via setWhitelist)
//Does not mean whitelisted as it can be revoked. Just to track address for loop
address[] public registeredAddress;
//Total amount not approved for withdrawal
uint256 public totalApprovedAmount = 0;
//Start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
uint256 public bonusVestingPeriod = 60 days;
/**
* Note all values are calculated in wei(uint256) including token amount
* 1 ether = 1000000000000000000 wei
* 1 viola = 1000000000000000000 vi lawei
*/
//Address where funds are collected
address public wallet;
//Min amount investor can purchase
uint256 public minWeiToPurchase;
// how many token units *in wei* a buyer gets *per wei*
uint256 public rate;
//Extra bonus token to give *in percentage*
uint public bonusTokenRateLevelOne = 20;
uint public bonusTokenRateLevelTwo = 15;
uint public bonusTokenRateLevelThree = 10;
uint public bonusTokenRateLevelFour = 0;
//Total amount of tokens allocated for crowdsale
uint256 public totalTokensAllocated;
//Total amount of tokens reserved from external sources
//Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether )
uint256 public totalReservedTokenAllocated;
//Numbers of token left above 0 to still be considered sold
uint256 public leftoverTokensBuffer;
/**
* event for front end logging
*/
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount);
event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount);
event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount);
event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount);
event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount);
event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount);
event CrowdsalePending();
event CrowdsaleStarted();
event CrowdsaleEnded();
event BonusRateChanged();
event Refunded(address indexed beneficiary, uint256 weiAmount);
//Set inital arguments of the crowdsale
function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external {
require(status == State.Deployed);
require(_startTime >= now);
require(_rate > 0);
require(address(_tokenAddress) != address(0));
require(_wallet != address(0));
startTime = _startTime;
endTime = _startTime + 30 days;
rate = _rate;
wallet = _wallet;
violaToken = VLTToken(_tokenAddress);
status = State.PendingStart;
CrowdsalePending();
}
/**
* Crowdsale state functions
* To track state of current crowdsale
*/
// To be called by Ethereum alarm clock or anyone
//Can only be called successfully when time is valid
function startCrowdsale() external {
require(withinPeriod());
require(violaToken != address(0));
require(getTokensLeft() > 0);
require(status == State.PendingStart);
status = State.Active;
CrowdsaleStarted();
}
//To be called by owner or contract
//Ends the crowdsale when tokens are sold out
function endCrowdsale() public {
if (!tokensHasSoldOut()) {
require(msg.sender == owner);
}
require(status == State.Active);
bonusVestingPeriod = now + 60 days;
status = State.Ended;
CrowdsaleEnded();
}
//Emergency pause
function pauseCrowdsale() onlyOwner external {
require(status == State.Active);
status = State.Paused;
}
//Resume paused crowdsale
function unpauseCrowdsale() onlyOwner external {
require(status == State.Paused);
status = State.Active;
}
function completeCrowdsale() onlyOwner external {
require(hasEnded());
require(violaToken.allowance(owner, this) == 0);
status = State.Completed;
_forwardFunds();
assert(this.balance == 0);
}
function burnExtraTokens() onlyOwner external {
require(hasEnded());
uint256 extraTokensToBurn = violaToken.allowance(owner, this);
violaToken.burnFrom(owner, extraTokensToBurn);
assert(violaToken.allowance(owner, this) == 0);
}
// send ether to the fund collection wallet
function _forwardFunds() internal {
wallet.transfer(this.balance);
}
function partialForwardFunds(uint _amountToTransfer) onlyOwner external {
require(status == State.Ended);
require(_amountToTransfer < totalApprovedAmount);
totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer);
wallet.transfer(_amountToTransfer);
}
/**
* Setter functions for crowdsale parameters
* Only owner can set values
*/
function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external {
require(_tokenBuffer > 0);
require(getTokensLeft() >= _tokenBuffer);
leftoverTokensBuffer = _tokenBuffer;
}
//Set the ether to token rate
function setRate(uint _rate) onlyOwner external {
require(_rate > 0);
rate = _rate;
}
function setBonusTokenRateLevelOne(uint _rate) onlyOwner external {
//require(_rate > 0);
bonusTokenRateLevelOne = _rate;
BonusRateChanged();
}
function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external {
//require(_rate > 0);
bonusTokenRateLevelTwo = _rate;
BonusRateChanged();
}
function setBonusTokenRateLevelThree(uint _rate) onlyOwner external {
//require(_rate > 0);
bonusTokenRateLevelThree = _rate;
BonusRateChanged();
}
function setBonusTokenRateLevelFour(uint _rate) onlyOwner external {
//require(_rate > 0);
bonusTokenRateLevelFour = _rate;
BonusRateChanged();
}
function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external {
minWeiToPurchase = _minWeiToPurchase;
}
/**
* Whitelisting and KYC functions
* Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC
*/
//Set the amount of wei an address can purchase up to
//@dev Value of 0 = not whitelisted
//@dev cap is in *18 decimals* ( 1 token = 1*10^18)
function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external {
require(_cap > 0);
require(_investor != address(0));
maxBuyCap[_investor] = _cap;
registeredAddress.push(_investor);
//add event
}
//Remove the address from whitelist
function removeWhitelistAddress(address _investor) onlyOwner external {
require(_investor != address(0));
maxBuyCap[_investor] = 0;
uint256 weiAmount = investedSum[_investor];
if (weiAmount > 0) {
_refund(_investor);
}
}
//Flag address as KYC approved. Address is now approved to claim tokens
function approveKYC(address _kycAddress) onlyOwner external {
require(_kycAddress != address(0));
addressKYC[_kycAddress] = true;
uint256 weiAmount = investedSum[_kycAddress];
totalApprovedAmount = totalApprovedAmount.add(weiAmount);
}
//Set KYC status as failed. Refund any eth back to address
function revokeKYC(address _kycAddress) onlyOwner external {
require(_kycAddress != address(0));
addressKYC[_kycAddress] = false;
uint256 weiAmount = investedSum[_kycAddress];
totalApprovedAmount = totalApprovedAmount.sub(weiAmount);
if (weiAmount > 0) {
_refund(_kycAddress);
}
}
/**
* Getter functions for crowdsale parameters
* Does not use gas
*/
//Checks if token has been sold out
function tokensHasSoldOut() view internal returns (bool) {
if (getTokensLeft() <= leftoverTokensBuffer) {
return true;
} else {
return false;
}
}
// @return true if the transaction can buy tokens
function withinPeriod() public view returns (bool) {
return now >= startTime && now <= endTime;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
if (status == State.Ended) {
return true;
}
return now > endTime;
}
function getTokensLeft() public view returns (uint) {
return violaToken.allowance(owner, this).sub(totalTokensAllocated);
}
function transferTokens (address receiver, uint tokenAmount) internal {
require(violaToken.transferFrom(owner, receiver, tokenAmount));
}
function getTimeBasedBonusRate() public view returns(uint) {
bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr
bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr
bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day
bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards
if (bonusDuration1) {
return bonusTokenRateLevelOne;
} else if (bonusDuration2) {
return bonusTokenRateLevelTwo;
} else if (bonusDuration3) {
return bonusTokenRateLevelThree;
} else if (bonusDuration4) {
return bonusTokenRateLevelFour;
} else {
return 0;
}
}
function getTotalTokensByAddress(address _investor) public view returns(uint) {
return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor));
}
function getTotalNormalTokensByAddress(address _investor) public view returns(uint) {
return tokensAllocated[_investor].add(externalTokensAllocated[_investor]);
}
function getTotalBonusTokensByAddress(address _investor) public view returns(uint) {
return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]);
}
function _clearTotalNormalTokensByAddress(address _investor) internal {
tokensAllocated[_investor] = 0;
externalTokensAllocated[_investor] = 0;
}
function _clearTotalBonusTokensByAddress(address _investor) internal {
bonusTokensAllocated[_investor] = 0;
externalBonusTokensAllocated[_investor] = 0;
}
/**
* Functions to handle buy tokens
* Fallback function as entry point for eth
*/
// Called when ether is sent to contract
function () external payable {
buyTokens(msg.sender);
}
//Used to buy tokens
function buyTokens(address investor) internal {
require(status == State.Active);
require(msg.value >= minWeiToPurchase);
uint weiAmount = msg.value;
checkCapAndRecord(investor,weiAmount);
allocateToken(investor,weiAmount);
}
//Internal call to check max user cap
function checkCapAndRecord(address investor, uint weiAmount) internal {
uint remaindingCap = maxBuyCap[investor];
require(remaindingCap >= weiAmount);
maxBuyCap[investor] = remaindingCap.sub(weiAmount);
investedSum[investor] = investedSum[investor].add(weiAmount);
}
//Internal call to allocated tokens purchased
function allocateToken(address investor, uint weiAmount) internal {
// calculate token amount to be created
uint tokens = weiAmount.mul(rate);
uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100);
uint tokensToAllocate = tokens.add(bonusTokens);
require(getTokensLeft() >= tokensToAllocate);
totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate);
tokensAllocated[investor] = tokensAllocated[investor].add(tokens);
bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens);
if (tokensHasSoldOut()) {
endCrowdsale();
}
TokenPurchase(investor, weiAmount, tokens, bonusTokens);
}
/**
* Functions for refunds & claim tokens
*
*/
//Refund users in case of unsuccessful crowdsale
function _refund(address _investor) internal {
uint256 investedAmt = investedSum[_investor];
require(investedAmt > 0);
uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]);
if (status == State.Active) {
//Refunded tokens go back to sale pool
totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens);
}
_clearAddressFromCrowdsale(_investor);
_investor.transfer(investedAmt);
Refunded(_investor, investedAmt);
}
//Partial refund users
function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external {
uint investedAmt = investedSum[_investor];
require(investedAmt > _refundAmt);
require(tokensAllocated[_investor] > _tokenAmt);
require(bonusTokensAllocated[_investor] > _bonusTokenAmt);
investedSum[_investor] = investedSum[_investor].sub(_refundAmt);
tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt);
bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt);
uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt);
if (status == State.Active) {
//Refunded tokens go back to sale pool
totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens);
}
_investor.transfer(_refundAmt);
Refunded(_investor, _refundAmt);
}
//Used by investor to claim token
function claimTokens() external {
require(hasEnded());
require(addressKYC[msg.sender]);
address tokenReceiver = msg.sender;
uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver);
require(tokensToClaim > 0);
_clearTotalNormalTokensByAddress(tokenReceiver);
violaToken.transferFrom(owner, tokenReceiver, tokensToClaim);
TokenDistributed(tokenReceiver, tokensToClaim);
}
//Used by investor to claim bonus token
function claimBonusTokens() external {
require(hasEnded());
require(now >= bonusVestingPeriod);
require(addressKYC[msg.sender]);
address tokenReceiver = msg.sender;
uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver);
require(tokensToClaim > 0);
_clearTotalBonusTokensByAddress(tokenReceiver);
violaToken.transferFrom(owner, tokenReceiver, tokensToClaim);
BonusTokenDistributed(tokenReceiver, tokensToClaim);
}
//Used by owner to distribute bonus token
function distributeBonusTokens(address _tokenReceiver) onlyOwner external {
require(hasEnded());
require(now >= bonusVestingPeriod);
address tokenReceiver = _tokenReceiver;
uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver);
require(tokensToClaim > 0);
_clearTotalBonusTokensByAddress(tokenReceiver);
transferTokens(tokenReceiver, tokensToClaim);
BonusTokenDistributed(tokenReceiver,tokensToClaim);
}
//Used by owner to distribute token
function distributeICOTokens(address _tokenReceiver) onlyOwner external {
require(hasEnded());
address tokenReceiver = _tokenReceiver;
uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver);
require(tokensToClaim > 0);
_clearTotalNormalTokensByAddress(tokenReceiver);
transferTokens(tokenReceiver, tokensToClaim);
TokenDistributed(tokenReceiver,tokensToClaim);
}
//For owner to reserve token for presale
// function reserveTokens(uint _amount) onlyOwner external {
// require(getTokensLeft() >= _amount);
// totalTokensAllocated = totalTokensAllocated.add(_amount);
// totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount);
// }
// //To distribute tokens not allocated by crowdsale contract
// function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external {
// require(hasEnded());
// require(_tokenReceiver != address(0));
// require(_amount > 0);
// violaToken.transferFrom(owner, _tokenReceiver, _amount);
// TokenDistributed(_tokenReceiver,_amount);
// }
//For external purchases & pre-sale via btc/fiat
function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external {
require(_amount > 0);
uint256 totalTokensToAllocate = _amount.add(_bonusAmount);
require(getTokensLeft() >= totalTokensToAllocate);
totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate);
totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate);
externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount);
externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount);
ExternalTokenPurchase(_investor, _amount, _bonusAmount);
}
function refundAllExternalPurchase(address _investor) onlyOwner external {
require(_investor != address(0));
require(externalTokensAllocated[_investor] > 0);
uint externalTokens = externalTokensAllocated[_investor];
uint externalBonusTokens = externalBonusTokensAllocated[_investor];
externalTokensAllocated[_investor] = 0;
externalBonusTokensAllocated[_investor] = 0;
uint totalInvestorTokens = externalTokens.add(externalBonusTokens);
totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens);
totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens);
ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens);
}
function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external {
require(_investor != address(0));
require(externalTokensAllocated[_investor] >= _amountToRefund);
require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund);
uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund);
externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund);
externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund);
totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund);
totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund);
ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund);
}
function _clearAddressFromCrowdsale(address _investor) internal {
tokensAllocated[_investor] = 0;
bonusTokensAllocated[_investor] = 0;
investedSum[_investor] = 0;
maxBuyCap[_investor] = 0;
}
function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external {
require(hasEnded());
require(_amount > 0);
uint256 tokensToAllocate = _amount.add(_bonusAmount);
require(getTokensLeft() >= tokensToAllocate);
totalTokensAllocated = totalTokensAllocated.add(_amount);
tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount);
bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount);
TopupTokenAllocated(_investor, _amount, _bonusAmount);
}
//For cases where token are mistakenly sent / airdrops
function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner {
require(status == State.Completed);
token.transfer(owner,amount);
}
} | Set KYC status as failed. Refund any eth back to address | function revokeKYC(address _kycAddress) onlyOwner external {
require(_kycAddress != address(0));
addressKYC[_kycAddress] = false;
uint256 weiAmount = investedSum[_kycAddress];
totalApprovedAmount = totalApprovedAmount.sub(weiAmount);
if (weiAmount > 0) {
_refund(_kycAddress);
}
}
| 5,343,236 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
import "./ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LCC is ERC721A, Ownable {
// Constants
uint256 public constant MAX_SUPPLY = 10_000;
// Variables
uint256 public MINT_PRICE = 0.07 ether;
mapping(address => bool) whitelistedAddressesOG;
uint256 public timestampPublicSale = 1672527599; // init to 2022-12-31 23:59:59 CET, to be set by owner
uint public percentageForTrading = 80;
uint public TRANCHE = 1;
/// @dev Base token URI used as a prefix by tokenURI().
string public baseTokenURI;
constructor() ERC721A("Legendary Cobra Club", "LCC", 1000, MAX_SUPPLY) {
baseTokenURI = "https://bafybeiad2xylgb47iw2ukcvhhfmtonuarf5e7k6xh3wvk5hyddxhan2imy.ipfs.dweb.link/metadata/";
}
/// @dev Returns an URI for a given token ID.
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
/// @dev Sets the base token URI prefix.
function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner {
baseTokenURI = _baseTokenURI;
}
/// Sets the minimum mint token price.
function setMintPrice(uint _mint_price) public onlyOwner {
MINT_PRICE = _mint_price;
}
/// Sets the timestamp date when everyone can mint new token.
function setTimestampPublicSale(uint256 _timestampPublicSale) public onlyOwner {
timestampPublicSale = _timestampPublicSale;
}
/// Sets the percentage for trading.
function setPercentageForTrading(uint _newPercentage) public onlyOwner {
percentageForTrading = _newPercentage;
}
/// Sets the mint trannche. 1 to 10
function setTranche(uint _tranche) public onlyOwner {
require(_tranche <=10, "tranche should be < 10");
TRANCHE = _tranche;
}
// Mint token if conditions are fulfilled.
function mint(uint number) public payable {
require( ((totalSupply() + number) / TRANCHE) <= 1000, "Max supply reached");
require(msg.value >= MINT_PRICE * number, "Transaction value is less than the min mint price");
if( timestampPublicSale > block.timestamp ) {
require(
verifyUserOG(msg.sender) ,
"You need to be whitelisted to mint token or you have wait for the public sale"
);
_safeMint(msg.sender, number);
}
else {
_safeMint(msg.sender, number);
}
}
// Owner can mint without paying smart contract
function mintFromOwner(uint number) public onlyOwner {
require( ((totalSupply() + number) / TRANCHE) <= 1000, "Max supply reached");
_safeMint(msg.sender, number);
}
/// Add a new address to the OG whitelist mapping.
function addWhitelistUserOG(address[] memory newWhitelistedUserOG) public onlyOwner {
for (uint i=0; i<newWhitelistedUserOG.length; i++) {
require( !verifyUserOG( newWhitelistedUserOG[i] ) , "already OG" );
whitelistedAddressesOG[ newWhitelistedUserOG[i] ] = true;
}
}
/// Verify is an address is whitelisted OG.
function verifyUserOG(address _whitelistedAddressOG) public view returns(bool) {
return whitelistedAddressesOG[_whitelistedAddressOG];
}
function getBalance() public view returns(uint) {
return address(this).balance;
}
function withdrawMoneyTo(address payable _to) public onlyOwner {
_to.transfer(getBalance() * (100 - percentageForTrading) / 100);
}
function withdrawMoneyForTrading() public onlyOwner {
payable(msg.sender).transfer(getBalance() * percentageForTrading / 100);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable collectionSize;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// 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 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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);
}
/**
* @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: 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
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);
} | Sets the mint trannche. 1 to 10 | function setTranche(uint _tranche) public onlyOwner {
require(_tranche <=10, "tranche should be < 10");
TRANCHE = _tranche;
}
| 13,962,259 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.6;
import {
IERC165,
ERC721,
IERC721,
IERC721Receiver,
Strings
} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol";
import {Settings} from "./Settings.sol";
contract Flashmint is
ERC721,
IERC721Receiver,
ReentrancyGuard,
IERC2981
{
using Strings for uint256;
/// -------------------------
/// === TOKEN INFORMATION ===
/// -------------------------
/// @notice the ERC721 token address of this vault's token
address public token;
/// @notice the erc721 token ID of this vault's token
uint256 public id;
/// -------------------------
/// === VAULT INFORMATION ===
/// -------------------------
/// @notice the protocol-wide settings
address public immutable settings;
/// @notice the price a lender must pay to mint with this token. in wei, ie 18 decimals (10**18 = 1)
uint256 public fee;
// NOT_ACTIVE when created, ACTIVE when initialized & ready for use
// FINISHED when NFT is withdrawn by owner
enum State { NOT_ACTIVE, ACTIVE, FINISHED }
State public vaultState;
/// @notice owner may reserve certain mints for themselves
mapping (address => bool) public reserved;
/// @notice NFTs owed to borrowers
/// @dev this only applies for NFTs minted without safeMint
/// note that tokenIds aren't reserved 1:1
/// token -> borrower -> number of NFTs
mapping (address => mapping (address => uint256)) public claimable;
/// @notice total number of NFTs owed to borrowers
/// the rest are prob airdrops and can be claimed by vault owner
/// token -> number of NFTs
mapping (address => uint256) public totalClaimable;
/// -------------------------
/// === MINT INFORMATION ===
/// -------------------------
enum FlightStatus {
READY, // before call to external NFT
INFLIGHT, // during call to external NFT
LANDED // once NFT is received in `onERC721Received`
}
struct MintRequest {
FlightStatus flightStatus;
address expectedNFTContractAddress;
uint256[] newids; // @notice this is only defined if flightStatus != READY
}
/// @notice state variable is needed to track a mint request because
/// we're reliant on the ERC721Receiver callback to get id
MintRequest private safeMintReq;
/// -------------------------
/// ======== EVENTS ========
/// -------------------------
/// @notice Emitted when `minter` borrows this NFT to mint `minted`
event FlashmintedSafe(address indexed minter, address indexed minted, uint256[] tokenIds, uint256 fee);
/// @notice Emitted when `minter` mints `amount` of NFTs (minted)
event Flashminted(address indexed minter, address indexed minted, uint256 amount, uint256 fee);
/// @notice Emitted when someone claims an NFT minted with unsafely
event ClaimedMint(address indexed claimant, address indexed minted, uint256 tokenId);
/// @notice Emitted when initial depositor reclaims their NFT and ends this contract.
event Closed(address depositor);
/// @notice Emitted when the claimer cashes out their fees
event Cash(address depositor, uint256 amount);
/// @notice Emitted when the cost is updated
event FeeUpdated(uint256 amount);
/// @notice Emitted when the owner reserves a mint for themselves
event Reserved(address indexed nft, bool indexed reserved);
string constant _name = unicode"⚡Flashmint Held NFT";
string constant _symbol = unicode"⚡FLASH";
constructor(address _settings) ERC721(_name, _symbol) {
vaultState = State.NOT_ACTIVE;
settings = _settings;
}
function name() public view override returns (string memory){return _name;}
function symbol() public view override returns (string memory){return _symbol;}
/// ---------------------------
/// === MODIFIERS ===
/// ---------------------------
// @dev access control for vault admin functions
modifier onlyVaultOwner {
require(msg.sender == ownerOf(0), "not owner");
_;
}
// @dev for use with calls to external contracts
modifier noStealing {
_;
require(IERC721(token).ownerOf(id) == address(this), "no stealing");
}
// @dev prevent malicious calls to `token` that eg approve() others
modifier notToken(address _token) {
require(token != _token, "can't call underlying");
_;
}
modifier noMeanCalldata(bytes calldata _mintData) {
bytes4 APPROVE = bytes4(0x095ea7b3);
bytes4 APPROVE_FOR_ALL = bytes4(0xa22cb465);
bytes4 sig = bytes4(_mintData[:4]);
require(
sig != APPROVE && sig != APPROVE_FOR_ALL,
"no mean sigs"
);
_;
}
/// ---------------------------
/// === LIFECYCLE FUNCTIONS ===
/// ---------------------------
function initializeWithNFT(address _token, uint256 _id, address _depositor, uint256 _fee) external nonReentrant {
require(vaultState == State.NOT_ACTIVE, "already active");
require(_token != _depositor, "self deposit");
token = _token;
id = _id;
vaultState = State.ACTIVE;
fee = _fee;
_safeMint(_depositor, 0);
emit FeeUpdated(_fee);
}
/// @notice allow the depositor to reclaim their NFT, ending this flashmint
function withdrawNFT() external nonReentrant {
vaultState = State.FINISHED;
// pay out remaining balance
_withdrawEth();
address recipient = ownerOf(0);
// @note requires that msgSender controls id 0 of this vault
transferFrom(recipient, address(this), 0);
// Burn LP token
_burn(0);
// Distribute underlying token
IERC721(token).safeTransferFrom(address(this), recipient, id);
emit Closed(msg.sender);
}
/// @notice allows anyone to forward payments to the depositor
function withdrawEth() external nonReentrant {
require(vaultState != State.NOT_ACTIVE, "State is NOT_ACTIVE");
_withdrawEth();
}
function _withdrawEth() internal {
address recipient = ownerOf(0);
uint256 amount = address(this).balance;
uint256 protocolFee = amount * Settings(settings).protocolFeeBips() / 10000;
address protocol = Settings(settings).protocolFeeReceiver();
bool sent;
if (protocolFee > 0 && protocol != address(0)) {
(sent, ) = payable(protocol).call{value: protocolFee}("");
require(sent, "_withdrawEth: protocol payment failed");
}
(sent, ) = payable(recipient).call{value: amount - protocolFee}("");
require(sent, "_withdrawEth: payment failed");
emit Cash(recipient, amount);
}
/// ---------------------------
/// === OWNER MGMT UTILITIES ===
/// ---------------------------
/// @notice allow the depositor to update their fee
function updateFee(uint256 _fee) external
onlyVaultOwner
nonReentrant
{
fee = _fee;
emit FeeUpdated(_fee);
}
/// @notice allow the depositor to reserve a mint for themselves
function reserve(address _token, bool _reserved) external
onlyVaultOwner
{
reserved[_token] = _reserved;
emit Reserved(_token, _reserved);
}
/// @notice let vault owner rescue eg airdrops
function rescueCoin(address _coin) external
onlyVaultOwner
notToken(_coin)
noStealing
{
uint256 balance = IERC20(_coin).balanceOf(address(this));
IERC20(_coin).transfer(msg.sender, balance);
}
/// @notice let vault owner rescue eg airdrops
function rescueNFT(address _token, uint256 _tokenId) external
nonReentrant
onlyVaultOwner
notToken(_token)
noStealing
{
// ensure token doesn't belong to a customer
require(
IERC721(_token).balanceOf(address(this)) >
totalClaimable[_token],
"spoken for"
);
IERC721(_token).transferFrom(address(this), msg.sender, _tokenId);
}
/// ---------------------------
/// === FLASHMINT FUNCTIONS ===
/// ---------------------------
/// @notice mint a derivative NFT and send it to the caller
/// @notice derivative must use `_safeMint` because need onERC721Received callback
/// @param _derivativeNFT the NFT user would like to mint
/// @param _mintData data for the mint function ie abi.encodeWithSignature(...)
function lendToMintSafe (
address _derivativeNFT,
bytes calldata _mintData
) external payable
nonReentrant
notToken(_derivativeNFT)
noMeanCalldata(_mintData)
noStealing
{
require(vaultState == State.ACTIVE, "vault not active");
require(msg.value >= fee, "didn't send enough eth");
require(!reserved[_derivativeNFT] || msg.sender == ownerOf(0), "NFT is reserved");
require(_derivativeNFT != address(this), "must call another contract");
require(_derivativeNFT != ownerOf(0), "must call another contract");
// request data is updated by nested functions, ie onERC721Received
delete safeMintReq.newids;
safeMintReq = MintRequest({
flightStatus: FlightStatus.INFLIGHT,
expectedNFTContractAddress: _derivativeNFT,
newids: new uint256[](0) // not used unless FlightStatus is LANDED
});
// mint the derivative and make sure we got it
(bool success, ) = _derivativeNFT.call{value: msg.value - fee}(_mintData);
require(success, "call to mint failed");
require(safeMintReq.flightStatus == FlightStatus.LANDED, "didnt mint");
uint256 len = safeMintReq.newids.length;
for (uint256 i = 0; i < len; i++) {
// @note: asserts that we own the token
IERC721(_derivativeNFT).safeTransferFrom(address(this), msg.sender, safeMintReq.newids[i]);
}
emit FlashmintedSafe(msg.sender, _derivativeNFT, safeMintReq.newids, fee);
// reset state variable for next calls.
delete safeMintReq.newids;
delete safeMintReq;
safeMintReq = MintRequest({
flightStatus: FlightStatus.READY,
expectedNFTContractAddress: address(0),
newids: new uint256[](0)
});
}
function onERC721Received(
address,
address,
uint256 _id,
bytes calldata
) external virtual override returns (bytes4) {
if (safeMintReq.flightStatus == FlightStatus.INFLIGHT
&& msg.sender == safeMintReq.expectedNFTContractAddress
){
// we're receiving the expected derivative
safeMintReq.flightStatus = FlightStatus.LANDED;
safeMintReq.newids.push(_id);
}
// Note: can still receive other NFTs
return this.onERC721Received.selector;
}
/// @notice mint an NFT that doesn't use `safeMint()`
/// without knowing the tokenId, two txs are required.
/// @notice this function is unsafe if _derivativeNFT is sketchy,
/// ie has non ERC721 `approve` fns,
/// @dev see `lendToMintSafe` for _safeMint() NFTs
function lendToMint(
address _derivativeNFT,
bytes calldata _mintData
) external payable
nonReentrant
notToken(_derivativeNFT)
noMeanCalldata(_mintData)
noStealing
{
require(vaultState == State.ACTIVE, "vault not active");
require(msg.value >= fee, "didn't send enough eth");
require(!reserved[_derivativeNFT] || msg.sender == ownerOf(0), "NFT is reserved");
require(_derivativeNFT != address(this), "must call another contract");
require(_derivativeNFT != ownerOf(0), "must call another contract");
uint256 balanceBefore = IERC721(_derivativeNFT).balanceOf(address(this));
// mint the derivative and make sure we got it
(bool success, ) = _derivativeNFT.call{value: msg.value - fee}(_mintData);
require(success, "call to mint failed");
// check that we minted successfully
uint256 gained = IERC721(_derivativeNFT).balanceOf(address(this)) - balanceBefore;
require(gained > 0, "didnt mint");
// set them aside for the minter
claimable[_derivativeNFT][msg.sender] += gained;
totalClaimable[_derivativeNFT] += gained;
emit Flashminted(msg.sender, _derivativeNFT, gained, fee);
}
function claimMintedNFT(address _derivativeNFT, uint256 _newTokenId) external
notToken(_derivativeNFT)
noStealing
{
// throws if msg.sender doesn't have a claimable token
claimable[_derivativeNFT][msg.sender] --;
totalClaimable[_derivativeNFT] --;
// throws if we don't own `_newTokenId`
IERC721(_derivativeNFT).safeTransferFrom(address(this), msg.sender, _newTokenId);
emit ClaimedMint(msg.sender, _derivativeNFT, _newTokenId);
}
/// ---------------------------
/// === TOKENURI FUNCTIONS ===
/// ---------------------------
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(vaultState == State.ACTIVE, "no token");
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory tAddr = toAsciiString(token);
string memory tId = id.toString();
string memory myAddr = toAsciiString(address(this));
return string(abi.encodePacked(
Settings(settings).baseURI(),
myAddr,
"/",
tokenId.toString(),
"/",
tAddr,
"/",
tId,
"/"
));
}
function toAsciiString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(bytes1 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
/// ---------------------------
/// = PROJECT SETTINGS & MARKETPLACES =
/// ---------------------------
// some NFT marketplaces wants an `owner()` function
function owner() public view virtual returns (address) {
return Settings(settings).marketplaceAdmin();
}
// eventual compatibility with royalties
function royaltyInfo(uint256 /*tokenId*/, uint256 _salePrice)
external view virtual override
returns (address receiver, uint256 royaltyAmount) {
receiver = Settings(settings).royaltyReceiver();
royaltyAmount = _salePrice * Settings(settings).royaltyPercentBips() / 10000;
}
function supportsInterface(bytes4 interfaceId)
public view virtual
override(IERC165, ERC721)
returns (bool)
{
return interfaceId == type(IERC2981).interfaceId
|| super.supportsInterface(interfaceId);
}
receive() external payable{}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @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 making 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
contract Settings is Ownable {
event RoyaltyInfoUpdated(address indexed receiver, uint256 royaltyPercentBips);
event ProtocolFeeUpdated(address indexed receiver, uint256 protocolFeeBips);
event MarketplaceAdminUpdated(address indexed marketplaceAdmin);
// royalties on LP tokens
uint256 public royaltyPercentBips; // ie 250 = 2.5%
address public royaltyReceiver;
// protocol fee on flashmints
uint256 public protocolFeeBips;
address public protocolFeeReceiver;
// some NFT marketplaces want NFTs to have an `owner()` function
address public marketplaceAdmin;
string public baseURI;
// royalties, protocol fee are 0 unless turned on
constructor() {
baseURI = "http://flashmint.ooo/api/tokenURI/";
}
function setRoyaltyPercentBips(uint256 _royaltyPercentBips) external onlyOwner {
require(_royaltyPercentBips < 1000, "royalties: cmon"); // force prevent high royalties
royaltyPercentBips = _royaltyPercentBips;
emit RoyaltyInfoUpdated(royaltyReceiver, _royaltyPercentBips);
}
function setRoyaltyReceiver(address _royaltyReceiver) external onlyOwner {
royaltyReceiver = _royaltyReceiver;
emit RoyaltyInfoUpdated(_royaltyReceiver, royaltyPercentBips);
}
function setProtocolFee(uint256 _protocolFeeBips) external onlyOwner {
require(_protocolFeeBips < 5000, "fee: cmon");
protocolFeeBips = _protocolFeeBips;
emit ProtocolFeeUpdated(protocolFeeReceiver, _protocolFeeBips);
}
function setProtocolFeeReceiver(address _protocolFeeReceiver) external onlyOwner {
protocolFeeReceiver = _protocolFeeReceiver;
emit ProtocolFeeUpdated(_protocolFeeReceiver, protocolFeeBips);
}
function setMarketplaceAdmin(address _marketplaceAdmin) external onlyOwner {
marketplaceAdmin = _marketplaceAdmin;
emit MarketplaceAdminUpdated(_marketplaceAdmin);
}
function setBaseURI(string calldata _baseURI) external onlyOwner {
baseURI = _baseURI;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// 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 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);
}
/**
* @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: 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
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: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// 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);
}
} | eventual compatibility with royalties | function royaltyInfo(uint256 /*tokenId*/, uint256 _salePrice)
external view virtual override
returns (address receiver, uint256 royaltyAmount) {
receiver = Settings(settings).royaltyReceiver();
royaltyAmount = _salePrice * Settings(settings).royaltyPercentBips() / 10000;
}
| 14,948,777 |
./full_match/137/0x7130678c156f525bdF23322Be09fA85301AcE1A0/sources/contracts/B4REAL.sol | Adds a wallet address from the whitelist | function includeInFee(address wallet)
public
onlyAdmin
onlyValidAddress(wallet)
{
whitelist[wallet] = true;
}
| 4,686,594 |
./partial_match/1/0xa3df9428dedA5120d04177488849f7507B2e5067/sources/SmartController.sol | Transfers tokens from a specific address [ERC20]. The address owner has to approve the spender beforehand. The from address, to address and amount are validated before executing method. Overrides method in a parent. Prior to transfering tokens the validator needs to approve. caller Address of the caller passed through the frontend. from Address to debet the tokens from. to Recipient address. amount Number of tokens to transfer./ | function transferFrom_withCaller(
address caller,
address from,
address to,
uint256 amount
) public override returns (bool) {
require(
smartToken.validate(from, to, amount),
"transferFrom request not valid"
);
return super.transferFrom_withCaller(caller, from, to, amount);
}
| 4,150,095 |
./full_match/43114/0xc9070B3EFE0aacC5AfB4B31C5DbDCA7C6B4bAAA9/sources/contracts/YieldWolf.sol | runs the strategy and pays the bounty reward _pid the pool id/ | function earn(uint256 _pid) external nonReentrant returns (uint256) {
return _earn(_pid);
}
| 4,507,341 |
/**
*Submitted for verification at Etherscan.io on 2021-09-09
*/
pragma solidity ^0.5.16;
interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint 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);
}
function _mint(address account, uint 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);
}
function _burn(address account, uint 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);
}
function _approve(address owner, address spender, uint 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);
}
}
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;
}
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;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Exotiqe is ERC20, ERC20Detailed {
uint256 public taxFee=2;
uint256 public sellIncrement=2;
address public taxWallet=0x21c16355430C1be5737B8849DEcc53BbD94bE16D;
constructor () public ERC20Detailed("Exotiqe", "EXOT", 18) {
_mint(0xd1d3A907691160f8753E2EE3653453b2221e20FA, 25e28);
}
function setIncrementFee(uint256 _sellIncrementFee) public{
sellIncrement = _sellIncrementFee;
}
function setTaxFee(uint256 _taxFee) public{
taxFee = _taxFee;
}
function setTaxWallet(address _setTaxWallet) public{
taxWallet = _setTaxWallet;
}
function mint(address recipient_, uint256 amount_)
public
returns (bool)
{
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter >= balanceBefore;
}
} | Solidity only automatically asserts when dividing by 0 | function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
| 15,036,347 |
pragma solidity ^0.5.0;
contract Auction {
// the owner of the auction
address payable public owner;
// the start time of the auction
uint256 public startTime;
// the end time of the auction
uint256 public endTime;
// the current highest bid/bidder
uint256 public highestBid;
address public highestBidder;
// mapping between bidders and the amount of money they bid
mapping(address => uint256) amounts;
event HighestBidIncreased(address bidder, uint256 amount);
constructor(uint256 _startTime, uint256 _endTime) public {
startTime = _startTime;
endTime = _endTime;
owner = msg.sender;
}
modifier notEnded() {
require(now <= endTime, "Auction has ended.");
_;
}
modifier hasEnded() {
require(now > endTime, "Auction hasn't ended.");
_;
}
modifier hasStarted() {
require(now >= startTime, "Auction didn't start yet.");
_;
}
modifier isHighestBid() {
require(msg.value > highestBid, "There is a higher bid.");
_;
}
modifier notOwner() {
require(msg.sender != owner, "The owner can't bid.");
_;
}
modifier isOwner() {
require(msg.sender == owner, "Access restricted to owner.");
_;
}
function bid() public payable notEnded hasStarted notOwner isHighestBid {
// if the highest bid has been overtaken, the previous highest bidder can withdraw all his money (including his highest bid)
if (highestBid != 0) {
amounts[highestBidder] += highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
emit HighestBidIncreased(msg.sender, msg.value);
}
function withdraw() public payable notOwner returns (bool) {
// you can withdraw if you are not owner
// if you are the current highest bidder, you can not withdraw your highest bid (only the other ones)
uint256 amount = amounts[msg.sender];
if (amount > 0) {
amounts[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// if the transaction fails, the amount is added back
amounts[msg.sender] = amount;
return false;
}
}
return true;
}
function transferToOwner() public hasEnded payable isOwner {
// if the auction is done, transfer the money to owner
// can be called only by the owner
owner.transfer(highestBid);
}
} | you can withdraw if you are not owner if you are the current highest bidder, you can not withdraw your highest bid (only the other ones) if the transaction fails, the amount is added back | function withdraw() public payable notOwner returns (bool) {
uint256 amount = amounts[msg.sender];
if (amount > 0) {
amounts[msg.sender] = 0;
if (!msg.sender.send(amount)) {
amounts[msg.sender] = amount;
return false;
}
}
return true;
}
| 999,975 |
// SPDX-License-Identifier: MIT
// TODO: What license do we release under?
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
@title Fountain
Create a MoneyPool (MP) that'll be used to sustain your project, and specify what its sustainability target is.
Maybe your project is providing a service or public good, maybe it's being a YouTuber, engineer, or artist -- or anything else.
Anyone with your address can help sustain your project, and once you're sustainable any additional contributions are redistributed back your sustainers.
Each MoneyPool is like a tier of the fountain, and the predefined cost to pursue the project is like the bounds of that tier's pool.
An address can only be associated with one active MoneyPool at a time, as well as a mutable one queued up for when the active MoneyPool expires.
If a MoneyPool expires without one queued, the current one will be cloned and sustainments at that time will be allocated to it.
It's impossible for a MoneyPool's sustainability or duration to be changed once there has been a sustainment made to it.
Any attempts to do so will just create/update the message sender's queued MP.
You can collect funds of yours from the sustainers pool (where MoneyPool surplus is distributed) or from the sustainability pool (where MoneyPool sustainments are kept) at anytime.
Future versions will introduce MoneyPool dependencies so that your project's surplus can get redistributed to the MP of projects it is composed of before reaching sustainers.
We also think it may be best to create a governance token WATER and route ~7% of ecosystem surplus to token holders, ~3% to fountain.finance contributors (which can be run through Fountain itself), and the rest to sustainers.
The basin of the Fountain should always be the sustainers of projects.
*/
contract FountainV1 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Possible states that a MoneyPool may be in
/// @dev immutable once the MoneyPool receives some sustainment.
/// @dev entirely mutable until they become active.
enum MoneyPoolState {Pending, Active, Redistributing}
/// @notice The MoneyPool structure represents a MoneyPool stewarded by an address, and accounts for which addresses have contributed to it.
struct MoneyPool {
// The address who defined this MoneyPool and who has access to its sustainments.
address who;
// The token that this MoneyPool can be funded with.
address want;
// The amount that represents sustainability for this MoneyPool.
uint256 sustainabilityTarget;
// The running amount that's been contributed to sustaining this MoneyPool.
uint256 currentSustainment;
// The time when this MoneyPool will become active.
uint256 start;
// The number of days until this MoneyPool's redistribution is added to the redistributionPool.
uint256 duration;
// Helper to verify this MoneyPool exists.
bool exists;
// ID of the previous MoneyPool
uint256 previousMoneyPoolId;
// Indicates if surplus funds have been redistributed for each sustainer address
mapping(address => bool) redistributed;
// The addresses who have helped to sustain this MoneyPool.
// NOTE: Using arrays may be bad practice and/or expensive
address[] sustainers;
// The amount each address has contributed to the sustaining of this MoneyPool.
mapping(address => uint256) sustainmentTracker;
// The amount that will be redistributed to each address as a
// consequence of abundant sustainment of this MoneyPool once it resolves.
mapping(address => uint256) redistributionTracker;
}
enum Pool {REDISTRIBUTION, SUSTAINABILITY}
/// @notice The official record of all MoneyPools ever created
mapping(uint256 => MoneyPool) public moneyPools;
/// @notice The latest MoneyPool for each creator address
mapping(address => uint256) public latestMoneyPoolIds;
/// @notice List of addresses sustained by each sustainer
mapping(address => address[]) public sustainedAddressesBySustainer;
// The amount that has been redistributed to each address as a consequence of surplus.
mapping(address => uint256) public redistributionPool;
// The funds that have accumulated to sustain each address's MoneyPools.
mapping(address => uint256) public sustainabilityPool;
// The total number of MoneyPools created, which is used for issuing MoneyPool IDs.
// MoneyPools should have an id > 0, 0 should not be a moneyPoolId.
uint256 public moneyPoolCount;
// The contract currently only supports sustainments in DAI.
address public DAI;
event CreateMoneyPool(
uint256 indexed id,
address indexed by,
uint256 sustainabilityTarget,
uint256 duration,
address want
);
event UpdateMoneyPool(
uint256 indexed id,
address indexed by,
uint256 sustainabilityTarget,
uint256 duration,
address want
);
event SustainMoneyPool(
uint256 indexed id,
address indexed sustainer,
uint256 amount
);
event Collect(address indexed by, Pool indexed from, uint256 amount);
// --- External getters --- //
function getSustainerCount(address who)
external
view
returns (uint256 count)
{
require(
latestMoneyPoolIds[who] > 0,
"No MoneyPool found at this address"
);
require(
moneyPools[latestMoneyPoolIds[who]].exists,
"No MoneyPool found at this address"
);
return moneyPools[latestMoneyPoolIds[who]].sustainers.length;
}
function getSustainmentTrackerAmount(address who, address by)
external
view
returns (uint256 amount)
{
require(
latestMoneyPoolIds[who] > 0,
"No MoneyPool found at this address"
);
require(
moneyPools[latestMoneyPoolIds[who]].exists,
"No MoneyPool found at this address"
);
return moneyPools[latestMoneyPoolIds[who]].sustainmentTracker[by];
}
function getRedistributionTrackerAmount(address who, address by)
external
view
returns (uint256 amount)
{
require(
latestMoneyPoolIds[who] > 0,
"No MoneyPool found at this address"
);
require(
moneyPools[latestMoneyPoolIds[who]].exists,
"No MoneyPool found at this address"
);
return moneyPools[latestMoneyPoolIds[who]].redistributionTracker[by];
}
constructor(address dai) public {
DAI = dai;
moneyPoolCount = 0;
}
/// @notice Creates a MoneyPool to be sustained for the sending address.
/// @param target The sustainability target for the MoneyPool, in DAI.
/// @param duration The duration of the MoneyPool, which starts once this is created.
/// @param want The ERC20 token desired, currently only DAI is supported.
/// @return success If the creation was successful.
function createMoneyPool(
uint256 target,
uint256 duration,
address want
) external returns (bool success) {
require(
latestMoneyPoolIds[msg.sender] == 0,
"Fountain::createMoneyPool: Address already has a MoneyPool, call `update` instead"
);
require(
duration >= 1,
"Fountain::createMoneyPool: A MoneyPool must be at least one day long"
);
require(
want == DAI,
"Fountain::createMoneyPool: For now, a MoneyPool can only be funded with DAI"
);
moneyPoolCount++;
// Must create structs that have mappings using this approach to avoid
// the RHS creating a memory-struct that contains a mapping.
// See https://ethereum.stackexchange.com/a/72310
MoneyPool storage newMoneyPool = moneyPools[moneyPoolCount];
newMoneyPool.who = msg.sender;
newMoneyPool.sustainabilityTarget = target;
newMoneyPool.currentSustainment = 0;
newMoneyPool.start = now;
newMoneyPool.duration = duration;
newMoneyPool.want = want;
newMoneyPool.exists = true;
newMoneyPool.previousMoneyPoolId = 0;
latestMoneyPoolIds[msg.sender] = moneyPoolCount;
emit CreateMoneyPool(
moneyPoolCount,
msg.sender,
target,
duration,
want
);
return true;
}
/// @notice Contribute a specified amount to the sustainability of the specified address's active MoneyPool.
/// @notice If the amount results in surplus, redistribute the surplus proportionally to sustainers of the MoneyPool.
/// @param who Address to sustain.
/// @param amount Amount of sustainment.
/// @return success If the sustainment was successful.
function sustain(address who, uint256 amount)
external
returns (bool success)
{
require(
amount > 0,
"Fountain::sustain: The sustainment amount should be positive"
);
uint256 moneyPoolId = _moneyPoolIdToSustain(who);
MoneyPool storage currentMoneyPool = moneyPools[moneyPoolId];
require(
currentMoneyPool.exists,
"Fountain::sustain: MoneyPool not found"
);
// The amount that should be reserved for the sustainability of the MoneyPool.
// If the MoneyPool is already sustainable, set to 0.
// If the MoneyPool is not yet sustainable even with the amount, set to the amount.
// Otherwise set to the portion of the amount it'll take for sustainability to be reached
uint256 sustainabilityAmount;
if (
currentMoneyPool.currentSustainment.add(amount) <=
currentMoneyPool.sustainabilityTarget
) {
sustainabilityAmount = amount;
} else if (
currentMoneyPool.currentSustainment >=
currentMoneyPool.sustainabilityTarget
) {
sustainabilityAmount = 0;
} else {
sustainabilityAmount = currentMoneyPool.sustainabilityTarget.sub(
currentMoneyPool.currentSustainment
);
}
// Save if the message sender is contributing to this MoneyPool for the first time.
bool isNewSustainer = currentMoneyPool.sustainmentTracker[msg.sender] ==
0;
// TODO: Not working.`Returned error: VM Exception while processing transaction: revert`
//https://ethereum.stackexchange.com/questions/60028/testing-transfer-of-tokens-with-truffle
// Got it working in tests using MockContract, but need to verify it works in testnet.
// Move the full sustainment amount to this address.
require(
IERC20(currentMoneyPool.want).transferFrom(
msg.sender,
address(this),
amount
),
"ERC20 transfer failed"
);
// Increment the funds that can be collected from sustainability.
sustainabilityPool[who] = sustainabilityPool[who].add(
sustainabilityAmount
);
// Increment the sustainments to the MoneyPool made by the message sender.
currentMoneyPool.sustainmentTracker[msg.sender] = currentMoneyPool
.sustainmentTracker[msg.sender]
.add(amount);
// Increment the total amount contributed to the sustainment of the MoneyPool.
currentMoneyPool.currentSustainment = currentMoneyPool
.currentSustainment
.add(amount);
// Add the message sender as a sustainer of the MoneyPool if this is the first sustainment it's making to it.
if (isNewSustainer) currentMoneyPool.sustainers.push(msg.sender);
// Add this address to the sustainer's list of sustained addresses
sustainedAddressesBySustainer[msg.sender].push(who);
// Redistribution amounts may have changed for the current MoneyPool.
_updateTrackedRedistribution(currentMoneyPool);
// Emit events.
emit SustainMoneyPool(moneyPoolId, msg.sender, amount);
return true;
}
/// @notice A message sender can collect what's been redistributed to it by MoneyPools once they have expired.
/// @param amount The amount to collect.
/// @return success If the collecting was a success.
function collectRedistributions(uint256 amount)
external
returns (bool success)
{
// Iterate over all of sender's sustained addresses to make sure
// redistribution has completed for all redistributable MoneyPools
address[] storage sustainedAddresses = sustainedAddressesBySustainer[msg
.sender];
for (uint256 i = 0; i < sustainedAddresses.length; i++) {
_redistributeMoneyPool(sustainedAddresses[i]);
}
_performCollectRedistributions(amount);
return true;
}
/// @notice A message sender can collect what's been redistributed to it by a specific MoneyPool once it's expired.
/// @param amount The amount to collect.
/// @param from The MoneyPool to collect from.
/// @return success If the collecting was a success.
function collectRedistributionsFromAddress(uint256 amount, address from)
external
returns (bool success)
{
_redistributeMoneyPool(from);
_performCollectRedistributions(amount);
return true;
}
/// @notice A message sender can collect what's been redistributed to it by specific MoneyPools once they have expired.
/// @param amount The amount to collect.
/// @param from The MoneyPools to collect from.
/// @return success If the collecting was a success.
function collectRedistributionsFromAddresses(
uint256 amount,
address[] calldata from
) external returns (bool success) {
for (uint256 i = 0; i < from.length; i++) {
_redistributeMoneyPool(from[i]);
}
_performCollectRedistributions(amount);
return true;
}
/// @notice A message sender can collect funds that have been used to sustain it's MoneyPools.
/// @param amount The amount to collect.
/// @return success If the collecting was a success.
function collectSustainments(uint256 amount)
external
returns (bool success)
{
require(
sustainabilityPool[msg.sender] >= amount,
"This address doesn't have enough to collect this much."
);
IERC20(DAI).safeTransferFrom(address(this), msg.sender, amount);
sustainabilityPool[msg.sender] = sustainabilityPool[msg.sender].sub(
amount
);
emit Collect(msg.sender, Pool.SUSTAINABILITY, amount);
return true;
}
/// @notice Updates the sustainability target and duration of the sender's current MoneyPool if it hasn't yet received sustainments, or
/// @notice sets the properties of the MoneyPool that will take effect once the current MoneyPool expires.
/// @param target The sustainability target to set.
/// @param duration The duration to set.
/// @param want The token that the MoneyPool wants.
/// @return success If the update was successful.
function updateMoneyPool(
uint256 target,
uint256 duration,
address want
) external returns (bool success) {
require(
latestMoneyPoolIds[msg.sender] > 0,
"You don't yet have a MoneyPool."
);
require(
want == DAI,
"Fountain::updateMoneyPool: For now, a MoneyPool can only be funded with DAI"
);
uint256 moneyPoolId = _moneyPoolIdToUpdate(msg.sender);
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
if (target > 0) moneyPool.sustainabilityTarget = target;
if (duration > 0) moneyPool.duration = duration;
moneyPool.want = want;
emit UpdateMoneyPool(
moneyPoolId,
moneyPool.who,
moneyPool.sustainabilityTarget,
moneyPool.duration,
moneyPool.want
);
return true;
}
// --- private --- //
/// @dev Executes the collection of redistributed funds.
/// @param amount The amount to collect.
function _performCollectRedistributions(uint256 amount) private {
require(
redistributionPool[msg.sender] >= amount,
"This address doesn't have enough to collect this much."
);
IERC20(DAI).safeTransferFrom(address(this), msg.sender, amount);
redistributionPool[msg.sender] = redistributionPool[msg.sender].sub(
amount
);
emit Collect(msg.sender, Pool.SUSTAINABILITY, amount);
}
/// @dev The sustainability of a MoneyPool cannot be updated if there have been sustainments made to it.
/// @param who The address to find a MoneyPool for.
/// @return id The resulting id.
function _moneyPoolIdToUpdate(address who) private returns (uint256 id) {
// Check if there is an active moneyPool
uint256 moneyPoolId = _getActiveMoneyPoolId(who);
if (
moneyPoolId != 0 && moneyPools[moneyPoolId].currentSustainment == 0
) {
// Allow active moneyPool to be updated if it has no sustainments
return moneyPoolId;
}
// Cannot update active moneyPool, check if there is a pending moneyPool
moneyPoolId = _getPendingMoneyPoolId(who);
if (moneyPoolId != 0) {
return moneyPoolId;
}
// No pending moneyPool found, clone the latest moneyPool
moneyPoolId = _getLatestMoneyPoolId(who);
return _createMoneyPoolFromId(moneyPoolId, now);
}
/// @dev Only active MoneyPools can be sustained.
/// @param who The address to find a MoneyPool for.
/// @return id The resulting id.
function _moneyPoolIdToSustain(address who) private returns (uint256 id) {
// Check if there is an active moneyPool
uint256 moneyPoolId = _getActiveMoneyPoolId(who);
if (moneyPoolId != 0) {
return moneyPoolId;
}
// No active moneyPool found, check if there is a pending moneyPool
moneyPoolId = _getPendingMoneyPoolId(who);
if (moneyPoolId != 0) {
return moneyPoolId;
}
// No pending moneyPool found, clone the latest moneyPool
moneyPoolId = _getLatestMoneyPoolId(who);
MoneyPool storage latestMoneyPool = moneyPools[moneyPoolId];
// Use a start date that's a multiple of the duration.
// This creates the effect that there have been scheduled MoneyPools ever since the `latest`, even if `latest` is a long time in the past.
uint256 start = _determineModuloStart(
latestMoneyPool.start.add(latestMoneyPool.duration),
latestMoneyPool.duration
);
return _createMoneyPoolFromId(moneyPoolId, start);
}
/// @dev Proportionally allocate the specified amount to the contributors of the specified MoneyPool,
/// @dev meaning each sustainer will receive a portion of the specified amount equivalent to the portion of the total
/// @dev amount contributed to the sustainment of the MoneyPool that they are responsible for.
/// @param mp The MoneyPool to update.
function _updateTrackedRedistribution(MoneyPool storage mp) private {
// Return if there's no surplus.
if (mp.sustainabilityTarget >= mp.currentSustainment) return;
uint256 surplus = mp.currentSustainment.sub(mp.sustainabilityTarget);
// For each sustainer, calculate their share of the sustainment and
// allocate a proportional share of the surplus, overwriting any previous value.
for (uint256 i = 0; i < mp.sustainers.length; i++) {
address sustainer = mp.sustainers[i];
uint256 currentSustainmentProportion = mp
.sustainmentTracker[sustainer]
.div(mp.currentSustainment);
uint256 sustainerSurplusShare = surplus.mul(
currentSustainmentProportion
);
//Store the updated redistribution in the MoneyPool.
mp.redistributionTracker[sustainer] = sustainerSurplusShare;
}
}
/// @dev Check to see if the given MoneyPool has started.
/// @param mp The MoneyPool to check.
/// @return isStarted The boolean result.
function _isMoneyPoolStarted(MoneyPool storage mp)
private
view
returns (bool isStarted)
{
return now >= mp.start;
}
/// @dev Check to see if the given MoneyPool has expired.
/// @param mp The MoneyPool to check.
/// @return isExpired The boolean result.
function _isMoneyPoolExpired(MoneyPool storage mp)
private
view
returns (bool isExpired)
{
return now > mp.start.add(mp.duration.mul(1 days));
}
/// @dev Take any tracked redistribution in the given moneyPool and
/// @dev add them to the redistribution pool.
/// @param mpAddress The MoneyPool address to redistribute.
function _redistributeMoneyPool(address mpAddress) private {
uint256 moneyPoolId = latestMoneyPoolIds[mpAddress];
require(
moneyPoolId > 0,
"Fountain::redistributeMoneyPool: MoneyPool not found"
);
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
// Iterate through all MoneyPools for this address. For each iteration,
// if the MoneyPool has a state of redistributing and it has not yet
// been redistributed for the current sustainer, then process the
// redistribution. Iterate until a MoneyPool is found that has already
// been redistributed for this sustainer. This logic should skip Active
// and Pending MoneyPools.
// Short circuits by testing `moneyPool.redistributed` to limit number
// of iterations since all previous MoneyPools must have already been
// redistributed.
address sustainer = msg.sender;
while (moneyPoolId > 0 && !moneyPool.redistributed[sustainer]) {
if (_state(moneyPoolId) == MoneyPoolState.Redistributing) {
redistributionPool[sustainer] = redistributionPool[sustainer]
.add(moneyPool.redistributionTracker[sustainer]);
moneyPool.redistributed[sustainer] = true;
}
moneyPoolId = moneyPool.previousMoneyPoolId;
moneyPool = moneyPools[moneyPoolId];
}
}
/// @dev Returns a copy of the given MoneyPool with reset sustainments.
/// @param moneyPoolId The id of the MoneyPool to base the new MoneyPool on.
/// @param start The start date to use for the new MoneyPool.
/// @return newMoneyPoolId The new MoneyPool ID.
function _createMoneyPoolFromId(uint256 moneyPoolId, uint256 start)
private
returns (uint256 newMoneyPoolId)
{
MoneyPool storage currentMoneyPool = moneyPools[moneyPoolId];
require(
currentMoneyPool.exists,
"Fountain::createMoneyPoolFromId: Invalid moneyPool"
);
moneyPoolCount++;
// Must create structs that have mappings using this approach to avoid
// the RHS creating a memory-struct that contains a mapping.
// See https://ethereum.stackexchange.com/a/72310
MoneyPool storage moneyPool = moneyPools[moneyPoolCount];
moneyPool.who = currentMoneyPool.who;
moneyPool.sustainabilityTarget = currentMoneyPool.sustainabilityTarget;
moneyPool.currentSustainment = 0;
moneyPool.start = start;
moneyPool.duration = currentMoneyPool.duration;
moneyPool.want = currentMoneyPool.want;
moneyPool.exists = true;
moneyPool.previousMoneyPoolId = moneyPoolId;
latestMoneyPoolIds[currentMoneyPool.who] = moneyPoolCount;
emit UpdateMoneyPool(
moneyPoolCount,
moneyPool.who,
moneyPool.sustainabilityTarget,
moneyPool.duration,
moneyPool.want
);
return moneyPoolCount;
}
/// @dev Returns a copy of the gi
/// @dev that starts when the given MoneyPool expired.
function _determineModuloStart(uint256 oldEnd, uint256 duration)
private
view
returns (uint256)
{
// Use the old end if the current time is still within the duration.
if (oldEnd.add(duration) > now) return oldEnd;
// Otherwise, use the closest multiple of the duration from the old end.
uint256 distanceToStart = (now.sub(oldEnd)).mod(duration);
return now.sub(distanceToStart);
}
function _state(uint256 moneyPoolId) private view returns (MoneyPoolState) {
require(
moneyPoolCount >= moneyPoolId && moneyPoolId > 0,
"Fountain::state: Invalid moneyPoolId"
);
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
require(moneyPool.exists, "Fountain::state: Invalid MoneyPool");
if (_isMoneyPoolExpired(moneyPool)) {
return MoneyPoolState.Redistributing;
}
if (_isMoneyPoolStarted(moneyPool) && !_isMoneyPoolExpired(moneyPool)) {
return MoneyPoolState.Active;
}
return MoneyPoolState.Pending;
}
function _getLatestMoneyPoolId(address moneyPoolAddress)
private
view
returns (uint256 id)
{
uint256 moneyPoolId = latestMoneyPoolIds[moneyPoolAddress];
require(
moneyPoolId > 0,
"Fountain::getLatestMoneyPoolId: MoneyPool not found"
);
return moneyPoolId;
}
function _getPendingMoneyPoolId(address moneyPoolAddress)
private
view
returns (uint256 id)
{
uint256 moneyPoolId = latestMoneyPoolIds[moneyPoolAddress];
require(
moneyPoolId > 0,
"Fountain::getPendingMoneyPoolId: MoneyPool not found"
);
if (_state(moneyPoolId) != MoneyPoolState.Pending) {
// There is no pending moneyPool if the latest MoneyPool is not pending
return 0;
}
return moneyPoolId;
}
function _getActiveMoneyPoolId(address moneyPoolAddress)
private
view
returns (uint256 id)
{
uint256 moneyPoolId = latestMoneyPoolIds[moneyPoolAddress];
require(
moneyPoolId > 0,
"Fountain::getActiveMoneyPoolId: MoneyPool not found"
);
// An Active moneyPool must be either the latest moneyPool or the
// moneyPool immediately before it.
if (_state(moneyPoolId) == MoneyPoolState.Active) {
return moneyPoolId;
}
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
require(
moneyPool.exists,
"Fountain::getActiveMoneyPoolId: Invalid MoneyPool"
);
moneyPoolId = moneyPool.previousMoneyPoolId;
if (moneyPoolId > 0 && _state(moneyPoolId) == MoneyPoolState.Active) {
return moneyPoolId;
}
return 0;
}
}
| A message sender can collect what's been redistributed to it by MoneyPools once they have expired. amount The amount to collect. return success If the collecting was a success. Iterate over all of sender's sustained addresses to make sure redistribution has completed for all redistributable MoneyPools | function collectRedistributions(uint256 amount)
external
returns (bool success)
{
address[] storage sustainedAddresses = sustainedAddressesBySustainer[msg
.sender];
for (uint256 i = 0; i < sustainedAddresses.length; i++) {
_redistributeMoneyPool(sustainedAddresses[i]);
}
_performCollectRedistributions(amount);
return true;
}
| 13,081,311 |
pragma solidity 0.4.24;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { BasicToken } from "openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol";
import { Ownable } from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title A token that can increase its supply in initial period
* @author Jakub Stefanski (https://github.com/jstefanski)
*/
contract MintableToken is BasicToken, Ownable {
using SafeMath for uint256;
/**
* @dev Address from which minted tokens are Transferred.
* @dev This is useful for blockchain explorers operating on Transfer event.
*/
address public constant MINT_ADDRESS = address(0x0);
/**
* @dev Indicates whether creating tokens has finished
*/
bool public mintingFinished;
/**
* @dev Addresses allowed to create tokens
*/
mapping (address => bool) public isMintingManager;
/**
* @dev Tokens minted to specified address
* @param to address The receiver of the tokens
* @param amount uint256 The amount of tokens
*/
event Minted(address indexed to, uint256 amount);
/**
* @dev Approves specified address as a Minting Manager
* @param addr address The approved address
*/
event MintingManagerApproved(address addr);
/**
* @dev Revokes specified address as a Minting Manager
* @param addr address The revoked address
*/
event MintingManagerRevoked(address addr);
/**
* @dev Creation of tokens finished
*/
event MintingFinished();
modifier onlyMintingManager(address addr) {
require(isMintingManager[addr]);
_;
}
modifier onlyMintingNotFinished {
require(!mintingFinished);
_;
}
/**
* @dev Approve specified address to mint tokens
* @param addr address The approved Minting Manager address
*/
function approveMintingManager(address addr)
public
onlyOwner
onlyMintingNotFinished
{
isMintingManager[addr] = true;
emit MintingManagerApproved(addr);
}
/**
* @dev Forbid specified address to mint tokens
* @param addr address The denied Minting Manager address
*/
function revokeMintingManager(address addr)
public
onlyOwner
onlyMintingManager(addr)
onlyMintingNotFinished
{
delete isMintingManager[addr];
emit MintingManagerRevoked(addr);
}
/**
* @dev Create new tokens and transfer them to specified address
* @param to address The address to transfer to
* @param amount uint256 The amount to be minted
*/
function mint(address to, uint256 amount)
public
onlyMintingManager(msg.sender)
onlyMintingNotFinished
{
totalSupply_ = totalSupply_.add(amount);
balances[to] = balances[to].add(amount);
emit Minted(to, amount);
emit Transfer(MINT_ADDRESS, to, amount);
}
/**
* @dev Prevent further creation of tokens
*/
function finishMinting()
public
onlyOwner
onlyMintingNotFinished
{
mintingFinished = true;
emit MintingFinished();
}
}
| Forbid specified address to mint tokens addr address The denied Minting Manager address/ | function revokeMintingManager(address addr)
public
onlyOwner
onlyMintingManager(addr)
onlyMintingNotFinished
{
delete isMintingManager[addr];
emit MintingManagerRevoked(addr);
}
| 955,909 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./ERC721.sol";
/**
* @title MasterchefMasatoshi
* NFT + DAO = NEW META
* Vitalik, remove contract size limit pls
*/
contract MasterchefMasatoshiJuniorX is ERC721, Ownable {
using ECDSA for bytes32;
string public PROVENANCE;
bool provenanceSet;
uint256 public mintPrice;
uint256 public maxPossibleSupply;
uint256 public allowListMintPrice;
uint256 public maxAllowedMints;
address public immutable currency;
address immutable wrappedNativeCoinAddress;
address payable immutable omakasea;
address private signerAddress;
bool public paused;
enum MintStatus {
PreMint,
AllowList,
Public,
Finished
}
MintStatus public mintStatus = MintStatus.PreMint;
mapping (address => uint256) public totalMintsPerAddress;
event Received(address, uint256);
receive() external payable {
emit Received(msg.sender, msg.value);
}
constructor(
string memory _name,
string memory _symbol,
uint256 _maxPossibleSupply,
uint256 _mintPrice,
uint256 _allowListMintPrice,
uint256 _maxAllowedMints,
address _signerAddress,
address payable _omakasea,
address _currency,
address _wrappedNativeCoinAddress
) ERC721(_name, _symbol, 10) {
maxPossibleSupply = _maxPossibleSupply;
mintPrice = _mintPrice;
allowListMintPrice = _allowListMintPrice;
maxAllowedMints = _maxAllowedMints;
signerAddress = _signerAddress;
omakasea = _omakasea;
currency = _currency;
wrappedNativeCoinAddress = _wrappedNativeCoinAddress;
}
function flipPaused() external onlyOwner {
paused = !paused;
}
function preMint(uint amount) public onlyOwner {
require(mintStatus == MintStatus.PreMint, "s");
require(totalSupply() + amount <= maxPossibleSupply, "m");
_safeMint(msg.sender, amount);
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
require(!provenanceSet);
PROVENANCE = provenanceHash;
provenanceSet = true;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function changeMintStatus(MintStatus _status) external onlyOwner {
require(_status != MintStatus.PreMint);
if (mintStatus == MintStatus.Public) {
require(_status != MintStatus.AllowList);
}
mintStatus = _status;
}
function mintAllowList(
bytes32 messageHash,
bytes calldata signature,
uint amount
) public payable {
require(mintStatus == MintStatus.AllowList && !paused, "s");
require(totalSupply() + amount <= maxPossibleSupply, "m");
require(hashMessage(msg.sender, address(this)) == messageHash, "i");
require(verifyAddressSigner(messageHash, signature), "f");
require(totalMintsPerAddress[msg.sender] + amount <= maxAllowedMints, "l");
uint mintAmount = allowListMintPrice * amount;
uint omakaseaFee = mintAmount * 25 / 1000;
if (currency == wrappedNativeCoinAddress) {
require(mintAmount <= msg.value, "a");
// 2.5% Omakasea Fee
omakasea.transfer(omakaseaFee);
} else {
IERC20 _currency = IERC20(currency);
// 2.5% Omakasea Fee
_currency.transferFrom(msg.sender, omakasea, omakaseaFee);
_currency.transferFrom(msg.sender, address(this), mintAmount - omakaseaFee);
}
totalMintsPerAddress[msg.sender] = totalMintsPerAddress[msg.sender] + amount;
_safeMint(msg.sender, amount);
}
function mintPublic(uint amount) public payable {
require(mintStatus == MintStatus.Public && !paused, "s");
require(totalSupply() + amount <= maxPossibleSupply, "m");
require(totalMintsPerAddress[msg.sender] + amount <= maxAllowedMints, "l");
uint mintAmount = mintPrice * amount;
uint omakaseaFee = mintAmount * 25 / 1000;
if (currency == wrappedNativeCoinAddress) {
require(mintPrice * amount <= msg.value, "a");
// 2.5% Omakasea Fee
omakasea.transfer(omakaseaFee);
} else {
IERC20 _currency = IERC20(currency);
// 2.5% Omakasea Fee
_currency.transferFrom(msg.sender, omakasea, omakaseaFee);
_currency.transferFrom(msg.sender, address(this), amount * mintPrice);
}
totalMintsPerAddress[msg.sender] = totalMintsPerAddress[msg.sender] + amount;
_safeMint(msg.sender, amount);
if (totalSupply() == maxPossibleSupply) {
mintStatus = MintStatus.Finished;
}
}
function verifyAddressSigner(bytes32 messageHash, bytes memory signature) private view returns (bool) {
return signerAddress == messageHash.toEthSignedMessageHash().recover(signature);
}
function hashMessage(address sender, address thisContract) public pure returns (bytes32) {
return keccak256(abi.encodePacked(sender, thisContract));
}
function withdraw() external onlyOwner() {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function withdrawTokens(address tokenAddress) external onlyOwner() {
IERC20(tokenAddress).transfer(msg.sender, IERC20(tokenAddress).balanceOf(address(this)));
}
}
// The High Table
// 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: 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;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "b");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "g");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), "b");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("u");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "0");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), "0");
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), "t");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("o");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "z");
return bytes(_baseURI).length > 0 ? string(abi.encodePacked(_baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "o");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"a"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "a");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "a");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"z"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "0");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "a");
require(quantity <= maxBatchSize, "m");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"z"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, "a");
require(prevOwnership.addr == from, "o");
require(to != address(0), "0");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "q");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "n");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(ownership.addr, ownership.startTimestamp);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("z");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// 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);
}
/**
* @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: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// 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: 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);
} | 2.5% Omakasea Fee 2.5% Omakasea Fee | function mintPublic(uint amount) public payable {
require(mintStatus == MintStatus.Public && !paused, "s");
require(totalSupply() + amount <= maxPossibleSupply, "m");
require(totalMintsPerAddress[msg.sender] + amount <= maxAllowedMints, "l");
uint mintAmount = mintPrice * amount;
uint omakaseaFee = mintAmount * 25 / 1000;
if (currency == wrappedNativeCoinAddress) {
require(mintPrice * amount <= msg.value, "a");
omakasea.transfer(omakaseaFee);
IERC20 _currency = IERC20(currency);
_currency.transferFrom(msg.sender, omakasea, omakaseaFee);
_currency.transferFrom(msg.sender, address(this), amount * mintPrice);
}
totalMintsPerAddress[msg.sender] = totalMintsPerAddress[msg.sender] + amount;
_safeMint(msg.sender, amount);
if (totalSupply() == maxPossibleSupply) {
mintStatus = MintStatus.Finished;
}
}
| 409,979 |
/**
*Submitted for verification at Etherscan.io on 2020-10-26
*/
// File: contracts/lib/interface/ICelerWallet.sol
pragma solidity ^0.5.1;
/**
* @title CelerWallet interface
*/
interface ICelerWallet {
function create(address[] calldata _owners, address _operator, bytes32 _nonce) external returns(bytes32);
function depositETH(bytes32 _walletId) external payable;
function depositERC20(bytes32 _walletId, address _tokenAddress, uint _amount) external;
function withdraw(bytes32 _walletId, address _tokenAddress, address _receiver, uint _amount) external;
function transferToWallet(bytes32 _fromWalletId, bytes32 _toWalletId, address _tokenAddress, address _receiver, uint _amount) external;
function transferOperatorship(bytes32 _walletId, address _newOperator) external;
function proposeNewOperator(bytes32 _walletId, address _newOperator) external;
function drainToken(address _tokenAddress, address _receiver, uint _amount) external;
function getWalletOwners(bytes32 _walletId) external view returns(address[] memory);
function getOperator(bytes32 _walletId) external view returns(address);
function getBalance(bytes32 _walletId, address _tokenAddress) external view returns(uint);
function getProposedNewOperator(bytes32 _walletId) external view returns(address);
function getProposalVote(bytes32 _walletId, address _owner) external view returns(bool);
event CreateWallet(bytes32 indexed walletId, address[] indexed owners, address indexed operator);
event DepositToWallet(bytes32 indexed walletId, address indexed tokenAddress, uint amount);
event WithdrawFromWallet(bytes32 indexed walletId, address indexed tokenAddress, address indexed receiver, uint amount);
event TransferToWallet(bytes32 indexed fromWalletId, bytes32 indexed toWalletId, address indexed tokenAddress, address receiver, uint amount);
event ChangeOperator(bytes32 indexed walletId, address indexed oldOperator, address indexed newOperator);
event ProposeNewOperator(bytes32 indexed walletId, address indexed newOperator, address indexed proposer);
event DrainToken(address indexed tokenAddress, address indexed receiver, uint amount);
}
// File: contracts/lib/interface/IEthPool.sol
pragma solidity ^0.5.1;
/**
* @title EthPool interface
*/
interface IEthPool {
function deposit(address _receiver) external payable;
function withdraw(uint _value) external;
function approve(address _spender, uint _value) external returns (bool);
function transferFrom(address _from, address payable _to, uint _value) external returns (bool);
function transferToCelerWallet(address _from, address _walletAddr, bytes32 _walletId, uint _value) external returns (bool);
function increaseAllowance(address _spender, uint _addedValue) external returns (bool);
function decreaseAllowance(address _spender, uint _subtractedValue) external returns (bool);
function balanceOf(address _owner) external view returns (uint);
function allowance(address _owner, address _spender) external view returns (uint);
event Deposit(address indexed receiver, uint value);
// transfer from "from" account inside EthPool to real "to" address outside EthPool
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// File: contracts/lib/interface/IPayRegistry.sol
pragma solidity ^0.5.1;
/**
* @title PayRegistry interface
*/
interface IPayRegistry {
function calculatePayId(bytes32 _payHash, address _setter) external pure returns(bytes32);
function setPayAmount(bytes32 _payHash, uint _amt) external;
function setPayDeadline(bytes32 _payHash, uint _deadline) external;
function setPayInfo(bytes32 _payHash, uint _amt, uint _deadline) external;
function setPayAmounts(bytes32[] calldata _payHashes, uint[] calldata _amts) external;
function setPayDeadlines(bytes32[] calldata _payHashes, uint[] calldata _deadlines) external;
function setPayInfos(bytes32[] calldata _payHashes, uint[] calldata _amts, uint[] calldata _deadlines) external;
function getPayAmounts(
bytes32[] calldata _payIds,
uint _lastPayResolveDeadline
) external view returns(uint[] memory);
function getPayInfo(bytes32 _payId) external view returns(uint, uint);
event PayInfoUpdate(bytes32 indexed payId, uint amount, uint resolveDeadline);
}
// File: contracts/lib/data/Pb.sol
pragma solidity ^0.5.0;
// runtime proto sol library
library Pb {
enum WireType { Varint, Fixed64, LengthDelim, StartGroup, EndGroup, Fixed32 }
struct Buffer {
uint idx; // the start index of next read. when idx=b.length, we're done
bytes b; // hold serialized proto msg, readonly
}
// create a new in-memory Buffer object from raw msg bytes
function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) {
buf.b = raw;
buf.idx = 0;
}
// whether there are unread bytes
function hasMore(Buffer memory buf) internal pure returns (bool) {
return buf.idx < buf.b.length;
}
// decode current field number and wiretype
function decKey(Buffer memory buf) internal pure returns (uint tag, WireType wiretype) {
uint v = decVarint(buf);
tag = v / 8;
wiretype = WireType(v & 7);
}
// count tag occurrences, return an array due to no memory map support
// have to create array for (maxtag+1) size. cnts[tag] = occurrences
// should keep buf.idx unchanged because this is only a count function
function cntTags(Buffer memory buf, uint maxtag) internal pure returns (uint[] memory cnts) {
uint originalIdx = buf.idx;
cnts = new uint[](maxtag+1); // protobuf's tags are from 1 rather than 0
uint tag;
WireType wire;
while (hasMore(buf)) {
(tag, wire) = decKey(buf);
cnts[tag] += 1;
skipValue(buf, wire);
}
buf.idx = originalIdx;
}
// read varint from current buf idx, move buf.idx to next read, return the int value
function decVarint(Buffer memory buf) internal pure returns (uint v) {
bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte)
bytes memory bb = buf.b; // get buf.b mem addr to use in assembly
v = buf.idx; // use v to save one additional uint variable
assembly {
tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp
}
uint b; // store current byte content
v = 0; // reset to 0 for return value
for (uint i=0; i<10; i++) {
assembly {
b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra
}
v |= (b & 0x7F) << (i * 7);
if (b & 0x80 == 0) {
buf.idx += i + 1;
return v;
}
}
revert(); // i=10, invalid varint stream
}
// read length delimited field and return bytes
function decBytes(Buffer memory buf) internal pure returns (bytes memory b) {
uint len = decVarint(buf);
uint end = buf.idx + len;
require(end <= buf.b.length); // avoid overflow
b = new bytes(len);
bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly
uint bStart;
uint bufBStart = buf.idx;
assembly {
bStart := add(b, 32)
bufBStart := add(add(bufB, 32), bufBStart)
}
for (uint i=0; i<len; i+=32) {
assembly{
mstore(add(bStart, i), mload(add(bufBStart, i)))
}
}
buf.idx = end;
}
// return packed ints
function decPacked(Buffer memory buf) internal pure returns (uint[] memory t) {
uint len = decVarint(buf);
uint end = buf.idx + len;
require(end <= buf.b.length); // avoid overflow
// array in memory must be init w/ known length
// so we have to create a tmp array w/ max possible len first
uint[] memory tmp = new uint[](len);
uint i = 0; // count how many ints are there
while (buf.idx < end) {
tmp[i] = decVarint(buf);
i++;
}
t = new uint[](i); // init t with correct length
for (uint j=0; j<i; j++) {
t[j] = tmp[j];
}
return t;
}
// move idx pass current value field, to beginning of next tag or msg end
function skipValue(Buffer memory buf, WireType wire) internal pure {
if (wire == WireType.Varint) { decVarint(buf); }
else if (wire == WireType.LengthDelim) {
uint len = decVarint(buf);
buf.idx += len; // skip len bytes value data
require(buf.idx <= buf.b.length); // avoid overflow
} else { revert(); } // unsupported wiretype
}
// type conversion help utils
function _bool(uint x) internal pure returns (bool v) {
return x != 0;
}
function _uint256(bytes memory b) internal pure returns (uint256 v) {
require(b.length <= 32); // b's length must be smaller than or equal to 32
assembly { v := mload(add(b, 32)) } // load all 32bytes to v
v = v >> (8 * (32 - b.length)); // only first b.length is valid
}
function _address(bytes memory b) internal pure returns (address v) {
v = _addressPayable(b);
}
function _addressPayable(bytes memory b) internal pure returns (address payable v) {
require(b.length == 20);
//load 32bytes then shift right 12 bytes
assembly { v := div(mload(add(b, 32)), 0x1000000000000000000000000) }
}
function _bytes32(bytes memory b) internal pure returns (bytes32 v) {
require(b.length == 32);
assembly { v := mload(add(b, 32)) }
}
// uint[] to uint8[]
function uint8s(uint[] memory arr) internal pure returns (uint8[] memory t) {
t = new uint8[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = uint8(arr[i]); }
}
function uint32s(uint[] memory arr) internal pure returns (uint32[] memory t) {
t = new uint32[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = uint32(arr[i]); }
}
function uint64s(uint[] memory arr) internal pure returns (uint64[] memory t) {
t = new uint64[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = uint64(arr[i]); }
}
function bools(uint[] memory arr) internal pure returns (bool[] memory t) {
t = new bool[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = arr[i]!=0; }
}
}
// File: contracts/lib/data/PbEntity.sol
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: entity.proto
pragma solidity ^0.5.0;
library PbEntity {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
enum TokenType { INVALID, ETH, ERC20 }
// TokenType[] decode function
function TokenTypes(uint[] memory arr) internal pure returns (TokenType[] memory t) {
t = new TokenType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = TokenType(arr[i]); }
}
enum TransferFunctionType { BOOLEAN_AND, BOOLEAN_OR, BOOLEAN_CIRCUIT, NUMERIC_ADD, NUMERIC_MAX, NUMERIC_MIN }
// TransferFunctionType[] decode function
function TransferFunctionTypes(uint[] memory arr) internal pure returns (TransferFunctionType[] memory t) {
t = new TransferFunctionType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = TransferFunctionType(arr[i]); }
}
enum ConditionType { HASH_LOCK, DEPLOYED_CONTRACT, VIRTUAL_CONTRACT }
// ConditionType[] decode function
function ConditionTypes(uint[] memory arr) internal pure returns (ConditionType[] memory t) {
t = new ConditionType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = ConditionType(arr[i]); }
}
struct AccountAmtPair {
address account; // tag: 1
uint256 amt; // tag: 2
} // end struct AccountAmtPair
function decAccountAmtPair(bytes memory raw) internal pure returns (AccountAmtPair memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.account = Pb._address(buf.decBytes());
}
else if (tag == 2) {
m.amt = Pb._uint256(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder AccountAmtPair
struct TokenInfo {
TokenType tokenType; // tag: 1
address tokenAddress; // tag: 2
} // end struct TokenInfo
function decTokenInfo(bytes memory raw) internal pure returns (TokenInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.tokenType = TokenType(buf.decVarint());
}
else if (tag == 2) {
m.tokenAddress = Pb._address(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TokenInfo
struct TokenDistribution {
TokenInfo token; // tag: 1
AccountAmtPair[] distribution; // tag: 2
} // end struct TokenDistribution
function decTokenDistribution(bytes memory raw) internal pure returns (TokenDistribution memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.distribution = new AccountAmtPair[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.token = decTokenInfo(buf.decBytes());
}
else if (tag == 2) {
m.distribution[cnts[2]] = decAccountAmtPair(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TokenDistribution
struct TokenTransfer {
TokenInfo token; // tag: 1
AccountAmtPair receiver; // tag: 2
} // end struct TokenTransfer
function decTokenTransfer(bytes memory raw) internal pure returns (TokenTransfer memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.token = decTokenInfo(buf.decBytes());
}
else if (tag == 2) {
m.receiver = decAccountAmtPair(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TokenTransfer
struct SimplexPaymentChannel {
bytes32 channelId; // tag: 1
address peerFrom; // tag: 2
uint seqNum; // tag: 3
TokenTransfer transferToPeer; // tag: 4
PayIdList pendingPayIds; // tag: 5
uint lastPayResolveDeadline; // tag: 6
uint256 totalPendingAmount; // tag: 7
} // end struct SimplexPaymentChannel
function decSimplexPaymentChannel(bytes memory raw) internal pure returns (SimplexPaymentChannel memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.peerFrom = Pb._address(buf.decBytes());
}
else if (tag == 3) {
m.seqNum = uint(buf.decVarint());
}
else if (tag == 4) {
m.transferToPeer = decTokenTransfer(buf.decBytes());
}
else if (tag == 5) {
m.pendingPayIds = decPayIdList(buf.decBytes());
}
else if (tag == 6) {
m.lastPayResolveDeadline = uint(buf.decVarint());
}
else if (tag == 7) {
m.totalPendingAmount = Pb._uint256(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder SimplexPaymentChannel
struct PayIdList {
bytes32[] payIds; // tag: 1
bytes32 nextListHash; // tag: 2
} // end struct PayIdList
function decPayIdList(bytes memory raw) internal pure returns (PayIdList memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.payIds = new bytes32[](cnts[1]);
cnts[1] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.payIds[cnts[1]] = Pb._bytes32(buf.decBytes());
cnts[1]++;
}
else if (tag == 2) {
m.nextListHash = Pb._bytes32(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder PayIdList
struct TransferFunction {
TransferFunctionType logicType; // tag: 1
TokenTransfer maxTransfer; // tag: 2
} // end struct TransferFunction
function decTransferFunction(bytes memory raw) internal pure returns (TransferFunction memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.logicType = TransferFunctionType(buf.decVarint());
}
else if (tag == 2) {
m.maxTransfer = decTokenTransfer(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TransferFunction
struct ConditionalPay {
uint payTimestamp; // tag: 1
address src; // tag: 2
address dest; // tag: 3
Condition[] conditions; // tag: 4
TransferFunction transferFunc; // tag: 5
uint resolveDeadline; // tag: 6
uint resolveTimeout; // tag: 7
address payResolver; // tag: 8
} // end struct ConditionalPay
function decConditionalPay(bytes memory raw) internal pure returns (ConditionalPay memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(8);
m.conditions = new Condition[](cnts[4]);
cnts[4] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.payTimestamp = uint(buf.decVarint());
}
else if (tag == 2) {
m.src = Pb._address(buf.decBytes());
}
else if (tag == 3) {
m.dest = Pb._address(buf.decBytes());
}
else if (tag == 4) {
m.conditions[cnts[4]] = decCondition(buf.decBytes());
cnts[4]++;
}
else if (tag == 5) {
m.transferFunc = decTransferFunction(buf.decBytes());
}
else if (tag == 6) {
m.resolveDeadline = uint(buf.decVarint());
}
else if (tag == 7) {
m.resolveTimeout = uint(buf.decVarint());
}
else if (tag == 8) {
m.payResolver = Pb._address(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder ConditionalPay
struct CondPayResult {
bytes condPay; // tag: 1
uint256 amount; // tag: 2
} // end struct CondPayResult
function decCondPayResult(bytes memory raw) internal pure returns (CondPayResult memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.condPay = bytes(buf.decBytes());
}
else if (tag == 2) {
m.amount = Pb._uint256(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CondPayResult
struct VouchedCondPayResult {
bytes condPayResult; // tag: 1
bytes sigOfSrc; // tag: 2
bytes sigOfDest; // tag: 3
} // end struct VouchedCondPayResult
function decVouchedCondPayResult(bytes memory raw) internal pure returns (VouchedCondPayResult memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.condPayResult = bytes(buf.decBytes());
}
else if (tag == 2) {
m.sigOfSrc = bytes(buf.decBytes());
}
else if (tag == 3) {
m.sigOfDest = bytes(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder VouchedCondPayResult
struct Condition {
ConditionType conditionType; // tag: 1
bytes32 hashLock; // tag: 2
address deployedContractAddress; // tag: 3
bytes32 virtualContractAddress; // tag: 4
bytes argsQueryFinalization; // tag: 5
bytes argsQueryOutcome; // tag: 6
} // end struct Condition
function decCondition(bytes memory raw) internal pure returns (Condition memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.conditionType = ConditionType(buf.decVarint());
}
else if (tag == 2) {
m.hashLock = Pb._bytes32(buf.decBytes());
}
else if (tag == 3) {
m.deployedContractAddress = Pb._address(buf.decBytes());
}
else if (tag == 4) {
m.virtualContractAddress = Pb._bytes32(buf.decBytes());
}
else if (tag == 5) {
m.argsQueryFinalization = bytes(buf.decBytes());
}
else if (tag == 6) {
m.argsQueryOutcome = bytes(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder Condition
struct CooperativeWithdrawInfo {
bytes32 channelId; // tag: 1
uint seqNum; // tag: 2
AccountAmtPair withdraw; // tag: 3
uint withdrawDeadline; // tag: 4
bytes32 recipientChannelId; // tag: 5
} // end struct CooperativeWithdrawInfo
function decCooperativeWithdrawInfo(bytes memory raw) internal pure returns (CooperativeWithdrawInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.seqNum = uint(buf.decVarint());
}
else if (tag == 3) {
m.withdraw = decAccountAmtPair(buf.decBytes());
}
else if (tag == 4) {
m.withdrawDeadline = uint(buf.decVarint());
}
else if (tag == 5) {
m.recipientChannelId = Pb._bytes32(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CooperativeWithdrawInfo
struct PaymentChannelInitializer {
TokenDistribution initDistribution; // tag: 1
uint openDeadline; // tag: 2
uint disputeTimeout; // tag: 3
uint msgValueReceiver; // tag: 4
} // end struct PaymentChannelInitializer
function decPaymentChannelInitializer(bytes memory raw) internal pure returns (PaymentChannelInitializer memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.initDistribution = decTokenDistribution(buf.decBytes());
}
else if (tag == 2) {
m.openDeadline = uint(buf.decVarint());
}
else if (tag == 3) {
m.disputeTimeout = uint(buf.decVarint());
}
else if (tag == 4) {
m.msgValueReceiver = uint(buf.decVarint());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder PaymentChannelInitializer
struct CooperativeSettleInfo {
bytes32 channelId; // tag: 1
uint seqNum; // tag: 2
AccountAmtPair[] settleBalance; // tag: 3
uint settleDeadline; // tag: 4
} // end struct CooperativeSettleInfo
function decCooperativeSettleInfo(bytes memory raw) internal pure returns (CooperativeSettleInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(4);
m.settleBalance = new AccountAmtPair[](cnts[3]);
cnts[3] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.seqNum = uint(buf.decVarint());
}
else if (tag == 3) {
m.settleBalance[cnts[3]] = decAccountAmtPair(buf.decBytes());
cnts[3]++;
}
else if (tag == 4) {
m.settleDeadline = uint(buf.decVarint());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CooperativeSettleInfo
struct ChannelMigrationInfo {
bytes32 channelId; // tag: 1
address fromLedgerAddress; // tag: 2
address toLedgerAddress; // tag: 3
uint migrationDeadline; // tag: 4
} // end struct ChannelMigrationInfo
function decChannelMigrationInfo(bytes memory raw) internal pure returns (ChannelMigrationInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.fromLedgerAddress = Pb._address(buf.decBytes());
}
else if (tag == 3) {
m.toLedgerAddress = Pb._address(buf.decBytes());
}
else if (tag == 4) {
m.migrationDeadline = uint(buf.decVarint());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder ChannelMigrationInfo
}
// File: contracts/lib/ledgerlib/LedgerStruct.sol
pragma solidity ^0.5.1;
/**
* @title Ledger Struct Library
* @notice CelerLedger library defining all used structs
*/
library LedgerStruct {
enum ChannelStatus { Uninitialized, Operable, Settling, Closed, Migrated }
struct PeerState {
uint seqNum;
// balance sent out to the other peer of the channel, no need to record amtIn
uint transferOut;
bytes32 nextPayIdListHash;
uint lastPayResolveDeadline;
uint pendingPayOut;
}
struct PeerProfile {
address peerAddr;
// the (monotone increasing) amount that this peer deposit into this channel
uint deposit;
// the (monotone increasing) amount that this peer withdraw from this channel
uint withdrawal;
PeerState state;
}
struct WithdrawIntent {
address receiver;
uint amount;
uint requestTime;
bytes32 recipientChannelId;
}
// Channel is a representation of the state channel between peers which puts the funds
// in CelerWallet and is hosted by a CelerLedger. The status of a state channel can
// be migrated from one CelerLedger instance to another CelerLedger instance with probably
// different operation logic.
struct Channel {
// the time after which peers can confirmSettle and before which peers can intendSettle
uint settleFinalizedTime;
uint disputeTimeout;
PbEntity.TokenInfo token;
ChannelStatus status;
// record the new CelerLedger address after channel migration
address migratedTo;
// only support 2-peer channel for now
PeerProfile[2] peerProfiles;
uint cooperativeWithdrawSeqNum;
WithdrawIntent withdrawIntent;
}
// Ledger is a host to record and operate the activities of many state
// channels with specific operation logic.
struct Ledger {
// ChannelStatus => number of channels
mapping(uint => uint) channelStatusNums;
IEthPool ethPool;
IPayRegistry payRegistry;
ICelerWallet celerWallet;
// per channel deposit limits for different tokens
mapping(address => uint) balanceLimits;
// whether deposit limits of all tokens have been enabled
bool balanceLimitsEnabled;
mapping(bytes32 => Channel) channelMap;
}
}
// File: contracts/lib/interface/ICelerLedger.sol
pragma solidity ^0.5.1;
/**
* @title CelerLedger interface
* @dev any changes in this interface must be synchronized to corresponding libraries
* @dev events in this interface must be exactly same in corresponding used libraries
*/
interface ICelerLedger {
/********** LedgerOperation related functions and events **********/
function openChannel(bytes calldata _openChannelRequest) external payable;
function deposit(bytes32 _channelId, address _receiver, uint _transferFromAmount) external payable;
function depositInBatch(
bytes32[] calldata _channelIds,
address[] calldata _receivers,
uint[] calldata _transferFromAmounts
) external;
function snapshotStates(bytes calldata _signedSimplexStateArray) external;
function intendWithdraw(bytes32 _channelId, uint _amount, bytes32 _recipientChannelId) external;
function confirmWithdraw(bytes32 _channelId) external;
function vetoWithdraw(bytes32 _channelId) external;
function cooperativeWithdraw(bytes calldata _cooperativeWithdrawRequest) external;
function intendSettle(bytes calldata _signedSimplexStateArray) external;
function clearPays(bytes32 _channelId, address _peerFrom, bytes calldata _payIdList) external;
function confirmSettle(bytes32 _channelId) external;
function cooperativeSettle(bytes calldata _settleRequest) external;
function getChannelStatusNum(uint _channelStatus) external view returns(uint);
function getEthPool() external view returns(address);
function getPayRegistry() external view returns(address);
function getCelerWallet() external view returns(address);
event OpenChannel(
bytes32 indexed channelId,
uint tokenType,
address indexed tokenAddress,
// TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed
address[2] peerAddrs,
uint[2] initialDeposits
);
// TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed
event Deposit(bytes32 indexed channelId, address[2] peerAddrs, uint[2] deposits, uint[2] withdrawals);
event SnapshotStates(bytes32 indexed channelId, uint[2] seqNums);
event IntendSettle(bytes32 indexed channelId, uint[2] seqNums);
event ClearOnePay(bytes32 indexed channelId, bytes32 indexed payId, address indexed peerFrom, uint amount);
event ConfirmSettle(bytes32 indexed channelId, uint[2] settleBalance);
event ConfirmSettleFail(bytes32 indexed channelId);
event IntendWithdraw(bytes32 indexed channelId, address indexed receiver, uint amount);
event ConfirmWithdraw(
bytes32 indexed channelId,
uint withdrawnAmount,
address indexed receiver,
bytes32 indexed recipientChannelId,
uint[2] deposits,
uint[2] withdrawals
);
event VetoWithdraw(bytes32 indexed channelId);
event CooperativeWithdraw(
bytes32 indexed channelId,
uint withdrawnAmount,
address indexed receiver,
bytes32 indexed recipientChannelId,
uint[2] deposits,
uint[2] withdrawals,
uint seqNum
);
event CooperativeSettle(bytes32 indexed channelId, uint[2] settleBalance);
/********** End of LedgerOperation related functions and events **********/
/********** LedgerChannel related functions and events **********/
function getSettleFinalizedTime(bytes32 _channelId) external view returns(uint);
function getTokenContract(bytes32 _channelId) external view returns(address);
function getTokenType(bytes32 _channelId) external view returns(PbEntity.TokenType);
function getChannelStatus(bytes32 _channelId) external view returns(LedgerStruct.ChannelStatus);
function getCooperativeWithdrawSeqNum(bytes32 _channelId) external view returns(uint);
function getTotalBalance(bytes32 _channelId) external view returns(uint);
function getBalanceMap(bytes32 _channelId) external view returns(address[2] memory, uint[2] memory, uint[2] memory);
function getChannelMigrationArgs(bytes32 _channelId) external view returns(uint, uint, address, uint);
function getPeersMigrationInfo(bytes32 _channelId) external view returns(
address[2] memory,
uint[2] memory,
uint[2] memory,
uint[2] memory,
uint[2] memory,
uint[2] memory
);
function getDisputeTimeout(bytes32 _channelId) external view returns(uint);
function getMigratedTo(bytes32 _channelId) external view returns(address);
function getStateSeqNumMap(bytes32 _channelId) external view returns(address[2] memory, uint[2] memory);
function getTransferOutMap(bytes32 _channelId) external view returns(
address[2] memory,
uint[2] memory
);
function getNextPayIdListHashMap(bytes32 _channelId) external view returns(
address[2] memory,
bytes32[2] memory
);
function getLastPayResolveDeadlineMap(bytes32 _channelId) external view returns(
address[2] memory,
uint[2] memory
);
function getPendingPayOutMap(bytes32 _channelId) external view returns(
address[2] memory,
uint[2] memory
);
function getWithdrawIntent(bytes32 _channelId) external view returns(address, uint, uint, bytes32);
/********** End of LedgerChannel related functions and events **********/
/********** LedgerBalanceLimit related functions and events **********/
function setBalanceLimits(address[] calldata _tokenAddrs, uint[] calldata _limits) external;
function disableBalanceLimits() external;
function enableBalanceLimits() external;
function getBalanceLimit(address _tokenAddr) external view returns(uint);
function getBalanceLimitsEnabled() external view returns(bool);
/********** End of LedgerBalanceLimit related functions and events **********/
/********** LedgerMigrate related functions and events **********/
function migrateChannelTo(bytes calldata _migrationRequest) external returns(bytes32);
function migrateChannelFrom(address _fromLedgerAddr, bytes calldata _migrationRequest) external;
event MigrateChannelTo(bytes32 indexed channelId, address indexed newLedgerAddr);
event MigrateChannelFrom(bytes32 indexed channelId, address indexed oldLedgerAddr);
/********** End of LedgerMigrate related functions and events **********/
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @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 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 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 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 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;
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
pragma solidity ^0.5.0;
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: contracts/lib/ledgerlib/LedgerChannel.sol
pragma solidity ^0.5.1;
/**
* @title Ledger Channel Library
* @notice CelerLedger library about Channel struct
* @dev this can be included in LedgerOperation to save some gas,
* however, keep this for now for clearness.
*/
library LedgerChannel {
using SafeMath for uint;
using ECDSA for bytes32;
/**
* @notice Get channel confirm settle open time
* @param _c the channel being used
* @return channel confirm settle open time
*/
function getSettleFinalizedTime(LedgerStruct.Channel storage _c) public view returns(uint) {
return _c.settleFinalizedTime;
}
/**
* @notice Get channel token contract address
* @param _c the channel being used
* @return channel token contract address
*/
function getTokenContract(LedgerStruct.Channel storage _c) public view returns(address) {
return _c.token.tokenAddress;
}
/**
* @notice Get channel token type
* @param _c the channel being used
* @return channel token type
*/
function getTokenType(LedgerStruct.Channel storage _c) public view returns(PbEntity.TokenType) {
return _c.token.tokenType;
}
/**
* @notice Get channel status
* @param _c the channel being used
* @return channel status
*/
function getChannelStatus(
LedgerStruct.Channel storage _c
)
public
view
returns(LedgerStruct.ChannelStatus)
{
return _c.status;
}
/**
* @notice Get cooperative withdraw seqNum
* @param _c the channel being used
* @return cooperative withdraw seqNum
*/
function getCooperativeWithdrawSeqNum(LedgerStruct.Channel storage _c) public view returns(uint) {
return _c.cooperativeWithdrawSeqNum;
}
/**
* @notice Return one channel's total balance amount
* @param _c the channel
* @return channel's balance amount
*/
function getTotalBalance(LedgerStruct.Channel storage _c) public view returns(uint) {
uint balance = _c.peerProfiles[0].deposit
.add(_c.peerProfiles[1].deposit)
.sub(_c.peerProfiles[0].withdrawal)
.sub(_c.peerProfiles[1].withdrawal);
return balance;
}
/**
* @notice Return one channel's balance info (depositMap and withdrawalMap)
* @dev Solidity can't directly return an array of struct for now
* @param _c the channel
* @return addresses of peers in the channel
* @return corresponding deposits of the peers (with matched index)
* @return corresponding withdrawals of the peers (with matched index)
*/
function getBalanceMap(LedgerStruct.Channel storage _c) public view
returns(address[2] memory, uint[2] memory, uint[2] memory)
{
address[2] memory peerAddrs = [_c.peerProfiles[0].peerAddr, _c.peerProfiles[1].peerAddr];
uint[2] memory deposits = [_c.peerProfiles[0].deposit, _c.peerProfiles[1].deposit];
uint[2] memory withdrawals = [_c.peerProfiles[0].withdrawal, _c.peerProfiles[1].withdrawal];
return (peerAddrs, deposits, withdrawals);
}
/**
* @notice Return channel-level migration arguments
* @param _c the channel to be viewed
* @return channel dispute timeout
* @return channel tokey type converted to uint
* @return channel token address
* @return sequence number of cooperative withdraw
* @dev related to Ledger Migration
*/
function getChannelMigrationArgs(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(uint, uint, address, uint)
{
return (
_c.disputeTimeout,
uint(_c.token.tokenType),
_c.token.tokenAddress,
_c.cooperativeWithdrawSeqNum
);
}
/**
* @notice Return migration info of the peers in the channel
* @param _c the channel to be viewed
* @return peers' addresses
* @return peers' deposits
* @return peers' withdrawals
* @return peers' state sequence numbers
* @return peers' transferOut map
* @return peers' pendingPayOut map
* @dev related to Ledger Migration
*/
function getPeersMigrationInfo(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(
address[2] memory,
uint[2] memory,
uint[2] memory,
uint[2] memory,
uint[2] memory,
uint[2] memory
)
{
LedgerStruct.PeerProfile[2] memory peerProfiles = _c.peerProfiles;
return (
[peerProfiles[0].peerAddr, peerProfiles[1].peerAddr],
[peerProfiles[0].deposit, peerProfiles[1].deposit],
[peerProfiles[0].withdrawal, peerProfiles[1].withdrawal],
[peerProfiles[0].state.seqNum, peerProfiles[1].state.seqNum],
[peerProfiles[0].state.transferOut, peerProfiles[1].state.transferOut],
[peerProfiles[0].state.pendingPayOut, peerProfiles[1].state.pendingPayOut]
);
}
/**
* @notice Return channel's dispute timeout
* @param _c the channel to be viewed
* @return channel's dispute timeout
*/
function getDisputeTimeout(LedgerStruct.Channel storage _c) public view returns(uint) { //inject PUBLIC FUNC TO EXTERNAL
return _c.disputeTimeout;
}
/**
* @notice Return channel's migratedTo address
* @param _c the channel to be viewed
* @return channel's migratedTo address
*/
function getMigratedTo(LedgerStruct.Channel storage _c) public view returns(address) { //inject PUBLIC FUNC TO EXTERNAL
return _c.migratedTo;
}
/**
* @notice Return state seqNum map of a duplex channel
* @param _c the channel to be viewed
* @return peers' addresses
* @return two simplex state sequence numbers
*/
function getStateSeqNumMap(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(address[2] memory, uint[2] memory)
{
LedgerStruct.PeerProfile[2] memory peerProfiles = _c.peerProfiles;
return (
[peerProfiles[0].peerAddr, peerProfiles[1].peerAddr],
[peerProfiles[0].state.seqNum, peerProfiles[1].state.seqNum]
);
}
/**
* @notice Return transferOut map of a duplex channel
* @param _c the channel to be viewed
* @return peers' addresses
* @return transferOuts of two simplex channels
*/
function getTransferOutMap(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(address[2] memory, uint[2] memory)
{
LedgerStruct.PeerProfile[2] memory peerProfiles = _c.peerProfiles;
return (
[peerProfiles[0].peerAddr, peerProfiles[1].peerAddr],
[peerProfiles[0].state.transferOut, peerProfiles[1].state.transferOut]
);
}
/**
* @notice Return nextPayIdListHash map of a duplex channel
* @param _c the channel to be viewed
* @return peers' addresses
* @return nextPayIdListHashes of two simplex channels
*/
function getNextPayIdListHashMap(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(address[2] memory, bytes32[2] memory)
{
LedgerStruct.PeerProfile[2] memory peerProfiles = _c.peerProfiles;
return (
[peerProfiles[0].peerAddr, peerProfiles[1].peerAddr],
[peerProfiles[0].state.nextPayIdListHash, peerProfiles[1].state.nextPayIdListHash]
);
}
/**
* @notice Return lastPayResolveDeadline map of a duplex channel
* @param _c the channel to be viewed
* @return peers' addresses
* @return lastPayResolveDeadlines of two simplex channels
*/
function getLastPayResolveDeadlineMap(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(address[2] memory, uint[2] memory)
{
LedgerStruct.PeerProfile[2] memory peerProfiles = _c.peerProfiles;
return (
[peerProfiles[0].peerAddr, peerProfiles[1].peerAddr],
[peerProfiles[0].state.lastPayResolveDeadline, peerProfiles[1].state.lastPayResolveDeadline]
);
}
/**
* @notice Return pendingPayOut map of a duplex channel
* @param _c the channel to be viewed
* @return peers' addresses
* @return pendingPayOuts of two simplex channels
*/
function getPendingPayOutMap(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(address[2] memory, uint[2] memory)
{
LedgerStruct.PeerProfile[2] memory peerProfiles = _c.peerProfiles;
return (
[peerProfiles[0].peerAddr, peerProfiles[1].peerAddr],
[peerProfiles[0].state.pendingPayOut, peerProfiles[1].state.pendingPayOut]
);
}
/**
* @notice Return the withdraw intent info of the channel
* @param _c the channel to be viewed
* @return receiver of the withdraw intent
* @return amount of the withdraw intent
* @return requestTime of the withdraw intent
* @return recipientChannelId of the withdraw intent
*/
function getWithdrawIntent(
LedgerStruct.Channel storage _c
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(address, uint, uint, bytes32)
{
LedgerStruct.WithdrawIntent memory withdrawIntent = _c.withdrawIntent;
return (
withdrawIntent.receiver,
withdrawIntent.amount,
withdrawIntent.requestTime,
withdrawIntent.recipientChannelId
);
}
/**
* @notice Import channel migration arguments from old CelerLedger contract
* @param _c the channel to be viewed
* @param _fromLedgerAddr old ledger address to import channel config from
* @param _channelId ID of the channel to be viewed
* @dev related to Ledger Migration
*/
function _importChannelMigrationArgs(
LedgerStruct.Channel storage _c,
address payable _fromLedgerAddr,
bytes32 _channelId
)
internal
{
uint tokenType;
(
_c.disputeTimeout,
tokenType,
_c.token.tokenAddress,
_c.cooperativeWithdrawSeqNum
) = ICelerLedger(_fromLedgerAddr).getChannelMigrationArgs(_channelId);
_c.token.tokenType = PbEntity.TokenType(tokenType);
}
/**
* @notice import channel peers' migration info from old CelerLedger contract
* @param _c the channel to be viewed
* @param _fromLedgerAddr old ledger address to import channel config from
* @param _channelId ID of the channel to be viewed
* @dev related to Ledger Migration
*/
function _importPeersMigrationInfo(
LedgerStruct.Channel storage _c,
address payable _fromLedgerAddr,
bytes32 _channelId
)
internal
{
(
address[2] memory peersAddrs,
uint[2] memory deposits,
uint[2] memory withdrawals,
uint[2] memory seqNums,
uint[2] memory transferOuts,
uint[2] memory pendingPayOuts
) = ICelerLedger(_fromLedgerAddr).getPeersMigrationInfo(_channelId);
for (uint i = 0; i < 2; i++) {
LedgerStruct.PeerProfile storage peerProfile = _c.peerProfiles[i];
peerProfile.peerAddr = peersAddrs[i];
peerProfile.deposit = deposits[i];
peerProfile.withdrawal = withdrawals[i];
peerProfile.state.seqNum = seqNums[i];
peerProfile.state.transferOut = transferOuts[i];
peerProfile.state.pendingPayOut = pendingPayOuts[i];
}
}
/**
* @notice Get the seqNums of two simplex channel states
* @param _c the channel
*/
function _getStateSeqNums(LedgerStruct.Channel storage _c) internal view returns(uint[2] memory) {
return [_c.peerProfiles[0].state.seqNum, _c.peerProfiles[1].state.seqNum];
}
/**
* @notice Check if _addr is one of the peers in channel _c
* @param _c the channel
* @param _addr the address to check
* @return is peer or not
*/
function _isPeer(LedgerStruct.Channel storage _c, address _addr) internal view returns(bool) {
return _addr == _c.peerProfiles[0].peerAddr || _addr == _c.peerProfiles[1].peerAddr;
}
/**
* @notice Get peer's ID
* @param _c the channel
* @param _peer address of peer
* @return peer's ID
*/
function _getPeerId(LedgerStruct.Channel storage _c, address _peer) internal view returns(uint) {
if (_peer == _c.peerProfiles[0].peerAddr) {
return 0;
} else if (_peer == _c.peerProfiles[1].peerAddr) {
return 1;
} else {
revert("Nonexist peer");
}
}
/**
* @notice Check the correctness of one peer's signature
* @param _c the channel
* @param _h the hash of the message signed by the peer
* @param _sig signature of the peer
* @return message is signed by one of the peers or not
*/
function _checkSingleSignature(
LedgerStruct.Channel storage _c,
bytes32 _h,
bytes memory _sig
)
internal
view
returns(bool)
{
address addr = _h.toEthSignedMessageHash().recover(_sig);
return _isPeer(_c, addr);
}
/**
* @notice Check the correctness of the co-signatures
* @param _c the channel
* @param _h the hash of the message signed by the peers
* @param _sigs signatures of the peers
* @return message are signed by both peers or not
*/
function _checkCoSignatures(
LedgerStruct.Channel storage _c,
bytes32 _h,
bytes[] memory _sigs
)
internal
view
returns(bool)
{
if (_sigs.length != 2) {
return false;
}
// check signature
bytes32 hash = _h.toEthSignedMessageHash();
address addr;
for (uint i = 0; i < 2; i++) {
addr = hash.recover(_sigs[i]);
// enforce the order of sigs consistent with ascending addresses
if (addr != _c.peerProfiles[i].peerAddr) {
return false;
}
}
return true;
}
/**
* @notice Validate channel final balance
* @dev settleBalance = deposit - withdrawal + transferIn - transferOut
* @param _c the channel
* @return (balance is valid, settle balance)
*/
function _validateSettleBalance(LedgerStruct.Channel storage _c)
internal
view
returns(bool, uint[2] memory)
{
LedgerStruct.PeerProfile[2] memory peerProfiles = _c.peerProfiles;
uint[2] memory settleBalance = [
peerProfiles[0].deposit.add(peerProfiles[1].state.transferOut),
peerProfiles[1].deposit.add(peerProfiles[0].state.transferOut)
];
for (uint i = 0; i < 2; i++) {
uint subAmt = peerProfiles[i].state.transferOut.add(peerProfiles[i].withdrawal);
if (settleBalance[i] < subAmt) {
return (false, [uint(0), uint(0)]);
}
settleBalance[i] = settleBalance[i].sub(subAmt);
}
return (true, settleBalance);
}
/**
* @notice Update record of one peer's withdrawal amount
* @param _c the channel
* @param _receiver receiver of this new withdrawal
* @param _amount amount of this new withdrawal
* @param _checkBalance check the balance if this is true
*/
function _addWithdrawal(
LedgerStruct.Channel storage _c,
address _receiver,
uint _amount,
bool _checkBalance
)
internal
{
// this implicitly require receiver be a peer
uint rid = _getPeerId(_c, _receiver);
_c.peerProfiles[rid].withdrawal = _c.peerProfiles[rid].withdrawal.add(_amount);
if (_checkBalance) {
require(getTotalBalance(_c) >= 0);
}
}
}
// File: contracts/lib/data/PbChain.sol
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: chain.proto
pragma solidity ^0.5.0;
library PbChain {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
struct OpenChannelRequest {
bytes channelInitializer; // tag: 1
bytes[] sigs; // tag: 2
} // end struct OpenChannelRequest
function decOpenChannelRequest(bytes memory raw) internal pure returns (OpenChannelRequest memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.sigs = new bytes[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelInitializer = bytes(buf.decBytes());
}
else if (tag == 2) {
m.sigs[cnts[2]] = bytes(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder OpenChannelRequest
struct CooperativeWithdrawRequest {
bytes withdrawInfo; // tag: 1
bytes[] sigs; // tag: 2
} // end struct CooperativeWithdrawRequest
function decCooperativeWithdrawRequest(bytes memory raw) internal pure returns (CooperativeWithdrawRequest memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.sigs = new bytes[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.withdrawInfo = bytes(buf.decBytes());
}
else if (tag == 2) {
m.sigs[cnts[2]] = bytes(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CooperativeWithdrawRequest
struct CooperativeSettleRequest {
bytes settleInfo; // tag: 1
bytes[] sigs; // tag: 2
} // end struct CooperativeSettleRequest
function decCooperativeSettleRequest(bytes memory raw) internal pure returns (CooperativeSettleRequest memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.sigs = new bytes[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.settleInfo = bytes(buf.decBytes());
}
else if (tag == 2) {
m.sigs[cnts[2]] = bytes(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CooperativeSettleRequest
struct ResolvePayByConditionsRequest {
bytes condPay; // tag: 1
bytes[] hashPreimages; // tag: 2
} // end struct ResolvePayByConditionsRequest
function decResolvePayByConditionsRequest(bytes memory raw) internal pure returns (ResolvePayByConditionsRequest memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.hashPreimages = new bytes[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.condPay = bytes(buf.decBytes());
}
else if (tag == 2) {
m.hashPreimages[cnts[2]] = bytes(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder ResolvePayByConditionsRequest
struct SignedSimplexState {
bytes simplexState; // tag: 1
bytes[] sigs; // tag: 2
} // end struct SignedSimplexState
function decSignedSimplexState(bytes memory raw) internal pure returns (SignedSimplexState memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.sigs = new bytes[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.simplexState = bytes(buf.decBytes());
}
else if (tag == 2) {
m.sigs[cnts[2]] = bytes(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder SignedSimplexState
struct SignedSimplexStateArray {
SignedSimplexState[] signedSimplexStates; // tag: 1
} // end struct SignedSimplexStateArray
function decSignedSimplexStateArray(bytes memory raw) internal pure returns (SignedSimplexStateArray memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(1);
m.signedSimplexStates = new SignedSimplexState[](cnts[1]);
cnts[1] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.signedSimplexStates[cnts[1]] = decSignedSimplexState(buf.decBytes());
cnts[1]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder SignedSimplexStateArray
struct ChannelMigrationRequest {
bytes channelMigrationInfo; // tag: 1
bytes[] sigs; // tag: 2
} // end struct ChannelMigrationRequest
function decChannelMigrationRequest(bytes memory raw) internal pure returns (ChannelMigrationRequest memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.sigs = new bytes[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelMigrationInfo = bytes(buf.decBytes());
}
else if (tag == 2) {
m.sigs[cnts[2]] = bytes(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder ChannelMigrationRequest
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// File: contracts/lib/ledgerlib/LedgerOperation.sol
pragma solidity ^0.5.1;
/**
* @title Ledger Operation Library
* @notice CelerLedger library of basic ledger operations
* @dev This library doesn't need "withdraw pattern" because both peers must be
* External Owned Accounts(EOA) since their signatures are required in openChannel.
*/
library LedgerOperation {
using SafeMath for uint;
using Address for address;
using SafeERC20 for IERC20;
using LedgerChannel for LedgerStruct.Channel;
/**
* @notice Open a state channel through auth withdraw message
* @dev library function can't be payable but can read msg.value in caller's context
* @param _self storage data of CelerLedger contract
* @param _openRequest bytes of open channel request message
*/
function openChannel(
LedgerStruct.Ledger storage _self,
bytes calldata _openRequest
)
external
{
PbChain.OpenChannelRequest memory openRequest =
PbChain.decOpenChannelRequest(_openRequest);
PbEntity.PaymentChannelInitializer memory channelInitializer =
PbEntity.decPaymentChannelInitializer(openRequest.channelInitializer);
require(channelInitializer.initDistribution.distribution.length == 2, "Wrong length");
require(block.number <= channelInitializer.openDeadline, "Open deadline passed");
PbEntity.TokenInfo memory token = channelInitializer.initDistribution.token;
uint[2] memory amounts = [
channelInitializer.initDistribution.distribution[0].amt,
channelInitializer.initDistribution.distribution[1].amt
];
address[2] memory peerAddrs = [
channelInitializer.initDistribution.distribution[0].account,
channelInitializer.initDistribution.distribution[1].account
];
// enforce ascending order of peers' addresses to simplify contract code
require(peerAddrs[0] < peerAddrs[1], "Peer addrs are not ascending");
ICelerWallet celerWallet = _self.celerWallet;
bytes32 h = keccak256(openRequest.channelInitializer);
(
bytes32 channelId,
LedgerStruct.Channel storage c
) = _createWallet(_self, celerWallet, peerAddrs, h);
c.disputeTimeout = channelInitializer.disputeTimeout;
_updateChannelStatus(_self, c, LedgerStruct.ChannelStatus.Operable);
c.token = _validateTokenInfo(token);
c.peerProfiles[0].peerAddr = peerAddrs[0];
c.peerProfiles[0].deposit = amounts[0];
c.peerProfiles[1].peerAddr = peerAddrs[1];
c.peerProfiles[1].deposit = amounts[1];
require(c._checkCoSignatures(h, openRequest.sigs), "Check co-sigs failed");
emit OpenChannel(channelId, uint(token.tokenType), token.tokenAddress, peerAddrs, amounts);
uint amtSum = amounts[0].add(amounts[1]);
// if total deposit is 0
if (amtSum == 0) {
require(msg.value == 0, "msg.value is not 0");
return;
}
// if total deposit is larger than 0
if (_self.balanceLimitsEnabled) {
require(amtSum <= _self.balanceLimits[token.tokenAddress], "Balance exceeds limit");
}
if (token.tokenType == PbEntity.TokenType.ETH) {
uint msgValueReceiver = channelInitializer.msgValueReceiver;
require(msg.value == amounts[msgValueReceiver], "msg.value mismatch");
if (amounts[msgValueReceiver] > 0) {
celerWallet.depositETH.value(amounts[msgValueReceiver])(channelId);
}
// peer ID of non-msgValueReceiver
uint pid = uint(1).sub(msgValueReceiver);
if (amounts[pid] > 0) {
_self.ethPool.transferToCelerWallet(
peerAddrs[pid],
address(celerWallet),
channelId,
amounts[pid]
);
}
} else if (token.tokenType == PbEntity.TokenType.ERC20) {
require(msg.value == 0, "msg.value is not 0");
IERC20 erc20Token = IERC20(token.tokenAddress);
for (uint i = 0; i < 2; i++) {
if (amounts[i] == 0) { continue; }
erc20Token.safeTransferFrom(peerAddrs[i], address(this), amounts[i]);
}
erc20Token.safeApprove(address(celerWallet), amtSum);
celerWallet.depositERC20(channelId, address(erc20Token), amtSum);
} else {
assert(false);
}
}
/**
* @notice Deposit ETH or ERC20 tokens into the channel
* @dev total deposit amount = msg.value(must be 0 for ERC20) + _transferFromAmount.
* library function can't be payable but can read msg.value in caller's context.
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
* @param _receiver address of the receiver
* @param _transferFromAmount amount of funds to be transfered from EthPool for ETH
* or ERC20 contract for ERC20 tokens
*/
function deposit(
LedgerStruct.Ledger storage _self,
bytes32 _channelId,
address _receiver,
uint _transferFromAmount
)
public //inject PUBLIC FUNC TO EXTERNAL
{
uint msgValue = msg.value;
// this implicitly require _receiver be a peer
_addDeposit(_self, _channelId, _receiver, _transferFromAmount.add(msgValue));
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
if (c.token.tokenType == PbEntity.TokenType.ETH) {
if (msgValue > 0) {
_self.celerWallet.depositETH.value(msgValue)(_channelId);
}
if (_transferFromAmount > 0) {
_self.ethPool.transferToCelerWallet(
msg.sender,
address(_self.celerWallet),
_channelId,
_transferFromAmount
);
}
} else if (c.token.tokenType == PbEntity.TokenType.ERC20) {
require(msgValue == 0, "msg.value is not 0");
IERC20 erc20Token = IERC20(c.token.tokenAddress);
erc20Token.safeTransferFrom(msg.sender, address(this), _transferFromAmount);
erc20Token.safeApprove(address(_self.celerWallet), _transferFromAmount);
_self.celerWallet.depositERC20(_channelId, address(erc20Token), _transferFromAmount);
} else {
assert(false);
}
}
/**
* @notice Store signed simplex states on-chain as checkpoints
* @dev simplex states in this array are not necessarily in the same channel,
* which means snapshotStates natively supports multi-channel batch processing.
* This function only updates seqNum, transferOut, pendingPayOut of each on-chain
* simplex state. It can't ensure that the pending pays will be cleared during
* settling the channel, which requires users call intendSettle with the same state.
* TODO: wait for Solidity's support to replace SignedSimplexStateArray with bytes[].
* @param _self storage data of CelerLedger contract
* @param _signedSimplexStateArray bytes of SignedSimplexStateArray message
*/
function snapshotStates(
LedgerStruct.Ledger storage _self,
bytes calldata _signedSimplexStateArray
)
external
{
PbChain.SignedSimplexStateArray memory signedSimplexStateArray =
PbChain.decSignedSimplexStateArray(_signedSimplexStateArray);
uint simplexStatesNum = signedSimplexStateArray.signedSimplexStates.length;
// snapshot each state
PbEntity.SimplexPaymentChannel memory simplexState =
PbEntity.decSimplexPaymentChannel(signedSimplexStateArray.signedSimplexStates[0].simplexState);
for (uint i = 0; i < simplexStatesNum; i++) {
bytes32 currentChannelId = simplexState.channelId;
LedgerStruct.Channel storage c = _self.channelMap[currentChannelId];
require(c.status == LedgerStruct.ChannelStatus.Operable, "Channel status error");
bytes32 stateHash = keccak256(signedSimplexStateArray.signedSimplexStates[i].simplexState);
bytes[] memory sigs = signedSimplexStateArray.signedSimplexStates[i].sigs;
require(c._checkCoSignatures(stateHash, sigs), "Check co-sigs failed");
uint peerFromId = c._getPeerId(simplexState.peerFrom);
LedgerStruct.PeerState storage state = c.peerProfiles[peerFromId].state;
require(simplexState.seqNum > state.seqNum, "seqNum error");
// no need to update nextPayIdListHash and lastPayResolveDeadline for snapshot purpose
state.seqNum = simplexState.seqNum;
state.transferOut = simplexState.transferToPeer.receiver.amt;
state.pendingPayOut = simplexState.totalPendingAmount;
if (i == simplexStatesNum.sub(1)) {
emit SnapshotStates(currentChannelId, c._getStateSeqNums());
} else if (i < simplexStatesNum.sub(1)) {
simplexState = PbEntity.decSimplexPaymentChannel(
signedSimplexStateArray.signedSimplexStates[i+1].simplexState
);
// enforce channelIds of simplex states are ascending
require(currentChannelId <= simplexState.channelId, "Non-ascending channelIds");
if (currentChannelId < simplexState.channelId) {
emit SnapshotStates(currentChannelId, c._getStateSeqNums());
}
} else {
assert(false);
}
}
}
/**
* @notice Intend to withdraw funds from channel
* @dev only peers can call intendWithdraw
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
* @param _amount amount of funds to withdraw
* @param _recipientChannelId withdraw to receiver address if 0,
* otherwise deposit to receiver address in the recipient channel
*/
function intendWithdraw(
LedgerStruct.Ledger storage _self,
bytes32 _channelId,
uint _amount,
bytes32 _recipientChannelId
)
public //inject PUBLIC FUNC TO EXTERNAL
{
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
LedgerStruct.PeerProfile[2] storage peerProfiles = c.peerProfiles;
LedgerStruct.WithdrawIntent storage withdrawIntent = c.withdrawIntent;
address receiver = msg.sender;
require(c.status == LedgerStruct.ChannelStatus.Operable, "Channel status error");
// withdrawIntent.receiver is address(0) if and only if there is no pending WithdrawIntent,
// because withdrawIntent.receiver may only be set as msg.sender which can't be address(0).
require(withdrawIntent.receiver == address(0), "Pending withdraw intent exists");
// check withdraw limit
// this implicitly requires receiver be a peer
uint rid = c._getPeerId(receiver);
uint pid = uint(1).sub(rid);
uint withdrawLimit = peerProfiles[rid].deposit
.add(peerProfiles[pid].state.transferOut)
.sub(peerProfiles[rid].withdrawal)
.sub(peerProfiles[rid].state.transferOut)
.sub(peerProfiles[rid].state.pendingPayOut);
require(_amount <= withdrawLimit, "Exceed withdraw limit");
withdrawIntent.receiver = receiver;
withdrawIntent.amount = _amount;
withdrawIntent.requestTime = block.number;
withdrawIntent.recipientChannelId = _recipientChannelId;
emit IntendWithdraw(_channelId, receiver, _amount);
}
/**
* @notice Confirm channel withdrawal
* @dev anyone can confirm a withdrawal intent
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
*/
function confirmWithdraw(
LedgerStruct.Ledger storage _self,
bytes32 _channelId
)
public //inject PUBLIC FUNC TO EXTERNAL
{
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
require(c.status == LedgerStruct.ChannelStatus.Operable, "Channel status error");
require(c.withdrawIntent.receiver != address(0), "No pending withdraw intent");
require(
block.number >= c.withdrawIntent.requestTime.add(c.disputeTimeout),
"Dispute not timeout"
);
address receiver = c.withdrawIntent.receiver;
uint amount = c.withdrawIntent.amount;
bytes32 recipientChannelId = c.withdrawIntent.recipientChannelId;
delete c.withdrawIntent;
// don't need to check balance because intendWithdraw() has already checked withdraw limit
// this implicitly require receiver be a peer
c._addWithdrawal(receiver, amount, false);
(, uint[2] memory deposits, uint[2] memory withdrawals) = c.getBalanceMap();
emit ConfirmWithdraw(_channelId, amount, receiver, recipientChannelId, deposits, withdrawals);
_withdrawFunds(_self, _channelId, receiver, amount, recipientChannelId);
}
/**
* @notice Veto current withdrawal intent
* @dev only peers can veto a withdrawal intent;
* peers can veto a withdrawal intent even after (requestTime + disputeTimeout)
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
*/
function vetoWithdraw(LedgerStruct.Ledger storage _self, bytes32 _channelId) public { //inject PUBLIC FUNC TO EXTERNAL
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
require(c.status == LedgerStruct.ChannelStatus.Operable, "Channel status error");
require(c.withdrawIntent.receiver != address(0), "No pending withdraw intent");
require(c._isPeer(msg.sender), "msg.sender is not peer");
delete c.withdrawIntent;
emit VetoWithdraw(_channelId);
}
/**
* @notice Cooperatively withdraw specific amount of deposit
* @param _self storage data of CelerLedger contract
* @param _cooperativeWithdrawRequest bytes of cooperative withdraw request message
*/
function cooperativeWithdraw(
LedgerStruct.Ledger storage _self,
bytes calldata _cooperativeWithdrawRequest
)
external
{
PbChain.CooperativeWithdrawRequest memory cooperativeWithdrawRequest =
PbChain.decCooperativeWithdrawRequest(_cooperativeWithdrawRequest);
PbEntity.CooperativeWithdrawInfo memory withdrawInfo =
PbEntity.decCooperativeWithdrawInfo(cooperativeWithdrawRequest.withdrawInfo);
bytes32 channelId = withdrawInfo.channelId;
bytes32 recipientChannelId = withdrawInfo.recipientChannelId;
LedgerStruct.Channel storage c = _self.channelMap[channelId];
require(c.status == LedgerStruct.ChannelStatus.Operable, "Channel status error");
bytes32 h = keccak256(cooperativeWithdrawRequest.withdrawInfo);
require(
c._checkCoSignatures(h, cooperativeWithdrawRequest.sigs),
"Check co-sigs failed"
);
// require an increment of exactly 1 for seqNum of each cooperative withdraw request
require(
withdrawInfo.seqNum.sub(c.cooperativeWithdrawSeqNum) == 1,
"seqNum error"
);
require(block.number <= withdrawInfo.withdrawDeadline, "Withdraw deadline passed");
address receiver = withdrawInfo.withdraw.account;
c.cooperativeWithdrawSeqNum = withdrawInfo.seqNum;
uint amount = withdrawInfo.withdraw.amt;
// this implicitly require receiver be a peer
c._addWithdrawal(receiver, amount, true);
(, uint[2] memory deposits, uint[2] memory withdrawals) = c.getBalanceMap();
emit CooperativeWithdraw(
channelId,
amount,
receiver,
recipientChannelId,
deposits,
withdrawals,
withdrawInfo.seqNum
);
_withdrawFunds(_self, channelId, receiver, amount, recipientChannelId);
}
/**
* @notice Intend to settle channel(s) with an array of signed simplex states
* @dev simplex states in this array are not necessarily in the same channel,
* which means intendSettle natively supports multi-channel batch processing.
* A simplex state with non-zero seqNum (non-null state) must be co-signed by both peers,
* while a simplex state with seqNum=0 (null state) only needs to be signed by one peer.
* TODO: wait for Solidity's support to replace SignedSimplexStateArray with bytes[].
* @param _self storage data of CelerLedger contract
* @param _signedSimplexStateArray bytes of SignedSimplexStateArray message
*/
function intendSettle(
LedgerStruct.Ledger storage _self,
bytes calldata _signedSimplexStateArray
)
external
{
PbChain.SignedSimplexStateArray memory signedSimplexStateArray =
PbChain.decSignedSimplexStateArray(_signedSimplexStateArray);
uint simplexStatesNum = signedSimplexStateArray.signedSimplexStates.length;
PbEntity.SimplexPaymentChannel memory simplexState =
PbEntity.decSimplexPaymentChannel(signedSimplexStateArray.signedSimplexStates[0].simplexState);
for (uint i = 0; i < simplexStatesNum; i++) {
bytes32 currentChannelId = simplexState.channelId;
LedgerStruct.Channel storage c = _self.channelMap[currentChannelId];
require(
c.status == LedgerStruct.ChannelStatus.Operable ||
c.status == LedgerStruct.ChannelStatus.Settling,
"Channel status error"
);
require(
c.settleFinalizedTime == 0 || block.number < c.settleFinalizedTime,
"Settle has already finalized"
);
bytes32 stateHash = keccak256(signedSimplexStateArray.signedSimplexStates[i].simplexState);
bytes[] memory sigs = signedSimplexStateArray.signedSimplexStates[i].sigs;
if (simplexState.seqNum > 0) { // non-null state
require(c._checkCoSignatures(stateHash, sigs), "Check co-sigs failed");
uint peerFromId = c._getPeerId(simplexState.peerFrom);
LedgerStruct.PeerState storage state = c.peerProfiles[peerFromId].state;
// ensure each state can be intendSettle at most once
if (c.status == LedgerStruct.ChannelStatus.Operable) {
// "==" is the case of cooperative on-chain checkpoint
require(simplexState.seqNum >= state.seqNum, "seqNum error");
} else if (c.status == LedgerStruct.ChannelStatus.Settling) {
require(simplexState.seqNum > state.seqNum, "seqNum error");
} else {
assert(false);
}
// update simplexState-dependent fields
// no need to update pendingPayOut since channel settle process doesn't use it
state.seqNum = simplexState.seqNum;
state.transferOut = simplexState.transferToPeer.receiver.amt;
state.nextPayIdListHash = simplexState.pendingPayIds.nextListHash;
state.lastPayResolveDeadline = simplexState.lastPayResolveDeadline;
_clearPays(_self, currentChannelId, peerFromId, simplexState.pendingPayIds.payIds);
} else if (simplexState.seqNum == 0) { // null state
// this implies both stored seqNums are 0
require(c.settleFinalizedTime == 0, "intendSettle before");
require(
sigs.length == 1 && c._checkSingleSignature(stateHash, sigs[0]),
"Check sig failed"
);
} else {
assert(false);
}
if (i == simplexStatesNum.sub(1)) {
_updateOverallStatesByIntendState(_self, currentChannelId);
} else if (i < simplexStatesNum.sub(1)) {
simplexState = PbEntity.decSimplexPaymentChannel(
signedSimplexStateArray.signedSimplexStates[i+1].simplexState
);
// enforce channelIds of simplex states are ascending
require(currentChannelId <= simplexState.channelId, "Non-ascending channelIds");
if (currentChannelId < simplexState.channelId) {
_updateOverallStatesByIntendState(_self, currentChannelId);
}
} else {
assert(false);
}
}
}
/**
* @notice Read payment results and add results to corresponding simplex payment channel
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
* @param _peerFrom address of the peer who send out funds
* @param _payIdList bytes of a pay id list
*/
function clearPays(
LedgerStruct.Ledger storage _self,
bytes32 _channelId,
address _peerFrom,
bytes calldata _payIdList
)
external
{
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
require(c.status == LedgerStruct.ChannelStatus.Settling, "Channel status error");
uint peerFromId = c._getPeerId(_peerFrom);
bytes32 listHash = keccak256(_payIdList);
LedgerStruct.PeerState storage state = c.peerProfiles[peerFromId].state;
require(state.nextPayIdListHash == listHash, "List hash mismatch");
PbEntity.PayIdList memory payIdList = PbEntity.decPayIdList(_payIdList);
state.nextPayIdListHash = payIdList.nextListHash;
_clearPays(_self, _channelId, peerFromId, payIdList.payIds);
}
/**
* @notice Confirm channel settlement
* @dev This must be alled after settleFinalizedTime
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
*/
function confirmSettle(
LedgerStruct.Ledger storage _self,
bytes32 _channelId
)
public //inject PUBLIC FUNC TO EXTERNAL
{
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
LedgerStruct.PeerProfile[2] storage peerProfiles = c.peerProfiles;
uint blockNumber = block.number;
require(c.status == LedgerStruct.ChannelStatus.Settling, "Channel status error");
// require no new intendSettle can be called
require(blockNumber >= c.settleFinalizedTime, "Settle is not finalized");
// require channel status of current intendSettle has been finalized,
// namely all payments have already been either cleared or expired
// TODO: here we should use (lastPayResolveDeadline + clear safe margin)
// instead of lastPayResolveDeadline to avoid race condition between clearPays
// and confirmSettle, which may lead to different settle balance. Add this safe
// margin to the value of lastPayResolveDeadline for now as a temporary solution.
require(
(peerProfiles[0].state.nextPayIdListHash == bytes32(0) ||
blockNumber > peerProfiles[0].state.lastPayResolveDeadline) &&
(peerProfiles[1].state.nextPayIdListHash == bytes32(0) ||
blockNumber > peerProfiles[1].state.lastPayResolveDeadline),
"Payments are not finalized"
);
(bool validBalance, uint[2] memory settleBalance) = c._validateSettleBalance();
if (!validBalance) {
_resetDuplexState(_self, c);
emit ConfirmSettleFail(_channelId);
return;
}
_updateChannelStatus(_self, c, LedgerStruct.ChannelStatus.Closed);
emit ConfirmSettle(_channelId, settleBalance);
// Withdrawal from Contracts pattern is needless here,
// because peers need to sign messages which implies that they can't be contracts
_batchTransferOut(
_self,
_channelId,
c.token.tokenAddress,
[peerProfiles[0].peerAddr, peerProfiles[1].peerAddr],
settleBalance
);
}
/**
* @notice Cooperatively settle the channel
* @param _self storage data of CelerLedger contract
* @param _settleRequest bytes of cooperative settle request message
*/
function cooperativeSettle(
LedgerStruct.Ledger storage _self,
bytes calldata _settleRequest
)
external
{
PbChain.CooperativeSettleRequest memory settleRequest =
PbChain.decCooperativeSettleRequest(_settleRequest);
PbEntity.CooperativeSettleInfo memory settleInfo =
PbEntity.decCooperativeSettleInfo(settleRequest.settleInfo);
bytes32 channelId = settleInfo.channelId;
LedgerStruct.Channel storage c = _self.channelMap[channelId];
require(
c.status == LedgerStruct.ChannelStatus.Operable ||
c.status == LedgerStruct.ChannelStatus.Settling,
"Channel status error"
);
bytes32 h = keccak256(settleRequest.settleInfo);
require(c._checkCoSignatures(h, settleRequest.sigs), "Check co-sigs failed");
address[2] memory peerAddrs = [c.peerProfiles[0].peerAddr, c.peerProfiles[1].peerAddr];
require(
settleInfo.seqNum > c.peerProfiles[0].state.seqNum &&
settleInfo.seqNum > c.peerProfiles[1].state.seqNum,
"seqNum error"
);
require(settleInfo.settleDeadline >= block.number, "Settle deadline passed");
// require distribution is consistent with the order of peerAddrs in channel
require(
settleInfo.settleBalance[0].account == peerAddrs[0] &&
settleInfo.settleBalance[1].account == peerAddrs[1],
"Settle accounts mismatch"
);
uint[2] memory settleBalance = [
settleInfo.settleBalance[0].amt,
settleInfo.settleBalance[1].amt
];
require(settleBalance[0].add(settleBalance[1]) == c.getTotalBalance(), "Balance sum mismatch");
_updateChannelStatus(_self, c, LedgerStruct.ChannelStatus.Closed);
emit CooperativeSettle(channelId, settleBalance);
_batchTransferOut(_self, channelId, c.token.tokenAddress, peerAddrs, settleBalance);
}
/**
* @notice Return channel number of given status in this contract
* @param _self storage data of CelerLedger contract
* @param _channelStatus query channel status converted to uint
* @return channel number of the status
*/
function getChannelStatusNum(
LedgerStruct.Ledger storage _self,
uint _channelStatus
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns(uint)
{
return _self.channelStatusNums[_channelStatus];
}
/**
* @notice Return EthPool used by this CelerLedger contract
* @param _self storage data of CelerLedger contract
* @return EthPool address
*/
function getEthPool(LedgerStruct.Ledger storage _self) public view returns(address) { //inject PUBLIC FUNC TO EXTERNAL
return address(_self.ethPool);
}
/**
* @notice Return PayRegistry used by this CelerLedger contract
* @param _self storage data of CelerLedger contract
* @return PayRegistry address
*/
function getPayRegistry(LedgerStruct.Ledger storage _self) public view returns(address) { //inject PUBLIC FUNC TO EXTERNAL
return address(_self.payRegistry);
}
/**
* @notice Return CelerWallet used by this CelerLedger contract
* @param _self storage data of CelerLedger contract
* @return CelerWallet address
*/
function getCelerWallet(LedgerStruct.Ledger storage _self) public view returns(address) { //inject PUBLIC FUNC TO EXTERNAL
return address(_self.celerWallet);
}
/**
* @notice create a wallet for a new channel
* @param _self storage data of CelerLedger contract
* @param _w celer wallet
* @param _peers peers of the new channel
* @param _nonce nonce for creating the wallet
* @return channel id, which is same as the created wallet id
* @return storage pointer of the channel
*/
function _createWallet(
LedgerStruct.Ledger storage _self,
ICelerWallet _w,
address[2] memory _peers,
bytes32 _nonce
)
internal
returns(bytes32, LedgerStruct.Channel storage)
{
address[] memory owners = new address[](2);
owners[0] = _peers[0];
owners[1] = _peers[1];
// it is safe to use abi.encodePacked() with only one dynamic variable
// use walletId as channelId
bytes32 channelId = _w.create(owners, address(this), _nonce);
// 0 is reserved for non-channel indication
require(channelId != bytes32(0), "channelId gets 0");
LedgerStruct.Channel storage c = _self.channelMap[channelId];
// No harm in having this check in case of keccak256 being broken
require(c.status == LedgerStruct.ChannelStatus.Uninitialized, "Occupied channelId");
return (channelId, c);
}
/**
* @notice Internal function to add deposit of a channel
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
* @param _receiver address of the receiver
* @param _amount the amount to be deposited
*/
function _addDeposit(
LedgerStruct.Ledger storage _self,
bytes32 _channelId,
address _receiver,
uint _amount
)
internal
{
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
require(c.status == LedgerStruct.ChannelStatus.Operable, "Channel status error");
// this implicitly require _receiver be a peer
uint rid = c._getPeerId(_receiver);
if (_self.balanceLimitsEnabled) {
require(
_amount.add(c.getTotalBalance()) <= _self.balanceLimits[c.token.tokenAddress],
"Balance exceeds limit"
);
}
c.peerProfiles[rid].deposit = c.peerProfiles[rid].deposit.add(_amount);
(
address[2] memory peerAddrs,
uint[2] memory deposits,
uint[2] memory withdrawals
) = c.getBalanceMap();
emit Deposit(_channelId, peerAddrs, deposits, withdrawals);
}
/**
* @notice Internal function to transfer funds out in batch
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
* @param _tokenAddr address of tokens to be transferred out
* @param _receivers the addresses of token receivers
* @param _amounts the amounts to be transferred
*/
function _batchTransferOut(
LedgerStruct.Ledger storage _self,
bytes32 _channelId,
address _tokenAddr,
address[2] memory _receivers,
uint[2] memory _amounts
)
internal
{
for (uint i = 0; i < 2; i++) {
if (_amounts[i] == 0) { continue; }
_self.celerWallet.withdraw(_channelId, _tokenAddr, _receivers[i], _amounts[i]);
}
}
/**
* @notice Internal function to withdraw funds out of the channel
* @param _self storage data of CelerLedger contract
* @param _channelId ID of the channel
* @param _receiver address of the receiver of the withdrawn funds
* @param _amount the amount of the withdrawn funds
* @param _recipientChannelId ID of the recipient channel
*/
function _withdrawFunds(
LedgerStruct.Ledger storage _self,
bytes32 _channelId,
address _receiver,
uint _amount,
bytes32 _recipientChannelId
)
internal
{
if (_amount == 0) { return; }
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
if (_recipientChannelId == bytes32(0)) {
_self.celerWallet.withdraw(_channelId, c.token.tokenAddress, _receiver, _amount);
} else {
LedgerStruct.Channel storage recipientChannel = _self.channelMap[_recipientChannelId];
require(
c.token.tokenType == recipientChannel.token.tokenType &&
c.token.tokenAddress == recipientChannel.token.tokenAddress,
"Token mismatch of recipient channel"
);
_addDeposit(_self, _recipientChannelId, _receiver, _amount);
// move funds from one channel's wallet to another channel's wallet
_self.celerWallet.transferToWallet(
_channelId,
_recipientChannelId,
c.token.tokenAddress,
_receiver,
_amount
);
}
}
/**
* @notice Reset the state of the channel
* @param _self storage data of CelerLedger contract
* @param _c the channel
*/
function _resetDuplexState(
LedgerStruct.Ledger storage _self,
LedgerStruct.Channel storage _c
)
internal
{
delete _c.settleFinalizedTime;
_updateChannelStatus(_self, _c, LedgerStruct.ChannelStatus.Operable);
delete _c.peerProfiles[0].state;
delete _c.peerProfiles[1].state;
// reset possibly remaining WithdrawIntent freezed by previous intendSettle()
delete _c.withdrawIntent;
}
/**
* @notice Clear payments by their hash array
* @param _self storage data of CelerLedger contract
* @param _channelId the channel ID
* @param _peerId ID of the peer who sends out funds
* @param _payIds array of pay ids to clear
*/
function _clearPays(
LedgerStruct.Ledger storage _self,
bytes32 _channelId,
uint _peerId,
bytes32[] memory _payIds
)
internal
{
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
uint[] memory outAmts = _self.payRegistry.getPayAmounts(
_payIds,
c.peerProfiles[_peerId].state.lastPayResolveDeadline
);
uint totalAmtOut = 0;
for (uint i = 0; i < outAmts.length; i++) {
totalAmtOut = totalAmtOut.add(outAmts[i]);
emit ClearOnePay(_channelId, _payIds[i], c.peerProfiles[_peerId].peerAddr, outAmts[i]);
}
c.peerProfiles[_peerId].state.transferOut =
c.peerProfiles[_peerId].state.transferOut.add(totalAmtOut);
}
/**
* @notice Update overall states of a duplex channel
* @param _self storage data of CelerLedger contract
* @param _channelId the channel ID
*/
function _updateOverallStatesByIntendState(
LedgerStruct.Ledger storage _self,
bytes32 _channelId
)
internal
{
LedgerStruct.Channel storage c = _self.channelMap[_channelId];
c.settleFinalizedTime = block.number.add(c.disputeTimeout);
_updateChannelStatus(_self, c, LedgerStruct.ChannelStatus.Settling);
emit IntendSettle(_channelId, c._getStateSeqNums());
}
/**
* @notice Update status of a channel
* @param _self storage data of CelerLedger contract
* @param _c the channel
* @param _newStatus new channel status
*/
function _updateChannelStatus(
LedgerStruct.Ledger storage _self,
LedgerStruct.Channel storage _c,
LedgerStruct.ChannelStatus _newStatus
)
internal
{
if (_c.status == _newStatus) {
return;
}
// update counter of old status
if (_c.status != LedgerStruct.ChannelStatus.Uninitialized) {
_self.channelStatusNums[uint(_c.status)] = _self.channelStatusNums[uint(_c.status)].sub(1);
}
// update counter of new status
_self.channelStatusNums[uint(_newStatus)] = _self.channelStatusNums[uint(_newStatus)].add(1);
_c.status = _newStatus;
}
/**
* @notice Validate token info
* @param _token token info to be validated
* @return validated token info
*/
function _validateTokenInfo(PbEntity.TokenInfo memory _token)
internal
view
returns(PbEntity.TokenInfo memory)
{
if (_token.tokenType == PbEntity.TokenType.ETH) {
require(_token.tokenAddress == address(0));
} else if (_token.tokenType == PbEntity.TokenType.ERC20) {
require(_token.tokenAddress != address(0));
require(_token.tokenAddress.isContract());
} else {
assert(false);
}
return _token;
}
event OpenChannel(
bytes32 indexed channelId,
uint tokenType,
address indexed tokenAddress,
// TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed
address[2] peerAddrs,
uint[2] initialDeposits
);
// TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed
event Deposit(bytes32 indexed channelId, address[2] peerAddrs, uint[2] deposits, uint[2] withdrawals);
event SnapshotStates(bytes32 indexed channelId, uint[2] seqNums);
event IntendSettle(bytes32 indexed channelId, uint[2] seqNums);
event ClearOnePay(bytes32 indexed channelId, bytes32 indexed payId, address indexed peerFrom, uint amount);
event ConfirmSettle(bytes32 indexed channelId, uint[2] settleBalance);
event ConfirmSettleFail(bytes32 indexed channelId);
event IntendWithdraw(bytes32 indexed channelId, address indexed receiver, uint amount);
event ConfirmWithdraw(
bytes32 indexed channelId,
uint withdrawnAmount,
address indexed receiver,
bytes32 indexed recipientChannelId,
uint[2] deposits,
uint[2] withdrawals
);
event VetoWithdraw(bytes32 indexed channelId);
event CooperativeWithdraw(
bytes32 indexed channelId,
uint withdrawnAmount,
address indexed receiver,
bytes32 indexed recipientChannelId,
uint[2] deposits,
uint[2] withdrawals,
uint seqNum
);
event CooperativeSettle(bytes32 indexed channelId, uint[2] settleBalance);
} | inject PUBLIC FUNC TO EXTERNAL | function getMigratedTo(LedgerStruct.Channel storage _c) public view returns(address) { | 5,426,848 |
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IMintableCollection.sol";
import "./interfaces/IRewardable.sol";
import "./abstract/EmergencyWithdrawable.sol";
import "./UnicStakingERC721.sol";
contract UnicStaking is EmergencyWithdrawable, IRewardable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct StakerInfo {
uint256 nftId;
uint256 amount;
uint256 stakeStartTime;
uint256 lockDays;
uint256 rewardDebt;
address rewardToken;
uint16 multiplier;
}
struct LockMultiplier {
uint16 multiplier;
bool exists;
}
struct RewardPool {
IERC20 rewardToken;
uint256 stakedAmount;
uint256 stakedAmountWithMultipliers;
uint256 totalRewardAmount;
uint256 accRewardPerShare;
uint256 lastRewardAmount;
}
IERC20 private stakingToken;
IMintableCollection private nftCollection;
uint256 public minStakeAmount;
uint256 private nftStartId;
// NFT ID to staker info
mapping(uint256 => StakerInfo) public stakes;
// Each uToken should have its own poolcontracts/UnicStaking.sol:115:9
mapping(address => RewardPool) public pools;
// Mapping from days => multiplier for timelock
mapping(uint256 => LockMultiplier) public lockMultipliers;
uint256 private constant DIV_PRECISION = 1e18;
event AddRewards(address indexed rewardToken, uint256 amount);
event Staked(
address indexed account,
address indexed rewardToken,
uint256 nftId,
uint256 amount,
uint256 lockDays
);
event Harvest(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount);
event Withdraw(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount);
event LogUpdateRewards(address indexed rewardToken, uint256 totalRewards, uint256 accRewardPerShare);
modifier poolExists(address rewardToken) {
require(address(pools[rewardToken].rewardToken) != address(0), "UnicStaking: Pool does not exist");
_;
}
modifier poolNotExists(address rewardToken) {
require(address(pools[rewardToken].rewardToken) == address(0), "UnicStaking: Pool does already exist");
_;
}
constructor(
IERC20 _stakingToken,
IMintableCollection _nftCollection,
uint256 _nftStartId,
uint256 _minStakeAmount
) public {
stakingToken = _stakingToken;
nftCollection = _nftCollection;
nftStartId = _nftStartId;
minStakeAmount = _minStakeAmount;
}
// lockdays are passed as seconds, multiplier in percentage from 100 (e.g. 170 for 70% on top)
function setLockMultiplier(uint256 lockDays, uint16 multiplier) external onlyOwner {
lockMultipliers[lockDays] = LockMultiplier({
multiplier: multiplier,
exists: true
});
}
function setMinStakeAmount(uint256 _minStakeAmount) external onlyOwner {
minStakeAmount = _minStakeAmount;
}
/**
* @param amount Amount of staking tokens
* @param lockDays How many days the staker wants to lock
* @param rewardToken The desired reward token to stake the tokens for (most likely a certain uToken)
*/
function stake(uint256 amount, uint256 lockDays, address rewardToken)
external
poolExists(rewardToken)
{
require(
amount >= minStakeAmount,
"UnicStaking: Amount must be greater than or equal to min stake amount"
);
require(
lockMultipliers[lockDays].exists,
"UnicStaking: Invalid number of lock days specified"
);
updateRewards(rewardToken);
// transfer the staking tokens into the staking pool
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
// now the data of the staker is persisted
StakerInfo storage staker = stakes[nftStartId];
staker.stakeStartTime = block.timestamp;
staker.amount = amount;
staker.lockDays = lockDays;
staker.multiplier = lockMultipliers[lockDays].multiplier;
staker.nftId = nftStartId;
staker.rewardToken = rewardToken;
RewardPool storage pool = pools[rewardToken];
// the amount with lock multiplier applied
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
staker.rewardDebt = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
pool.stakedAmount = pool.stakedAmount.add(amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.add(virtualAmount);
nftStartId = nftStartId.add(1);
nftCollection.mint(msg.sender, nftStartId - 1);
emit Staked(msg.sender, rewardToken, nftStartId - 1, amount, lockDays);
}
function withdraw(uint256 nftId) external {
StakerInfo storage staker = stakes[nftId];
require(address(staker.rewardToken) != address(0), "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may withdraw"
);
require(
(staker.stakeStartTime.add(staker.lockDays)) < block.timestamp,
"UnicStaking: Lock time not expired"
);
RewardPool storage pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
updateRewards(staker.rewardToken);
// lets burn the NFT first
nftCollection.burn(nftId);
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward = accumulated.sub(staker.rewardDebt);
// reset the pool props
pool.stakedAmount = pool.stakedAmount.sub(staker.amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount);
uint256 staked = staker.amount;
// reset all staker props
staker.rewardDebt = 0;
staker.amount = 0;
staker.stakeStartTime = 0;
staker.lockDays = 0;
staker.nftId = 0;
staker.rewardToken = address(0);
stakingToken.safeTransfer(msg.sender, reward.add(staked));
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
emit Withdraw(msg.sender, address(staker.rewardToken), nftId, staked);
}
function updateRewards(address rewardToken) private poolExists(rewardToken) {
RewardPool storage pool = pools[rewardToken];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
if (pool.totalRewardAmount > pool.lastRewardAmount) {
if (pool.stakedAmountWithMultipliers > 0) {
uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount);
pool.accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers));
}
pool.lastRewardAmount = pool.totalRewardAmount;
emit LogUpdateRewards(rewardToken, pool.lastRewardAmount, pool.accRewardPerShare);
}
}
function createPool(address rewardToken) external poolNotExists(rewardToken) {
RewardPool memory pool = RewardPool({
rewardToken: IERC20(rewardToken),
stakedAmount: 0,
stakedAmountWithMultipliers: 0,
totalRewardAmount: 0,
accRewardPerShare: 0,
lastRewardAmount: 0
});
pools[rewardToken] = pool;
}
function addRewards(address rewardToken, uint256 amount) override external poolExists(rewardToken) {
require(amount > 0, "UnicStaking: Amount must be greater than zero");
IERC20(rewardToken).safeTransferFrom(msg.sender, address(this), amount);
RewardPool storage pool = pools[rewardToken];
pool.totalRewardAmount = pool.totalRewardAmount.add(amount);
emit AddRewards(rewardToken, amount);
}
function harvest(uint256 nftId) external {
StakerInfo storage staker = stakes[nftId];
require(staker.nftId > 0, "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may harvest"
);
updateRewards(address(staker.rewardToken));
RewardPool memory pool = pools[address(staker.rewardToken)];
uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward;
// this needs to be considered due to roundings in reward calculation
if (accumulated > staker.rewardDebt) {
reward = accumulated.sub(staker.rewardDebt);
}
staker.rewardDebt = accumulated;
pool.rewardToken.safeTransfer(msg.sender, reward);
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
}
function pendingReward(uint256 nftId) external view returns (uint256) {
StakerInfo memory staker = stakes[nftId];
require(staker.nftId > 0, "StakingPool: No staker exists");
RewardPool memory pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
uint256 accRewardPerShare = 0;
// run a part from the updateRewards logic but don't persist anything
if (pool.totalRewardAmount > pool.lastRewardAmount) {
if (pool.stakedAmountWithMultipliers > 0) {
uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount);
accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers));
}
}
uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(accRewardPerShare).div(DIV_PRECISION);
// this can happen due to roundings in the reward calculation
if (staker.rewardDebt > accumulated) {
return 0;
}
return accumulated.sub(staker.rewardDebt);
}
// returns the virtual amount after having a multiplier applied
function virtualAmount(uint256 amount, uint256 multiplier) private view returns (uint256) {
return amount.mul(multiplier.mul(DIV_PRECISION).div(100)).div(DIV_PRECISION);
}
// returns the stake with multiplier for an nftId
function getStakeWithMultiplier(uint256 nftId) external view returns (uint256 stakeWithMultiplier){
StakerInfo memory staker = stakes[nftId];
stakeWithMultiplier = virtualAmount(staker.amount, staker.multiplier);
}
}
| lets burn the NFT first reset the pool props reset all staker props | function withdraw(uint256 nftId) external {
StakerInfo storage staker = stakes[nftId];
require(address(staker.rewardToken) != address(0), "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may withdraw"
);
require(
(staker.stakeStartTime.add(staker.lockDays)) < block.timestamp,
"UnicStaking: Lock time not expired"
);
RewardPool storage pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
updateRewards(staker.rewardToken);
nftCollection.burn(nftId);
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward = accumulated.sub(staker.rewardDebt);
pool.stakedAmount = pool.stakedAmount.sub(staker.amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount);
uint256 staked = staker.amount;
staker.rewardDebt = 0;
staker.amount = 0;
staker.stakeStartTime = 0;
staker.lockDays = 0;
staker.nftId = 0;
staker.rewardToken = address(0);
stakingToken.safeTransfer(msg.sender, reward.add(staked));
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
emit Withdraw(msg.sender, address(staker.rewardToken), nftId, staked);
}
| 13,132,040 |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "./interfaces/IManaging.sol";
import "../core/DaoConstants.sol";
import "../core/DaoRegistry.sol";
import "../adapters/interfaces/IVoting.sol";
import "../guards/MemberGuard.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
contract ManagingContract is IManaging, DaoConstants, MemberGuard {
struct ProposalDetails {
bytes32 adapterId;
address adapterAddress;
bytes32[] keys;
uint256[] values;
uint128 flags;
}
mapping(address => mapping(bytes32 => ProposalDetails)) public proposals;
/*
* default fallback function to prevent from sending ether to the contract
*/
receive() external payable {
revert("fallback revert");
}
/**
* @notice Creates a proposal to replace, remove or add an adapter.
* @dev If the adapterAddress is equal to 0x0, the adapterId is removed from the registry if available.
* @dev If the adapterAddress is a reserved address, it reverts.
* @dev keys and value must have the same length.
* @dev proposalId can not be reused.
* @param dao The dao address.
* @param proposalId The guild kick proposal id.
* @param adapterId The adapter id to replace, remove or add.
* @param adapterAddress The adapter address to add or replace. Use 0x0 if you want to remove the adapter.
* @param keys The configuration keys for the adapter.
* @param values The values to set for the adapter configuration.
* @param _flags The ACL for the new adapter, up to 2**128-1.
*/
function submitProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes32 adapterId,
address adapterAddress,
bytes32[] calldata keys,
uint256[] calldata values,
uint256 _flags
) external override onlyMember(dao) {
require(
keys.length == values.length,
"must be an equal number of config keys and values"
);
require(_flags < type(uint128).max, "flags parameter overflow");
uint128 flags = uint128(_flags);
require(
isNotReservedAddress(adapterAddress),
"adapter address is reserved address"
);
dao.submitProposal(proposalId);
proposals[address(dao)][proposalId] = ProposalDetails(
adapterId,
adapterAddress,
keys,
values,
flags
);
}
/**
* @notice Sponsor a proposal if the proposal id exists.
* @dev Only members are allowed to sponsor proposals.
* @param dao The dao address.
* @param proposalId The guild kick proposal id.
* @param data Additional data that can be used for offchain voting validation.
*/
function sponsorProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes calldata data
) external override {
IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING));
address sponsoredBy =
votingContract.getSenderAddress(
dao,
address(this),
data,
msg.sender
);
_sponsorProposal(dao, proposalId, data, sponsoredBy, votingContract);
}
function _sponsorProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes memory data,
address sponsoredBy,
IVoting votingContract
) internal {
dao.sponsorProposal(proposalId, sponsoredBy, address(votingContract));
votingContract.startNewVotingForProposal(dao, proposalId, data);
}
/**
* @notice Processes a proposal that was sponsored.
* @dev Only members can process a proposal.
* @dev Only if the voting pass the proposal is processed.
* @dev Reverts when the adapter address is already in use and it is an adapter addition.
* @param dao The dao address.
* @param proposalId The guild kick proposal id.
*/
function processProposal(DaoRegistry dao, bytes32 proposalId)
external
override
{
ProposalDetails memory proposal = proposals[address(dao)][proposalId];
IVoting votingContract = IVoting(dao.votingAdapter(proposalId));
require(address(votingContract) != address(0), "adapter not found");
require(
votingContract.voteResult(dao, proposalId) ==
IVoting.VotingState.PASS,
"proposal did not pass"
);
dao.processProposal(proposalId);
dao.replaceAdapter(
proposal.adapterId,
proposal.adapterAddress,
proposal.flags,
proposal.keys,
proposal.values
);
}
}
| Processes a proposal that was sponsored. Only members can process a proposal. Only if the voting pass the proposal is processed. Reverts when the adapter address is already in use and it is an adapter addition. dao The dao address. proposalId The guild kick proposal id./ | function processProposal(DaoRegistry dao, bytes32 proposalId)
external
override
{
ProposalDetails memory proposal = proposals[address(dao)][proposalId];
IVoting votingContract = IVoting(dao.votingAdapter(proposalId));
require(address(votingContract) != address(0), "adapter not found");
require(
votingContract.voteResult(dao, proposalId) ==
IVoting.VotingState.PASS,
"proposal did not pass"
);
dao.processProposal(proposalId);
dao.replaceAdapter(
proposal.adapterId,
proposal.adapterAddress,
proposal.flags,
proposal.keys,
proposal.values
);
}
| 5,431,873 |
./partial_match/4/0xed9287ca282Cf581a237e95ADFcfB7E49Bd8ED57/sources/auto_pool.sol | user should hold 2500 tokens for qualify for loyalty bonus; return loyalty bonus users | function loyaltyOf() public view returns(uint256){
address _customerAddress = msg.sender;
if(tokenBalanceLedger_[_customerAddress] >= 2000*10**uint256(decimals)){
}
else{
return 0;
}
}
| 16,971,197 |
./partial_match/1/0x9a5132e149c547F254C73226DA7f770d43D9EA44/sources/contracts/periphery/libraries/Path.sol | Skips a token from the buffer and returns the remainder path The swap path return The remaining token elements in the path | function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
| 2,733,422 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract SmartChefMarket is Ownable {
using SafeERC20 for IERC20;
uint public totalTokensPlaced;
uint public lastRewardBlock;
address[] public listRewardTokens;
address market;
struct RewardToken {
uint rewardPerBlock;
uint startBlock;
uint accTokenPerShare; // Accumulated Tokens per share, times 1e12.
uint rewardsForWithdrawal;
bool enabled; // true - enable; false - disable
}
mapping (address => uint) public userNFTPlaced; //How many tokens placed in market by user
mapping (address => mapping(address => uint)) public rewardDebt; //user => (rewardToken => rewardDebt);
mapping (address => RewardToken) public rewardTokens;
event AddNewTokenReward(address token);
event DisableTokenReward(address token);
event ChangeTokenReward(address indexed token, uint rewardPerBlock);
// event StakeTokens(address indexed user, uint amountRB, uint[] tokensId);
// event UnstakeToken(address indexed user, uint amountRB, uint[] tokensId);
event EmergencyWithdraw(address indexed user, uint tokenCount);
modifier onlyMarket(){
require(msg.sender == market, "Only market");
_;
}
function isTokenInList(address _token) internal view returns(bool){
address[] memory _listRewardTokens = listRewardTokens;
bool thereIs = false;
for(uint i = 0; i < _listRewardTokens.length; i++){
if(_listRewardTokens[i] == _token){
thereIs = true;
break;
}
}
return thereIs;
}
function getListRewardTokens() public view returns(address[] memory){
address[] memory list = new address[](listRewardTokens.length);
list = listRewardTokens;
return list;
}
function addNewTokenReward(address _newToken, uint _startBlock, uint _rewardPerBlock) public onlyOwner {
require(_newToken != address(0), "Address shouldn't be 0");
require(isTokenInList(_newToken) == false, "Token is already in the list");
listRewardTokens.push(_newToken);
if(_startBlock == 0){
rewardTokens[_newToken].startBlock = block.number + 1;
} else {
rewardTokens[_newToken].startBlock = _startBlock;
}
rewardTokens[_newToken].rewardPerBlock = _rewardPerBlock;
if(IERC20(_newToken).balanceOf(address(this)) > rewardTokens[_newToken].rewardsForWithdrawal){
rewardTokens[_newToken].enabled = true;
} else {
rewardTokens[_newToken].enabled = false;
}
emit AddNewTokenReward(_newToken);
}
function disableTokenReward(address _token) public onlyOwner {
require(isTokenInList(_token), "Token not in the list");
rewardTokens[_token].enabled = false;
emit DisableTokenReward(_token);
}
function enableTokenReward(address _token, uint _startBlock, uint _rewardPerBlock) public onlyOwner {
require(isTokenInList(_token), "Token not in the list");
require(_startBlock >= block.number, "Start block Must be later than current");
if(IERC20(_token).balanceOf(address(this)) > rewardTokens[_token].rewardsForWithdrawal){
rewardTokens[_token].enabled = true;
rewardTokens[_token].startBlock = _startBlock;
rewardTokens[_token].rewardPerBlock = _rewardPerBlock;
emit ChangeTokenReward(_token, _rewardPerBlock);
} else {
revert("Not enough balance of token");
}
updatePool();
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint _from, uint _to) public pure returns (uint) {
if(_to > _from){
return _to - _from;
} else {
return 0;
}
}
// View function to see pending Reward on frontend.
function pendingReward(address _user) external view returns (address[] memory, uint[] memory) {
uint nftPlaced = userNFTPlaced[_user];
uint[] memory rewards = new uint[](listRewardTokens.length);
if(nftPlaced == 0){
return (listRewardTokens, rewards);
}
uint _totalTokensPlaced = totalTokensPlaced;
uint _multiplier = getMultiplier(lastRewardBlock, block.number);
uint _accTokenPerShare = 0;
for(uint i = 0; i < listRewardTokens.length; i++){
address curToken = listRewardTokens[i];
RewardToken memory curRewardToken = rewardTokens[curToken];
if (_multiplier != 0 && _totalTokensPlaced != 0) {
_accTokenPerShare = curRewardToken.accTokenPerShare +
(_multiplier * curRewardToken.rewardPerBlock * 1e12 / _totalTokensPlaced);
} else {
_accTokenPerShare = curRewardToken.accTokenPerShare;
}
rewards[i] = (nftPlaced * _accTokenPerShare / 1e12) - rewardDebt[_user][curToken];
}
return (listRewardTokens, rewards);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool() public {
uint multiplier = getMultiplier(lastRewardBlock, block.number);
uint _totalTokenPlaced = totalTokensPlaced; //Gas safe
if(multiplier == 0){
return;
}
lastRewardBlock = block.number;
if(_totalTokenPlaced == 0){
return;
}
for(uint i = 0; i < listRewardTokens.length; i++){
address curToken = listRewardTokens[i];
RewardToken memory curRewardToken = rewardTokens[curToken];
if(curRewardToken.enabled == false || curRewardToken.startBlock >= block.number){
continue;
} else {
uint curMultiplier;
if(getMultiplier(curRewardToken.startBlock, block.number) < multiplier){
curMultiplier = getMultiplier(curRewardToken.startBlock, block.number);
} else {
curMultiplier = multiplier;
}
uint tokenReward = curRewardToken.rewardPerBlock * curMultiplier;
rewardTokens[curToken].rewardsForWithdrawal += tokenReward;
rewardTokens[curToken].accTokenPerShare += (tokenReward * 1e12) / _totalTokenPlaced;
}
}
}
function withdrawReward() public {
_withdrawReward(msg.sender);
}
function _updateRewardDebt(address _user) internal {
for(uint i = 0; i < listRewardTokens.length; i++){
rewardDebt[_user][listRewardTokens[i]] = userNFTPlaced[_user] * rewardTokens[listRewardTokens[i]].accTokenPerShare / 1e12;
}
}
function _withdrawReward(address _user) internal {
updatePool();
uint nftPlaced = userNFTPlaced[_user];
address[] memory _listRewardTokens = listRewardTokens;
if(nftPlaced == 0){
return;
}
for(uint i = 0; i < _listRewardTokens.length; i++){
RewardToken storage curRewardToken = rewardTokens[_listRewardTokens[i]];
uint pending = nftPlaced * curRewardToken.accTokenPerShare / 1e12 - rewardDebt[_user][_listRewardTokens[i]];
if(pending > 0){
curRewardToken.rewardsForWithdrawal -= pending;
rewardDebt[_user][_listRewardTokens[i]] = nftPlaced * curRewardToken.accTokenPerShare / 1e12;
IERC20(_listRewardTokens[i]).safeTransfer(address(_user), pending);
}
}
}
function updateStakedTokens(address _user, uint amount) public onlyMarket {
_withdrawReward(_user);
totalTokensPlaced -= userNFTPlaced[_user];
userNFTPlaced[_user] = amount;
totalTokensPlaced += amount;
_updateRewardDebt(_user);
}
// Withdraw reward token. EMERGENCY ONLY.
function emergencyRewardTokenWithdraw(address _token, uint256 _amount) public onlyOwner {
require(IERC20(_token).balanceOf(address(this)) >= _amount, "Not enough balance");
IERC20(_token).safeTransfer(msg.sender, _amount);
}
function setMarket(address _market) public onlyOwner {
market = _market;
}
} | Withdraw reward token. EMERGENCY ONLY. | function emergencyRewardTokenWithdraw(address _token, uint256 _amount) public onlyOwner {
require(IERC20(_token).balanceOf(address(this)) >= _amount, "Not enough balance");
IERC20(_token).safeTransfer(msg.sender, _amount);
}
| 13,016,438 |
pragma solidity ^0.5.0;
//Functionality list
//create posts
//list posts
//tip author posts with crypto
//create new contract / class
contract SocialNetwork {
//variables
string public name;
uint public postCount = 0;
//keep track of unique Posts
mapping(uint => Post) public posts;
//key/value store to write data on the blockchain
//create post data structure
struct Post {
uint id;
string content;
uint tipAmount;
address payable author;
}
//define event to track vaues stored inside of Post object
event PostCreated(
uint id,
string content,
uint tipAmount,
address payable author
);
//
event PostTipped(
uint id,
string content,
uint tipAmount,
address payable author
);
//constructor method
constructor() public {
name = "App Uni Social Network";
}
//Post function
function createPost(string memory _content) public {
//set required check
require(bytes(_content).length > 0);
//connvert _content to bytes array and get its length
//icrement post count
postCount ++;
//instantiate Post and add to mapping to write to blockchain
posts[postCount] = Post(postCount, _content, 0, msg.sender);
//posts is a key value pair, with postCount value === key
//trigger event (same values as createPost function that's being tested)
emit PostCreated(postCount, _content, 0, msg.sender);
}
function tipPost(uint _id) public payable {
//check for valid id
require(_id > 0 && _id <= postCount);
//fetch post
Post memory _post = posts[_id];
//fetch author
address payable _author = _post.author;
//pay author
address(_author).transfer(msg.value);
//increment tip amount
_post.tipAmount = _post.tipAmount + msg.value;
//update post
posts[_id] = _post;
//trigger post
emit PostTipped(postCount, _post.content, _post.tipAmount, _author);
}
} | Post functionset required checkconnvert _content to bytes array and get its lengthicrement post countinstantiate Post and add to mapping to write to blockchainposts is a key value pair, with postCount value === keytrigger event (same values as createPost function that's being tested) | function createPost(string memory _content) public {
require(bytes(_content).length > 0);
postCount ++;
posts[postCount] = Post(postCount, _content, 0, msg.sender);
emit PostCreated(postCount, _content, 0, msg.sender);
}
| 15,850,509 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.7.0;
import "./interfaces/IBank.sol";
import "./interfaces/IPriceOracle.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/Math.sol";
import "hardhat/console.sol";
contract Bank is IBank {
IPriceOracle oracle;
address private hakToken;
address private magic_token = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
struct Balance {
address[] token_address_list;
Account[] borrow_list;
mapping(address => Account) tokens_map;
// mapping(address => Account) borrows_map;
uint256 collateral;
Account eth_act;
}
mapping(address => Balance) private accounts;
constructor(address _priceOracle, address _hakToken) {
oracle = IPriceOracle(_priceOracle);
hakToken = _hakToken;
}
function updateBorrowInterest() private returns (uint256) {
Balance storage user_bal = accounts[msg.sender];
uint256 total = 0;
uint256 arrayLength = user_bal.borrow_list.length;
for (uint256 i = 0; i < arrayLength; i++) {
Account memory updated_token_acc = calculateInterest(
user_bal.borrow_list[i],
block.number,
5
);
user_bal.borrow_list[i] = updated_token_acc;
total =
total +
updated_token_acc.deposit +
updated_token_acc.interest;
}
return total;
}
modifier updateInterest(address token) {
Balance storage user_bal = accounts[msg.sender];
Account memory updated_eth_acc = calculateInterest(
user_bal.eth_act,
block.number,
3
);
accounts[msg.sender].eth_act = updated_eth_acc;
uint256 arrayLength = user_bal.token_address_list.length;
for (uint256 i = 0; i < arrayLength; i++) {
Account memory updated_token_acc = calculateInterest(
user_bal.tokens_map[user_bal.token_address_list[i]],
block.number,
3
);
user_bal.tokens_map[
user_bal.token_address_list[i]
] = updated_token_acc;
// totalValue += mappedUsers[addressIndices[i]];
}
_;
}
// TODO: maybe we can use calldata instead of memory
function calculateInterest(
Account memory account,
uint256 current_block,
uint256 interest
) private view returns (Account memory) {
uint256 passed_block = current_block - account.lastInterestBlock;
if (passed_block < 0) revert("Can not go back to past");
uint256 tem = DSMath.mul(interest, passed_block);
// uint256 amt_interest = ((3 * passed_block) / 10000); // TODO: Recheck // .03
uint256 added_interest = DSMath.mul(account.deposit, tem) / 10000;
// revert(added_interest);
return
Account(
account.deposit,
account.interest + added_interest,
current_block
);
}
function isValidContract(address token)
private
view
returns (bool isContract)
{
uint32 size;
assembly {
size := extcodesize(token)
}
return (size > 0);
}
modifier OnlyIfValidToken(address token) {
if (token != magic_token && isValidContract(token) == false) {
revert("token not supported");
}
_;
}
function deposit(address token, uint256 amount)
external
payable
override
OnlyIfValidToken(token)
updateInterest(token)
returns (bool)
{
// TODO: check for negative or 0
if (token == magic_token) {
accounts[msg.sender].eth_act.deposit =
accounts[msg.sender].eth_act.deposit +
amount;
if (accounts[msg.sender].eth_act.lastInterestBlock == 0) {
accounts[msg.sender].eth_act.lastInterestBlock = block.number;
}
return true;
} else {
IERC20 iecr20 = IERC20(token);
if (iecr20.allowance(msg.sender, address(this)) < amount) {
return false;
}
// TODO: Only set this value if money substraction was successful
// TODO: Add thread safety. Should we????
accounts[msg.sender].token_address_list.push(token);
accounts[msg.sender].tokens_map[token].deposit =
accounts[msg.sender].tokens_map[token].deposit +
amount;
if (accounts[msg.sender].tokens_map[token].lastInterestBlock == 0) {
accounts[msg.sender].tokens_map[token].lastInterestBlock = block
.number;
}
return
IERC20(token).transferFrom(msg.sender, address(this), amount);
}
// emit Deposit(msg.sender, token, amount);
// return true;
}
function getBalance(address token) public view override returns (uint256) {
// todo check if key is present in map
if (token == magic_token) {
Account memory updated = calculateInterest(
accounts[msg.sender].eth_act,
block.number,
3
);
return updated.deposit + updated.interest;
} else {
Account memory updated = calculateInterest(
accounts[msg.sender].tokens_map[token],
block.number,
3
);
return updated.deposit + updated.interest;
}
}
function check_balance(uint256 cur_balance, uint256 to_withdraw)
private
pure
{
if (cur_balance == 0) {
revert("no balance");
}
if (cur_balance < to_withdraw) {
revert("amount exceeds balance");
}
}
//TODO: Check interest
function withdraw(address token, uint256 amount)
external
override
OnlyIfValidToken(token)
updateInterest(token)
returns (uint256)
{
// TODO: Check negative
// TODO: Check can not withdraw more than balance
uint256 to_withdraw = 0;
if (token == magic_token) {
if (amount == 0) {
// if zero, then we withdraw all the money
to_withdraw =
accounts[msg.sender].eth_act.deposit +
accounts[msg.sender].eth_act.interest;
} else {
to_withdraw = amount;
}
// TODO: make thread safe
uint256 cur_balance = accounts[msg.sender].eth_act.deposit +
accounts[msg.sender].eth_act.interest;
check_balance(cur_balance, to_withdraw);
if (to_withdraw <= accounts[msg.sender].eth_act.interest) {
accounts[msg.sender].eth_act.interest =
accounts[msg.sender].eth_act.interest -
to_withdraw;
} else {
accounts[msg.sender].eth_act.deposit =
accounts[msg.sender].eth_act.deposit -
(to_withdraw - accounts[msg.sender].eth_act.interest);
accounts[msg.sender].eth_act.interest = 0;
}
emit Withdraw(msg.sender, token, to_withdraw);
return to_withdraw;
} else {
if (amount == 0) {
// if zero, then we withdraw all the money
to_withdraw =
accounts[msg.sender].tokens_map[token].deposit +
accounts[msg.sender].tokens_map[token].interest;
} else {
to_withdraw = amount;
}
// TODO: make thread safe
uint256 cur_balance = accounts[msg.sender]
.tokens_map[token]
.deposit + accounts[msg.sender].tokens_map[token].interest;
check_balance(cur_balance, to_withdraw);
if (
to_withdraw <= accounts[msg.sender].tokens_map[token].interest
) {
accounts[msg.sender].tokens_map[token].interest =
accounts[msg.sender].tokens_map[token].interest -
to_withdraw;
} else {
accounts[msg.sender].tokens_map[token].deposit =
accounts[msg.sender].tokens_map[token].deposit -
(to_withdraw -
accounts[msg.sender].tokens_map[token].interest);
accounts[msg.sender].tokens_map[token].interest = 0;
}
emit Withdraw(msg.sender, token, to_withdraw);
return to_withdraw;
}
}
function borrow(address token, uint256 amount)
external
override
OnlyIfValidToken(token)
updateInterest(token)
returns (uint256)
{
if (token != magic_token) {
revert("");
}
if (accounts[msg.sender].token_address_list.length == 0) {
revert("no collateral deposited");
}
uint256 cur_balance = 0;
Balance storage user_bal = accounts[msg.sender];
uint256 arrayLength = user_bal.token_address_list.length;
for (uint256 i = 0; i < arrayLength; i++) {
cur_balance =
cur_balance +
user_bal.tokens_map[user_bal.token_address_list[i]].deposit +
user_bal.tokens_map[user_bal.token_address_list[i]].interest;
}
Account memory borrow_item = Account(amount, 0, block.number);
user_bal.borrow_list.push(borrow_item);
user_bal.collateral = (cur_balance * 10000) / updateBorrowInterest();
emit Borrow(msg.sender, token, amount, user_bal.collateral);
return user_bal.collateral;
}
function repay(address token, uint256 amount)
external
payable
override
OnlyIfValidToken(token)
returns (uint256)
{}
function liquidate(address token, address account)
external
payable
override
returns (bool)
{}
function getCollateralRatio(address token, address account)
public
view
override
returns (uint256)
{
return accounts[msg.sender].collateral;
}
}
| TODO: check for negative or 0 | function deposit(address token, uint256 amount)
external
payable
override
OnlyIfValidToken(token)
updateInterest(token)
returns (bool)
{
if (token == magic_token) {
accounts[msg.sender].eth_act.deposit =
accounts[msg.sender].eth_act.deposit +
amount;
if (accounts[msg.sender].eth_act.lastInterestBlock == 0) {
accounts[msg.sender].eth_act.lastInterestBlock = block.number;
}
return true;
IERC20 iecr20 = IERC20(token);
if (iecr20.allowance(msg.sender, address(this)) < amount) {
return false;
}
accounts[msg.sender].tokens_map[token].deposit =
accounts[msg.sender].tokens_map[token].deposit +
amount;
if (accounts[msg.sender].tokens_map[token].lastInterestBlock == 0) {
accounts[msg.sender].tokens_map[token].lastInterestBlock = block
.number;
}
return
IERC20(token).transferFrom(msg.sender, address(this), amount);
}
| 15,798,812 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.