file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// Verified by Darwinia Network
// hevm: flattened sources of src/ItemBase.sol
pragma solidity >0.4.13 >=0.4.23 >=0.4.24 <0.7.0 >=0.6.7 <0.7.0;
////// lib/ds-auth/src/auth.sol
// 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.4.23; */
interface DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) external view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
////// lib/ds-math/src/math.sol
/// math.sol -- mixin for inline numerical wizardry
// 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.4.13; */
contract DSMath {
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");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
////// lib/ds-stop/lib/ds-note/src/note.sol
/// note.sol -- the `note' modifier, for logging calls as events
// 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.4.23; */
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
uint256 wad;
assembly {
foo := calldataload(4)
bar := calldataload(36)
wad := callvalue()
}
_;
emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data);
}
}
////// lib/ds-stop/src/stop.sol
/// stop.sol -- mixin for enable/disable functionality
// Copyright (C) 2017 DappHub, LLC
// 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.4.23; */
/* import "ds-auth/auth.sol"; */
/* import "ds-note/note.sol"; */
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped, "ds-stop-is-stopped");
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
////// lib/zeppelin-solidity/src/proxy/Initializable.sol
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
/* 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;
}
}
////// src/interfaces/IELIP002.sol
/* pragma solidity ^0.6.7; */
/**
@title IELIP002
@dev See https://github.com/evolutionlandorg/furnace/blob/main/elip-002.md
@author [email protected]
*/
interface IELIP002 {
struct Item {
// index of `Formula`
uint256 index;
// strength rate
uint128 rate;
uint16 objClassExt;
uint16 class;
uint16 grade;
// element prefer
uint16 prefer;
// major material
address major;
uint256 id;
// amount of minor material
address minor;
uint256 amount;
}
/**
@dev `Enchanted` MUST emit when item is enchanted.
The `user` argument MUST be the address of an account/contract that is approved to make the enchant (SHOULD be msg.sender).
The `tokenId` argument MUST be token Id of the item which it is enchanted.
The `index` argument MUST be index of the `Formula`.
The `rate` argument MUST be rate of minor material.
The `objClassExt` argument MUST be extension of `ObjectClass`.
The `class` argument MUST be class of the item.
The `grade` argument MUST be grade of the item.
The `prefer` argument MUST be prefer of the item.
The `major` argument MUST be token address of major material.
The `id` argument MUST be token id of major material.
The `minor` argument MUST be token address of minor material.
The `amount` argument MUST be token amount of minor material.
The `now` argument MUST be timestamp of enchant.
*/
event Enchanced(
address indexed user,
uint256 indexed tokenId,
uint256 index,
uint128 rate,
uint16 objClassExt,
uint16 class,
uint16 grade,
uint16 prefer,
address major,
uint256 id,
address minor,
uint256 amount,
uint256 now
);
/**
@dev `Disenchanted` MUST emit when item is disenchanted.
The `user` argument MUST be the address of an account/contract that is approved to make the disenchanted (SHOULD be msg.sender).
The `tokenId` argument MUST be token Id of the item which it is disenchated.
The `majors` argument MUST be major token addresses of major material.
The `id` argument MUST be token ids of major material.
The `minor` argument MUST be token addresses of minor material.
The `amount` argument MUST be token amounts of minor material.
*/
event Disenchanted(
address indexed user,
uint256 tokenId,
address major,
uint256 id,
address minor,
uint256 amount
);
/**
@notice Caller must be owner of tokens to enchant.
@dev Enchant function, Enchant a new NFT token from ERC721 tokens and ERC20 tokens. Enchant rule is according to `Formula`.
MUST revert if `_index` is not in `formula`.
MUST revert on any other error.
@param _index Index of formula to enchant.
@param _id ID of NFT tokens.
@param _token Address of FT token.
@return {
"tokenId": "New Token ID of Enchanting."
}
*/
function enchant(
uint256 _index,
uint256 _id,
address _token
) external returns (uint256);
// {
// ### smelt
// 1. check Formula rule by index
// 2. transfer FT and NFT to address(this)
// 3. track FTs NFT to new NFT
// 4. mint new NFT to caller
// }
/**
@notice Caller must be owner of token id to disenchat.
@dev Disenchant function, A enchanted NFT can be disenchanted into origin ERC721 tokens and ERC20 tokens recursively.
MUST revert on any other error.
@param _id Token ID to disenchant.
@param _depth Depth of disenchanting recursively.
*/
function disenchant(uint256 _id, uint256 _depth) external;
// {
// ### disenchant
// 1. tranfer _id to address(this)
// 2. burn new NFT
// 3. delete track FTs NFTs to new NFT
// 4. transfer FNs NFTs to owner
// }
/**
@dev Get base info of item.
@param _tokenId Token id of item.
@return {
"objClassExt": "Extension of `ObjectClass`.",
"class": "Class of the item.",
"grade": "Grade of the item."
}
*/
function getBaseInfo(uint256 _tokenId)
external
view
returns (
uint16,
uint16,
uint16
);
/**
@dev Get rate of item.
@param _tokenId Token id of item.
@param _element Element item prefer.
@return {
"rate": "strength rate of item."
}
*/
function getRate(uint256 _tokenId, uint256 _element)
external
view
returns (uint256);
function getPrefer(uint256 _tokenId)
external
view
returns (uint16);
function getObjectClassExt(uint256 _tokenId)
external
view
returns (uint16);
}
////// src/interfaces/IFormula.sol
/* pragma solidity ^0.6.7; */
/**
@title IFormula
@author [email protected]
*/
interface IFormula {
struct FormulaEntry {
// item name
bytes32 name;
// strength rate
uint128 rate;
// extension of `ObjectClass`
uint16 objClassExt;
uint16 class;
uint16 grade;
bool canDisenchant;
// if it is removed
// uint256 enchantTime;
// uint256 disenchantTime;
// uint256 loseRate;
bool disable;
// minor material info
bytes32 minor;
uint256 amount;
// major material info
// [address token, uint16 objectClassExt, uint16 class, uint16 grade]
address majorAddr;
uint16 majorObjClassExt;
uint16 majorClass;
uint16 majorGrade;
}
event AddFormula(
uint256 indexed index,
bytes32 name,
uint128 rate,
uint16 objClassExt,
uint16 class,
uint16 grade,
bool canDisenchant,
bytes32 minor,
uint256 amount,
address majorAddr,
uint16 majorObjClassExt,
uint16 majorClass,
uint16 majorGrade
);
event DisableFormula(uint256 indexed index);
event EnableFormula(uint256 indexed index);
/**
@notice Only governance can add `formula`.
@dev Add a formula rule.
MUST revert if length of `_majors` is not the same as length of `_class`.
MUST revert if length of `_minors` is not the same as length of `_mins` and `_maxs.
MUST revert on any other error.
@param _name New enchanted NFT name.
@param _rate New enchanted NFT rate.
@param _objClassExt New enchanted NFT objectClassExt.
@param _class New enchanted NFT class.
@param _grade New enchanted NFT grade.
@param _minor FT Token address of minor meterail for enchanting.
@param _amount FT Token amount of minor meterail for enchanting.
@param _majorAddr FT token address of major meterail for enchanting.
@param _majorObjClassExt FT token objectClassExt of major meterail for enchanting.
@param _majorClass FT token class of major meterail for enchanting.
@param _majorGrade FT token grade of major meterail for enchanting.
*/
function insert(
bytes32 _name,
uint128 _rate,
uint16 _objClassExt,
uint16 _class,
uint16 _grade,
bool _canDisenchant,
bytes32 _minor,
uint256 _amount,
address _majorAddr,
uint16 _majorObjClassExt,
uint16 _majorClass,
uint16 _majorGrade
) external;
/**
@notice Only governance can enable `formula`.
@dev Enable a formula rule.
MUST revert on any other error.
@param _index index of formula.
*/
function disable(uint256 _index) external;
/**
@notice Only governance can disble `formula`.
@dev Disble a formula rule.
MUST revert on any other error.
@param _index index of formula.
*/
function enable(uint256 _index) external;
/**
@dev Returns the length of the formula.
0x1f7b6d32
*/
function length() external view returns (uint256);
/**
@dev Returns the availability of the formula.
*/
function isDisable(uint256 _index) external view returns (bool);
/**
@dev returns the minor material of the formula.
*/
function getMinor(uint256 _index)
external
view
returns (bytes32, uint256);
/**
@dev Decode major info of the major.
0x6ef2fd27
@return {
"token": "Major token address.",
"objClassExt": "Major token objClassExt.",
"class": "Major token class.",
"grade": "Major token address."
}
*/
function getMajorInfo(uint256 _index)
external
view
returns (
address,
uint16,
uint16,
uint16
);
/**
@dev Returns meta info of the item.
0x78533046
@return {
"objClassExt": "Major token objClassExt.",
"class": "Major token class.",
"grade": "Major token address.",
"base": "Base strength rate.",
"enhance": "Enhance strength rate.",
}
*/
function getMetaInfo(uint256 _index)
external
view
returns (
uint16,
uint16,
uint16,
uint128
);
/**
@dev returns canDisenchant of the formula.
*/
function canDisenchant(uint256 _index) external view returns (bool);
}
////// src/interfaces/IMetaDataTeller.sol
/* pragma solidity ^0.6.7; */
interface IMetaDataTeller {
function addTokenMeta(
address _token,
uint16 _grade,
uint112 _strengthRate
) external;
function getObjClassExt(address _token, uint256 _id) external view returns (uint16 objClassExt);
//0xf666196d
function getMetaData(address _token, uint256 _id)
external
view
returns (uint16, uint16, uint16);
//0x7999a5cf
function getPrefer(bytes32 _minor, address _token) external view returns (uint256);
//0x33281815
function getRate(
address _token,
uint256 _id,
uint256 _index
) external view returns (uint256);
//0xf8350ed0
function isAllowed(address _token, uint256 _id) external view returns (bool);
}
////// src/interfaces/IObjectOwnership.sol
/* pragma solidity ^0.6.7; */
interface IObjectOwnership {
function mintObject(address _to, uint128 _objectId) external returns (uint256 _tokenId);
function burn(address _to, uint256 _tokenId) external;
}
////// src/interfaces/ISettingsRegistry.sol
/* pragma solidity ^0.6.7; */
interface ISettingsRegistry {
function uintOf(bytes32 _propertyName) external view returns (uint256);
function stringOf(bytes32 _propertyName) external view returns (string memory);
function addressOf(bytes32 _propertyName) external view returns (address);
function bytesOf(bytes32 _propertyName) external view returns (bytes memory);
function boolOf(bytes32 _propertyName) external view returns (bool);
function intOf(bytes32 _propertyName) external view returns (int);
function setUintProperty(bytes32 _propertyName, uint _value) external;
function setStringProperty(bytes32 _propertyName, string calldata _value) external;
function setAddressProperty(bytes32 _propertyName, address _value) external;
function setBytesProperty(bytes32 _propertyName, bytes calldata _value) external;
function setBoolProperty(bytes32 _propertyName, bool _value) external;
function setIntProperty(bytes32 _propertyName, int _value) external;
function getValueTypeOf(bytes32 _propertyName) external view returns (uint /* SettingsValueTypes */ );
event ChangeProperty(bytes32 indexed _propertyName, uint256 _type);
}
////// src/ItemBase.sol
/* pragma solidity ^0.6.7; */
/* import "ds-math/math.sol"; */
/* import "ds-stop/stop.sol"; */
/* import "zeppelin-solidity/proxy/Initializable.sol"; */
/* import "./interfaces/IELIP002.sol"; */
/* import "./interfaces/IFormula.sol"; */
/* import "./interfaces/ISettingsRegistry.sol"; */
/* import "./interfaces/IMetaDataTeller.sol"; */
/* import "./interfaces/IObjectOwnership.sol"; */
contract ItemBase is Initializable, DSStop, DSMath, IELIP002 {
// 0x434f4e54524143545f4d455441444154415f54454c4c45520000000000000000
bytes32 public constant CONTRACT_METADATA_TELLER =
"CONTRACT_METADATA_TELLER";
// 0x434f4e54524143545f464f524d554c4100000000000000000000000000000000
bytes32 public constant CONTRACT_FORMULA = "CONTRACT_FORMULA";
// 0x434f4e54524143545f4f424a4543545f4f574e45525348495000000000000000
bytes32 public constant CONTRACT_OBJECT_OWNERSHIP =
"CONTRACT_OBJECT_OWNERSHIP";
//0x434f4e54524143545f4c505f454c454d454e545f544f4b454e00000000000000
bytes32 public constant CONTRACT_LP_ELEMENT_TOKEN =
"CONTRACT_LP_ELEMENT_TOKEN";
//0x434f4e54524143545f454c454d454e545f544f4b454e00000000000000000000
bytes32 public constant CONTRACT_ELEMENT_TOKEN = "CONTRACT_ELEMENT_TOKEN";
// rate precision
uint128 public constant RATE_PRECISION = 10**8;
// save about 200 gas when contract create
bytes4 private constant _SELECTOR_TRANSFERFROM =
bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 private constant _SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
/*** STORAGE ***/
uint128 public lastItemObjectId;
ISettingsRegistry public registry;
mapping(uint256 => Item) public tokenId2Item;
// mapping(uint256 => mapping(uint256 => uint256)) public tokenId2Rate;
/**
* @dev Same with constructor, but is used and called by storage proxy as logic contract.
*/
function initialize(address _registry) public initializer {
owner = msg.sender;
emit LogSetOwner(msg.sender);
registry = ISettingsRegistry(_registry);
// trick test
// lastItemObjectId = 1000000;
}
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) private {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(_SELECTOR_TRANSFERFROM, from, to, value)); // solhint-disable-line
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Furnace: TRANSFERFROM_FAILED"
);
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'Furnace: TRANSFER_FAILED');
}
function enchant(
uint256 _index,
uint256 _id,
address _token
) external override stoppable returns (uint256) {
address teller = registry.addressOf(CONTRACT_METADATA_TELLER);
address formula = registry.addressOf(CONTRACT_FORMULA);
require(
IFormula(formula).isDisable(_index) == false,
"Furnace: FORMULA_DISABLE"
);
(address majorAddr, uint16 originClass, uint16 originPrefer) =
_dealMajor(teller, formula, _index, _id);
(uint16 prefer, uint256 amount) =
_dealMinor(teller, formula, _index, _token);
if (originClass > 0) {
require(prefer == originPrefer, "Furnace: INVALID_PREFER");
}
return _enchanceItem(formula, _index, prefer, majorAddr, _id, _token, amount);
}
function _dealMajor(
address teller,
address formula,
uint256 _index,
uint256 _id
) private returns (address, uint16, uint16) {
(
address majorAddress,
uint16 majorObjClassExt,
uint16 majorClass,
uint16 majorGrade
) = IFormula(formula).getMajorInfo(_index);
(uint16 objectClassExt, uint16 class, uint16 grade) =
IMetaDataTeller(teller).getMetaData(majorAddress, _id);
require(
objectClassExt == majorObjClassExt,
"Furnace: INVALID_OBJECTCLASSEXT"
);
require(class == majorClass, "Furnace: INVALID_CLASS");
require(grade == majorGrade, "Furnace: INVALID_GRADE");
_safeTransferFrom(majorAddress, msg.sender, address(this), _id);
uint16 prefer = 0;
if (class > 0) {
prefer = getPrefer(_id);
}
return (majorAddress, class, prefer);
}
function _dealMinor(
address teller,
address formula,
uint256 _index,
address _token
) private returns (uint16, uint256) {
(bytes32 minor, uint256 amount) = IFormula(formula).getMinor(_index);
uint16 prefer = 0;
uint256 element = IMetaDataTeller(teller).getPrefer(minor, _token);
require(element > 0 && element < 6, "Furnace: INVALID_MINOR");
prefer |= uint16(1 << element);
require(amount <= uint128(-1), "Furnace: VALUE_OVERFLOW");
_safeTransferFrom(_token, msg.sender, address(this), amount);
return (prefer, amount);
}
function _enchanceItem(
address formula,
uint256 _index,
uint16 _prefer,
address _major,
uint256 _id,
address _minor,
uint256 _amount
) private returns (uint256) {
lastItemObjectId += 1;
require(lastItemObjectId <= uint128(-1), "Furnace: OBJECTID_OVERFLOW");
(uint16 objClassExt, uint16 class, uint16 grade, uint128 rate) =
IFormula(formula).getMetaInfo(_index);
Item memory item =
Item({
index: _index,
rate: rate,
objClassExt: objClassExt,
class: class,
grade: grade,
prefer: _prefer,
major: _major,
id: _id,
minor: _minor,
amount: _amount
});
uint256 tokenId =
IObjectOwnership(registry.addressOf(CONTRACT_OBJECT_OWNERSHIP))
.mintObject(msg.sender, lastItemObjectId);
tokenId2Item[tokenId] = item;
emit Enchanced(
msg.sender,
tokenId,
item.index,
item.rate,
item.objClassExt,
item.class,
item.grade,
item.prefer,
item.major,
item.id,
item.minor,
item.amount,
now // solhint-disable-line
);
return tokenId;
}
function _disenchantItem(address to, uint256 tokenId) private {
IObjectOwnership(registry.addressOf(CONTRACT_OBJECT_OWNERSHIP)).burn(
to,
tokenId
);
delete tokenId2Item[tokenId];
}
function disenchant(uint256 _id, uint256 _depth)
external
override
stoppable
{
_safeTransferFrom(
registry.addressOf(CONTRACT_OBJECT_OWNERSHIP),
msg.sender,
address(this),
_id
);
_disenchant(_id, _depth);
}
function _disenchant(uint256 _tokenId, uint256 _depth)
private
{
(
uint16 class,
bool canDisenchant,
address major,
uint256 id,
address minor,
uint256 amount
) = getEnchantedInfo(_tokenId);
require(_depth > 0, "Furnace: INVALID_DEPTH");
require(canDisenchant == true, "Furnace: DISENCHANT_DISABLE");
require(class > 0, "Furnace: INVALID_CLASS");
_disenchantItem(address(this), _tokenId);
if (_depth == 1 || class == 0) {
_safeTransferFrom(major, address(this), msg.sender, id);
} else {
_disenchant(id, _depth - 1);
}
_safeTransfer(minor, msg.sender, amount);
emit Disenchanted(msg.sender, _tokenId, major, id, minor, amount);
}
function getRate(uint256 _tokenId, uint256 _element)
public
view
override
returns (uint256)
{
Item storage item = tokenId2Item[_tokenId];
if (uint256(item.prefer) & (1 << _element) > 0) {
return uint256(item.rate);
}
return uint256(item.rate / 2);
}
function getBaseInfo(uint256 _tokenId)
public
view
override
returns (
uint16,
uint16,
uint16
)
{
Item storage item = tokenId2Item[_tokenId];
return (item.objClassExt, item.class, item.grade);
}
function getPrefer(uint256 _tokenId) public view override returns (uint16) {
return tokenId2Item[_tokenId].prefer;
}
function getObjectClassExt(uint256 _tokenId)
public
view
override
returns (uint16)
{
return tokenId2Item[_tokenId].objClassExt;
}
function getEnchantedInfo(uint256 _tokenId)
public
view
returns (
uint16,
bool,
address,
uint256,
address,
uint256
)
{
Item storage item = tokenId2Item[_tokenId];
return (
item.class,
IFormula(registry.addressOf(CONTRACT_FORMULA)).canDisenchant(item.index),
item.major,
item.id,
item.minor,
item.amount
);
}
}
|
Same with constructor, but is used and called by storage proxy as logic contract./ trick test lastItemObjectId = 1000000;
|
function getMetaInfo(uint256 _index)
external
view
returns (
uint16,
uint16,
uint16,
uint128
);
@dev returns canDisenchant of the formula.
function canDisenchant(uint256 _index) external view returns (bool);
}
}
}
}
function initialize(address _registry) public initializer {
owner = msg.sender;
emit LogSetOwner(msg.sender);
registry = ISettingsRegistry(_registry);
}
| 441,371 |
// v7
/**
* Presale.sol
*/
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
* @param a First number
* @param b Second number
*/
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.
* @param a First number
* @param b Second number
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
* @param a First number
* @param b Second number
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
* @param a First number
* @param b Second number
*/
function add(uint256 a, uint256 b) internal pure 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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// interface to the crowdsale contract
interface CrowdSale {
function crowdSaleCheck() external view returns (bool);
}
/**
* @title InvestorsStorage
* @dev InvestorStorage contract interface with newInvestment and getInvestedAmount functions which need to be implemented
*/
interface InvestorsStorage {
function newInvestment(address _investor, uint256 _amount) external;
function getInvestedAmount(address _investor) external view returns (uint256);
}
/**
* @title TokenContract
* @dev Token contract interface with transfer and balanceOf functions which need to be implemented
*/
interface TokenContract {
/**
* @dev Transfer funds to recipient address
* @param _recipient Recipients address
* @param _amount Amount to transfer
*/
function transfer(address _recipient, uint256 _amount) external returns (bool);
/**
* @dev Return balance of holders address
* @param _holder Holders address
*/
function balanceOf(address _holder) external view returns (uint256);
}
/**
* @title PreSale
* @dev PreSale Contract which executes and handles presale of the tokens
*/
contract PreSale is Ownable {
using SafeMath for uint256;
// variables
TokenContract public tkn;
CrowdSale public cSale;
InvestorsStorage public investorsStorage;
uint256 public levelEndDate;
uint256 public currentLevel;
uint256 public levelTokens = 375000;
uint256 public tokensSold;
uint256 public weiRised;
uint256 public ethPrice;
address[] public investorsList;
bool public presalePaused;
bool public presaleEnded;
uint256[12] private tokenPrice = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48];
uint256 private baseTokens = 375000;
uint256 private usdCentValue;
uint256 private minInvestment;
/**
* @dev Constructor of Presale contract
*/
constructor() public {
tkn = TokenContract(0x95c5bf2e68b76F2276221A8FFc9c47a49E9405Ec); // address of the token contract
investorsStorage = InvestorsStorage(0x15c7c30B980ef442d3C811A30346bF9Dd8906137); // address of the storage contract
minInvestment = 100 finney;
updatePrice(5000);
}
/**
* @dev Fallback payable function which executes additional checks and functionality when tokens need to be sent to the investor
*/
function() payable public {
require(msg.value >= minInvestment); // check for minimum investment amount
require(!presalePaused);
require(!presaleEnded);
prepareSell(msg.sender, msg.value);
}
/**
* @dev Prepare sell of the tokens
* @param _investor Investors address
* @param _amount Amount invested
*/
function prepareSell(address _investor, uint256 _amount) private {
uint256 remaining;
uint256 pricePerCent;
uint256 pricePerToken;
uint256 toSell;
uint256 amount = _amount;
uint256 sellInWei;
address investor = _investor;
pricePerCent = getUSDPrice();
pricePerToken = pricePerCent.mul(tokenPrice[currentLevel]); // calculate the price for each token in the current level
toSell = _amount.div(pricePerToken); // calculate the amount to sell
if (toSell < levelTokens) { // if there is enough tokens left in the current level, sell from it
levelTokens = levelTokens.sub(toSell);
weiRised = weiRised.add(_amount);
executeSell(investor, toSell, _amount);
owner.transfer(_amount);
} else { // if not, sell from 2 or more different levels
while (amount > 0) {
if (toSell > levelTokens) {
toSell = levelTokens; // sell all the remaining in the level
sellInWei = toSell.mul(pricePerToken);
amount = amount.sub(sellInWei);
if (currentLevel < 11) { // if is the last level, sell only the tokens left,
currentLevel += 1;
levelTokens = baseTokens;
} else {
remaining = amount;
amount = 0;
}
} else {
sellInWei = amount;
amount = 0;
}
executeSell(investor, toSell, sellInWei);
weiRised = weiRised.add(sellInWei);
owner.transfer(amount);
if (amount > 0) {
toSell = amount.div(pricePerToken);
}
if (remaining > 0) { // if there is any mount left, it means that is the the last level an there is no more tokens to sell
investor.transfer(remaining);
owner.transfer(address(this).balance);
presaleEnded = true;
}
}
}
}
/**
* @dev Execute sell of the tokens - send investor to investors storage and transfer tokens
* @param _investor Investors address
* @param _tokens Amount of tokens to be sent
* @param _weiAmount Amount invested in wei
*/
function executeSell(address _investor, uint256 _tokens, uint256 _weiAmount) private {
uint256 totalTokens = _tokens * (10 ** 18);
tokensSold += _tokens; // update tokens sold
investorsStorage.newInvestment(_investor, _weiAmount); // register the invested amount in the storage
require(tkn.transfer(_investor, totalTokens)); // transfer the tokens to the investor
emit NewInvestment(_investor, totalTokens);
}
/**
* @dev Getter for USD price of tokens
*/
function getUSDPrice() private view returns (uint256) {
return usdCentValue;
}
/**
* @dev Change USD price of tokens
* @param _ethPrice New Ether price
*/
function updatePrice(uint256 _ethPrice) private {
uint256 centBase = 1 * 10 ** 16;
require(_ethPrice > 0);
ethPrice = _ethPrice;
usdCentValue = centBase.div(_ethPrice);
}
/**
* @dev Set USD to ETH value
* @param _ethPrice New Ether price
*/
function setUsdEthValue(uint256 _ethPrice) onlyOwner external { // set the ETH value in USD
updatePrice(_ethPrice);
}
/**
* @dev Set the crowdsale contract address
* @param _crowdSale Crowdsale contract address
*/
function setCrowdSaleAddress(address _crowdSale) onlyOwner public { // set the crowdsale contract address
cSale = CrowdSale(_crowdSale);
}
/**
* @dev Set the storage contract address
* @param _investorsStorage Investors storage contract address
*/
function setStorageAddress(address _investorsStorage) onlyOwner public { // set the storage contract address
investorsStorage = InvestorsStorage(_investorsStorage);
}
/**
* @dev Pause the presale
* @param _paused Paused state - true/false
*/
function pausePresale(bool _paused) onlyOwner public { // pause the presale
presalePaused = _paused;
}
/**
* @dev Get funds
*/
function getFunds() onlyOwner public { // request the funds
owner.transfer(address(this).balance);
}
event NewInvestment(address _investor, uint256 tokens);
}
|
InvestorsStorage InvestorStorage contract interface with newInvestment and getInvestedAmount functions which need to be implemented/
|
interface InvestorsStorage {
function newInvestment(address _investor, uint256 _amount) external;
function getInvestedAmount(address _investor) external view returns (uint256);
}
| 6,461,322 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./interfaces/IPancakeRouter02.sol";
import "./interfaces/IAlpacaToken.sol";
import "hardhat/console.sol";
interface IFarm {
function userInfo(uint256 _pid, address _user) external view returns (uint256 amount, uint256 rewardDebt, uint256 bonusDebt, uint256 fundedBy);
}
interface ITreasury {
function notifyExternalReward(uint256 _amount) external;
}
interface IFairLaunch {
function pendingAlpaca(uint256 _pid, address _user) external view returns (uint256);
function deposit(address _for, uint256 _pid, uint256 _amount) external;
function withdraw(address _for, uint256 _pid, uint256 _amount) external;
function withdrawAll(address _for, uint256 _pid) external;
function harvest(uint256 _pid) external;
}
interface IVault {
/// @dev Add more ERC20 to the bank. Hope to get some good returns.
function deposit(uint256 amountToken) external;
/// @dev Withdraw ERC20 from the bank by burning the share tokens.
function withdraw(uint256 share) external;
}
contract iSwapStrategyAlpaca is Ownable, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
bool public isAutoComp; // this vault is purely for staking. eg. WBNB-BDO staking vault.
bool public strategyStopped = false;
bool public checkForUnlockReward = false;
address public vaultContractAddress; // address of vault.
address public farmContractAddress; // address of farm, eg, PCS, Thugs etc.
uint256 public pid; // pid of pool in farmContractAddress
address public wantAddress;
address public earnedAddress;
address public routerAddress = address(0x10ED43C718714eb63d5aA57B78B54704E256024E); // PancakeSwap: Router
address public operator;
address public strategist;
bool public notPublic = false; // allow public to call earn() function
uint256 public lastEarnBlock = 0;
uint256 public wantLockedTotal = 0;
uint256 public sharesTotal = 0;
uint256 public controllerFee = 100; // 100 = 1%
uint256 public constant CONTROLLER_FEE_UL = 100; // 0.5% is the max entrance fee settable. UL = upper limit
uint256 public constant CONTROLLER_FEE_DENOMINATOR = 10000;
uint256 public entranceFeeFactor = 0; // 0% entrance fee (goes to pool + prevents front-running)
uint256 public constant ENTRANCE_FEE_FACTOR_MAX = 10000; // 100 = 1%
uint256 public constant ENTRANCE_FEE_FACTOR_LL = 500; // 0.5% is the max entrance fee settable. LL = lower limit
address[] public earnedToWantPath;
address[] public earnedToBusdPath;
address[] public wantToEarnedPath;
event Deposit(uint256 amount);
event Withdraw(uint256 amount);
event Farm(uint256 amount);
event Compound(address token0Address, uint256 token0Amt, address token1Address, uint256 token1Amt);
event Earned(address earnedAddress, uint256 earnedAmt);
event BuyBack(address earnedAddress, address buyBackToken, uint256 earnedAmt, uint256 buyBackAmt, address receiver);
event DistributeFee(address earnedAddress, uint256 fee, address receiver);
event ConvertDustToEarned(address tokenAddress, address earnedAddress, uint256 tokenAmt);
event InCaseTokensGetStuck(address tokenAddress, uint256 tokenAmt, address receiver);
event ExecuteTransaction(address indexed target, uint256 value, string signature, bytes data);
// _controller: iVaultBank
// _buyBackToken1Info[]: buyBackToken1, buyBackAddress1, buyBackToken1MidRouteAddress
// _buyBackToken2Info[]: buyBackToken2, buyBackAddress2, buyBackToken2MidRouteAddress
// _token0Info[]: token0Address, token0MidRouteAddress
// _token1Info[]: token1Address, token1MidRouteAddress
constructor(
address _controller,
bool _isAutoComp,
address _vaultContractAddress,
address _farmContractAddress,
uint256 _pid,
address _wantAddress,
address _earnedAddress,
address _routerAddress
) {
operator = msg.sender;
strategist = msg.sender;
// to call earn if public not allowed
isAutoComp = _isAutoComp;
wantAddress = _wantAddress;
if (_routerAddress != address(0)) routerAddress = _routerAddress;
if (isAutoComp) {
vaultContractAddress = _vaultContractAddress;
farmContractAddress = _farmContractAddress;
pid = _pid;
earnedAddress = _earnedAddress;
routerAddress = _routerAddress;
earnedToBusdPath = [_earnedAddress, address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56)]; // BUSD Address
earnedToWantPath = [_earnedAddress, _wantAddress];
wantToEarnedPath = [_wantAddress, _earnedAddress];
}
transferOwnership(_controller);
}
receive() external payable {}
fallback() external payable {}
modifier onlyOperator() {
require(operator == msg.sender, "iSwapStrategyAlpaca: caller is not the operator");
_;
}
modifier onlyStrategist() {
require(strategist == msg.sender || operator == msg.sender, "iSwapStrategyAlpaca: caller is not the strategist");
_;
}
modifier strategyRunning() {
require(!strategyStopped, "iSwapStrategyAlpaca: strategy is not running");
_;
}
function isAuthorised(address _account) public view returns (bool) {
return (_account == operator) || (msg.sender == strategist);
}
// Receives new deposits from user
function deposit(address, uint256 _wantAmt) public onlyOwner whenNotPaused strategyRunning returns (uint256) {
IERC20(wantAddress).safeTransferFrom(address(msg.sender), address(this), _wantAmt);
uint256 sharesAdded = _wantAmt;
if (wantLockedTotal > 0) {
sharesAdded = _wantAmt * sharesTotal * entranceFeeFactor / wantLockedTotal / ENTRANCE_FEE_FACTOR_MAX;
}
sharesTotal = sharesTotal + sharesAdded;
if (isAutoComp) {
_farm();
} else {
wantLockedTotal = wantLockedTotal + _wantAmt;
}
emit Deposit(_wantAmt);
return sharesAdded;
}
function farm() public nonReentrant strategyRunning {
_farm();
}
function _farm() internal {
// add to vault to get ibToken
uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this));
wantLockedTotal = wantLockedTotal + wantAmt;
IERC20(wantAddress).safeIncreaseAllowance(vaultContractAddress, wantAmt);
IVault(vaultContractAddress).deposit(wantAmt);
// add ibToken to farm contract
uint256 ibWantAmt = IERC20(vaultContractAddress).balanceOf(address(this));
IERC20(vaultContractAddress).safeIncreaseAllowance(farmContractAddress, ibWantAmt);
IFairLaunch(farmContractAddress).deposit(address(this), pid, ibWantAmt);
emit Farm(wantAmt);
}
function withdraw(address, uint256 _wantAmt) public onlyOwner nonReentrant returns (uint256) {
require(_wantAmt > 0, "iSwapStrategyAlpaca: !_wantAmt");
if (isAutoComp && !strategyStopped) {
IFairLaunch(farmContractAddress).withdraw(address(this), pid, _wantAmt);
IVault(vaultContractAddress).withdraw(_wantAmt);
}
uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this));
if (_wantAmt > wantAmt) {
_wantAmt = wantAmt;
}
if (wantLockedTotal < _wantAmt) {
_wantAmt = wantLockedTotal;
}
uint256 sharesRemoved = _wantAmt * sharesTotal / wantLockedTotal;
if (sharesRemoved > sharesTotal) {
sharesRemoved = sharesTotal;
}
sharesTotal = sharesTotal - sharesRemoved;
wantLockedTotal = wantLockedTotal - _wantAmt;
IERC20(wantAddress).safeTransfer(address(msg.sender), _wantAmt);
emit Withdraw(_wantAmt);
return sharesRemoved;
}
// 1. Harvest farm tokens
// 2. Converts farm tokens into want tokens
// 3. Deposits want tokens
function earn() public whenNotPaused {
require(isAutoComp, "iSwapStrategyAlpaca: !isAutoComp");
require(!notPublic || isAuthorised(msg.sender), "iSwapStrategyAlpaca: !authorised");
// Harvest farm tokens
IFairLaunch(farmContractAddress).harvest(pid);
// Check if there is any unlocked amount
if (checkForUnlockReward) {
if (IAlpacaToken(earnedAddress).canUnlockAmount(address(this)) > 0) {
IAlpacaToken(earnedAddress).unlock();
}
}
// Converts farm tokens into want tokens
uint256 earnedAmt = IERC20(earnedAddress).balanceOf(address(this));
emit Earned(earnedAddress, earnedAmt);
uint256 _distributeFee = distributeFees(earnedAmt);
earnedAmt = earnedAmt - _distributeFee;
IERC20(earnedAddress).safeIncreaseAllowance(routerAddress, earnedAmt);
if (earnedAddress != wantAddress) {
// Swap half earned to token0
IPancakeRouter02(routerAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(earnedAmt, 0, earnedToWantPath, address(this), block.timestamp + 60);
}
// Get want tokens, ie. add liquidity
uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this));
if (wantAmt > 0) {
emit Compound(wantAddress, wantAmt, address (0), 0);
}
lastEarnBlock = block.number;
_farm();
}
function distributeFees(uint256 _earnedAmt) internal returns (uint256 _fee) {
if (_earnedAmt > 0) {
// Performance fee
if (controllerFee > 0) {
_fee = _earnedAmt * controllerFee / CONTROLLER_FEE_DENOMINATOR;
IERC20(earnedAddress).safeTransfer(operator, _fee);
emit DistributeFee(earnedAddress, _fee, operator);
}
}
}
function convertDustToEarned() public whenNotPaused {
require(isAutoComp, "iSwapStrategyAlpaca: !isAutoComp");
// Converts dust tokens into earned tokens, which will be reinvested on the next earn().
// Converts token0 dust (if any) to earned tokens
uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this));
if (wantAddress != earnedAddress && wantAmt > 0) {
IERC20(wantAddress).safeIncreaseAllowance(routerAddress, wantAmt);
// Swap all dust tokens to earned tokens
IPancakeRouter02(routerAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(wantAmt, 0, wantToEarnedPath, address(this), block.timestamp + 60);
emit ConvertDustToEarned(wantAddress, earnedAddress, wantAmt);
}
}
function uniExchangeRate(uint256 _tokenAmount, address[] memory _path) public view returns (uint256) {
uint256[] memory amounts = IPancakeRouter02(routerAddress).getAmountsOut(_tokenAmount, _path);
return amounts[amounts.length - 1];
}
function pendingHarvest() public view returns (uint256) {
uint256 _earnedBal = IERC20(earnedAddress).balanceOf(address(this));
return IFairLaunch(farmContractAddress).pendingAlpaca(pid, address(this)) + _earnedBal;
}
function pendingHarvestDollarValue() public view returns (uint256) {
uint256 _pending = pendingHarvest();
return (_pending == 0) ? 0 : uniExchangeRate(_pending, earnedToBusdPath);
}
function balanceInPool() public view returns (uint256) {
(uint256 amount, , , ) = IFarm(farmContractAddress).userInfo(pid, address (this));
return amount;
}
function pause() external onlyOperator {
_pause();
}
function unpause() external onlyOperator {
_unpause();
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setStrategist(address _strategist) external onlyOperator {
strategist = _strategist;
}
function setEntranceFeeFactor(uint256 _entranceFeeFactor) external onlyOperator {
require(_entranceFeeFactor > ENTRANCE_FEE_FACTOR_LL, "iSwapStrategyAlpaca: !safe - too low");
require(_entranceFeeFactor <= ENTRANCE_FEE_FACTOR_MAX, "iSwapStrategyAlpaca: !safe - too high");
entranceFeeFactor = _entranceFeeFactor;
}
function setControllerFee(uint256 _controllerFee) external onlyOperator {
require(_controllerFee <= CONTROLLER_FEE_UL, "iSwapStrategyAlpaca: too high");
controllerFee = _controllerFee;
}
function setNotPublic(bool _notPublic) external onlyOperator {
notPublic = _notPublic;
}
function setCheckForUnlockReward(bool _checkForUnlockReward) external onlyOperator {
checkForUnlockReward = _checkForUnlockReward;
}
function setRouterAddress(address _routerAddress) external onlyOperator {
routerAddress = _routerAddress;
}
function inCaseTokensGetStuck(address _token, uint256 _amount, address _to) external onlyOperator {
require(_token != earnedAddress, "!safe");
require(_token != wantAddress, "!safe");
IERC20(_token).safeTransfer(_to, _amount);
emit InCaseTokensGetStuck(_token, _amount, _to);
}
function emergencyWithraw() external onlyOperator {
(uint256 _wantAmt, , , ) = IFarm(farmContractAddress).userInfo(pid, address (this));
IFairLaunch(farmContractAddress).withdraw(address(this), pid, _wantAmt);
IVault(vaultContractAddress).withdraw(_wantAmt);
strategyStopped = true;
}
function resumeStrategy() external onlyOperator {
strategyStopped = false;
farm();
}
}
|
Harvest farm tokens Check if there is any unlocked amount Swap half earned to token0
|
function earn() public whenNotPaused {
require(isAutoComp, "iSwapStrategyAlpaca: !isAutoComp");
require(!notPublic || isAuthorised(msg.sender), "iSwapStrategyAlpaca: !authorised");
IFairLaunch(farmContractAddress).harvest(pid);
if (checkForUnlockReward) {
if (IAlpacaToken(earnedAddress).canUnlockAmount(address(this)) > 0) {
IAlpacaToken(earnedAddress).unlock();
}
}
emit Earned(earnedAddress, earnedAmt);
uint256 _distributeFee = distributeFees(earnedAmt);
earnedAmt = earnedAmt - _distributeFee;
IERC20(earnedAddress).safeIncreaseAllowance(routerAddress, earnedAmt);
if (earnedAddress != wantAddress) {
IPancakeRouter02(routerAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(earnedAmt, 0, earnedToWantPath, address(this), block.timestamp + 60);
}
if (wantAmt > 0) {
emit Compound(wantAddress, wantAmt, address (0), 0);
}
lastEarnBlock = block.number;
_farm();
}
| 13,068,890 |
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
import "./BDERC1155Tradable.sol";
import "./IWarrior.sol";
import "./IRegion.sol";
//Import ERC1155 standard for utilizing FAME tokens
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
///@title LootChestCollectible
///@notice The contract for managing BattleDrome Loot Chest Tokens
contract LootChestCollectible is BDERC1155Tradable, ERC1155Holder {
//////////////////////////////////////////////////////////////////////////////////////////
// Config
//////////////////////////////////////////////////////////////////////////////////////////
//Fungible Token Tiers
enum ChestType {
NULL,
BRONZE,
SILVER,
GOLD,
DIAMOND
}
//Chest level multipliers are used in math throughout, this is done by taking the integerized value of ChestType
//ie:
// bronze = 1
// silver = 2
// gold = 3
// diamond = 4
//And then taking 2 ^ ({val}-1)
//So the resulting multipliers would be for example:
// bronze = 1
// silver = 2
// gold = 4
// diamond = 8
//Chest Contents Constants
//Base value is multiplied by the appropriate chest level multiplier
uint constant FIXED_VALUE_BASE = 125;
//Chance Constants - chance/10000 eg: 100.00%
//This applies to the bronze level chests, each subsequent chest has chances multiplied by it's multiplier
uint constant CHANCE_BONUS_10 = 500; //5% - Bronze, 10% - Silver, 20% - Gold, 40% - Diamond
uint constant CHANCE_BONUS_25 = 200; //2% - Bronze, 4% - Silver, 8% - Gold, 16% - Diamond
uint constant CHANCE_BONUS_50 = 100; //1% - Bronze, 2% - Silver, 4% - Gold, 8% - Diamond
uint constant CHANCE_BONUS_WARRIOR = 100; //1% - Bronze, 2% - Silver, 4% - Gold, 8% - Diamond
uint constant CHANCE_BONUS_REGION = 5; //0.05% - Bronze, 0.1% - Silver, 0.2% - Gold, 0.4% - Diamond
//Costing Constants
uint constant ICO_BASE_FAME_VALUE = 10000000 gwei;
uint constant NEW_FAME_PER_OLD = 1000;
uint constant NEW_FAME_ICO_VALUE = ICO_BASE_FAME_VALUE / NEW_FAME_PER_OLD;
uint constant VOLUME_DISCOUNT_PERCENT = 1; //Cost break when increasing tier when calculating cost of a chest tier
//ie: this percentage is multiplied by the multiplier, and applied as a discount to price
uint constant MIN_DEMAND_RATIO = 5000; //Percent * 10000 similar to chances above
uint constant MAX_DEMAND_RATIO = 20000; //Percent * 10000 similar to chances above
//Other Misc Config Constants
uint8 constant RECENT_SALES_TO_TRACK = 64; //Max of last 32 sales
uint constant RECENT_SALES_TIME_SECONDS = 86400 * 30; //Max of last 30 days
//////////////////////////////////////////////////////////////////////////////////////////
// Structs
//////////////////////////////////////////////////////////////////////////////////////////
struct ChestSale {
uint64 timestamp;
uint8 chest_type;
uint32 quantity;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Local Storage Variables
//////////////////////////////////////////////////////////////////////////////////////////
//Associated Contracts
IERC1155 FAMEContract;
uint256 FAMETokenID;
IWarrior WarriorContract;
IRegion RegionContract;
//Sales History (Demand Tracking)
ChestSale[RECENT_SALES_TO_TRACK] recentSales;
uint currentSaleIndex = 0;
//////////////////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////////////////
constructor(address _proxyRegistryAddress)
BDERC1155Tradable(
"LootChestCollectible",
"BDLC",
_proxyRegistryAddress,
"https://metadata.battledrome.io/api/erc1155-loot-chest/"
)
{
}
//////////////////////////////////////////////////////////////////////////////////////////
// Errors
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice The contract does not have sufficient FAME to support `requested` chests of type `chestType`, maximum of `maxPossible` can be created with current balance.
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param requested The number of chests requested
*@param maxPossible The maximum number of chests of the requested type that can be created with current balance
*/
error InsufficientContractBalance(uint8 chestType, uint256 requested, uint256 maxPossible);
/**
*@notice Insufficient Ether sent for the requested action. You sent `sent` Wei but `required` Wei was required
*@param sent The amount of Ether (in Wei) that was sent by the caller
*@param required The amount of Ether (in Wei) that was actually required for the requested action
*/
error InsufficientEther(uint256 sent, uint256 required);
/**
*@notice Insufficient Chests of type: `chestType`, you only have `balance` chests of that type!
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param balance The number of chests the user currently has of the specified type
*/
error InsufficientChests(uint8 chestType, uint256 balance);
/**
*@notice Error minting new Warrior NFT!
*@param code Error Code
*/
error ErrorMintingWarrior(uint code);
/**
*@notice Error minting new Region NFT!
*@param code Error Code
*/
error ErrorMintingRegion(uint code);
//////////////////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Indicates that a user `opener` opened `quantity` chests of type `chestType` at `timeStamp`
*@param opener The address that opened the chests
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests opened in this event
*@param timeStamp the timestamp that the chests were opened
*@param fame The amount of FAME found in the box(s)
*@param warriors The number of warriors found in the box(s)
*@param regions The number of regions found in the box(s)
*/
event LootBoxOpened(address indexed opener, uint8 indexed chestType, uint32 quantity, uint32 timeStamp, uint32 fame, uint32 warriors, uint32 regions);
//////////////////////////////////////////////////////////////////////////////////////////
// ERC1155 Overrides/Functions
//////////////////////////////////////////////////////////////////////////////////////////
function contractURI() public pure returns (string memory) {
return "https://metadata.battledrome.io/contract/erc1155-loot-chest";
}
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) public override returns (bytes4) {
require(
(
(msg.sender == address(FAMEContract) && _id == FAMETokenID) || //Allow reciept of FAME tokens
msg.sender == address(RegionContract) || //Allow Region Contract to send us Region NFTs (to forward to users)
msg.sender == address(this) //Allow any internal transaction originated here
),
"INVALID_TOKEN!" //Otherwise kick back INVALID_TOKEN error code, preventing the transfer.
);
bytes4 rv = super.onERC1155Received(_operator, _from, _id, _amount, _data);
return rv;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(BDERC1155Tradable, ERC1155Receiver)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Loot Box Buy/Sell
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Buy a number of chests of the specified type, paying ETH
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests to buy
*/
function buy(ChestType chestType, uint quantity) public payable {
//First, is it possible to buy the proposed chests? If not, then revert to prevent people wasting money
uint maxCreatable = maxSafeCreatable(chestType);
if(maxCreatable >= quantity){
//We have sufficient balance to create at least the requested amount
//So calculate the required price of the requested chests:
uint price = getPrice(chestType) * quantity;
//Did the user send enough?
if(msg.value>=price){
//Good, they paid enough... Let's mint their chests then!
_mint(msg.sender, uint(chestType), quantity, "");
tokenSupply[uint(chestType)] = tokenSupply[uint(chestType)] + quantity; //Because we're bypassing the normal mint function.
ChestSale storage saleRecord = recentSales[(currentSaleIndex++)%RECENT_SALES_TO_TRACK];
saleRecord.timestamp = uint64(block.timestamp);
saleRecord.chest_type = uint8(chestType);
saleRecord.quantity = uint32(quantity);
//Check if they overpaid and refund:
if(msg.value>price){
payable(msg.sender).transfer(msg.value-price);
}
}else{
//Bad monkey! Not enough money!
revert InsufficientEther(msg.value,price);
}
}else{
//Insufficient balance, throw error:
revert InsufficientContractBalance(uint8(chestType), quantity, maxCreatable);
}
}
/**
*@notice Sell a number of FAME back to the contract, in exchange for whatever the current payout is.
*@param quantity The number of FAME to sell
*/
function sell(uint quantity) public {
uint payOutAmount = getBuyBackPrice(quantity);
transferFAME(msg.sender,address(this),quantity);
require(address(this).balance>=payOutAmount,"CONTRACT BALANCE ERROR!");
if(payOutAmount>0) payable(msg.sender).transfer(payOutAmount);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Loot Box Opening
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Open a number of your owned chests of the specified type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests to open
*@return fameReward The amount of FAME found in the chests
*@return warriors The number of bonus Warriors found in the chests
*@return regions The number of bonus Regions found in the chests
*/
function open(ChestType chestType, uint quantity) public ownersOnly(uint(chestType)) returns (uint fameReward, uint warriors, uint regions) {
//First let's confirm if the user actually owns enough chests of the appropriate type that they've requested
uint balance = balanceOf(msg.sender, uint(chestType));
if(balance >= quantity){
fameReward = 0;
warriors = 0;
regions = 0;
uint chestTypeMultiplier = (2**(uint(chestType)-1));
uint baseFAMEReward = FIXED_VALUE_BASE * chestTypeMultiplier;
//Burn the appropriate number of chests:
_burn(msg.sender,uint(chestType),quantity);
//Iterate the chests requested to calculate rewards
for(uint chest=0;chest<quantity;chest++){
//Calculate the FAME Reward amount for this chest:
uint fameRoll = roll(chest*2+0);
if(fameRoll<(CHANCE_BONUS_50 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1500 / 1000;
}else if(fameRoll<(CHANCE_BONUS_25 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1250 / 1000;
}else if(fameRoll<(CHANCE_BONUS_10 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1100 / 1000;
}else{
fameReward += baseFAMEReward;
}
//Calculate if any prize (NFT) was also received in this chest:
uint prizeRoll = roll(chest*2+1);
if(prizeRoll<(CHANCE_BONUS_REGION * chestTypeMultiplier)){
//Woohoo! Won a Region! BONUS!
regions++;
}else if(fameRoll<(CHANCE_BONUS_WARRIOR * chestTypeMultiplier)){
//Woohoo! Won a Warrior!
warriors++;
}
}
//Ok now that we've figured out their rewards, let's give it all to them!
//First the FAME:
transferFAME(address(this),msg.sender,fameReward);
//Now if there are regions or warriors in the rewards, mint the appropriate NFTs:
for(uint w=0;w<warriors;w++){
//Unfortunately because of how warrior minting works, we need to pre-generate some random traits:
// For the record this was chosen for a good reason, it's more flexible and supports a wider set of use cases
// But it is a bit more work when implementing in an external contract like this...
//First let's grab a random seed:
uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp,blockhash(block.number))));
//And then generate the remaining traits from it
uint16 colorHue = uint16(uint(keccak256(abi.encodePacked(randomSeed,uint8(1)))));
uint8 armorType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(2)))))%4;
uint8 shieldType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(3)))))%4;
uint8 weaponType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(4)))))%10;
//Now mint the warrior:
WarriorContract.mintCustomWarrior(msg.sender, 0, true, randomSeed, colorHue, armorType, shieldType, weaponType);
}
for(uint r=0;r<regions;r++){
//When minting Regions, the caller (this contract) will end up owning them, so we need to first mint, then change ownership:
//First we try to mint:
try RegionContract.trustedCreateRegion() returns (uint regionID){
//Now we transfer it to the user:
RegionContract.safeTransferFrom(address(this),msg.sender,regionID,1,"");
} catch Error(string memory reason) {
revert(reason);
} catch Panic(uint code) {
revert ErrorMintingRegion(code);
} catch (bytes memory) {
revert ErrorMintingRegion(0);
}
}
emit LootBoxOpened(msg.sender, uint8(chestType), uint32(quantity), uint32(block.timestamp), uint32(fameReward), uint32(warriors), uint32(regions));
}else{
//Bad monkey! You don't have that many chests to open!
revert InsufficientChests(uint8(chestType), balance);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Costing Getters
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Get the Base Value (guaranteed FAME contents) of a given chest type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return value The Value (amount of FAME) included in the chest type
*/
function getBaseValue(ChestType chestType) public pure returns (uint value) {
require(chestType > ChestType.NULL && chestType <= ChestType.DIAMOND, "ILLEGAL CHEST TYPE");
value = FIXED_VALUE_BASE * (2**(uint(chestType)-1));
}
/**
*@notice Get the recent sales volume (total amount of FAME sold in chest Base Values)
*@return volume The total Base Value (guaranteed included FAME) of all recent chest sales
*@dev This is used to figure out demand for costing math
*/
function getRecentSalesVolume() public view returns (uint volume) {
volume = 1; //To avoid div/0
for(uint i = 0; i<RECENT_SALES_TO_TRACK; i++){
if(recentSales[i].timestamp >= block.timestamp - RECENT_SALES_TIME_SECONDS){
volume += getBaseValue(ChestType(recentSales[i].chest_type)) * recentSales[i].quantity;
}
}
}
/**
*@notice Calculate the current FAME price (price per FAME token in ETH)
*@return price The current ETH price (in wei) of a single FAME token
*@dev This is used to calculate the "market floor" price for FAME so that we can use it to caluclate cost of chests.
*/
function getCurrentFAMEPrice() public view returns (uint price) {
//First we look at the current (available/non-liable) fame balance, and the recent sales volume, and calculate a demand ratio:
// Note: recent sales volume is always floored at the value of at least one of the max chest, which allows
// for the situation where there is zero supply, to incentivize seeding the supply to accommodate chest sales.
// Otherwise, what happens is if the contract runs dry, and no sales happen because there is no supply, the
// "recent sales" drop to zero, resulting in artificially deflated demand, even though "demand" might be high, but
// it can't be observed because lack of supply has choked off sales. (not to mention it also helps avoid div/0)
//ie: if we have 10,000 FAME, and we've recently only sold 1000, then we have 10:1 ratio so plenty of supply to meet the demand
// however if we have 1000 FAME, and recently sold 2000, we have a 0.5:1 ratio, so low supply, which should drive up price...
//Price is calculated by first calculating demand ratio, and then clamping it to min/max range (in config constants)
//Then taking the ICO base value of new FAME, and dividing by the demand ratio.
//As a practical example, let's assume the ICO base value was 10,000gwei per fame,
//And assume we have a demand ratio clamp range of 0.5 - 2.0
//Then the following table demonstrates how the demand ratios would equate to FAME price
//0.5:1 - 20,000 gwei/FAME
//0.75:1 - 13,333 gwei/FAME
//1:1 - 10,000 gwei/FAME
//1.25:1 - 8,000 gwei/FAME
//1.5:1 - 6,666 gwei/FAME
//1.75:1 - 5,714 gwei/FAME
//2:1 - 5,000 gwei/FAME
//Keep in mind this mechanism is designed to be a fallback to market liquidity. Ideally if the market is healthy, then on
//exchange sites such as OpenSea, or other token exchanges, FAME will trade for normal market value and this contract will be ignored.
//This contract serves a purpose during ramp-up of BattleDrome, to provide a buy-in mechanism, and a sell-off mechanism to distribute
//some of the FAME from ICO backers, to seed initial market distribution, and jump-start new players.
//It also serves a purpose if market liquidity results in poor conditions, provided people are still interested in the tokens/game
//As it will serve as a floor price mechanism, allowing holders to liquidate if there is some demand, and players to buy in if there is supply
//Get the raw sales volume
uint rawSalesVolume = getRecentSalesVolume();
//Find out the minimum sales volume (cost of a diamond chest)
uint minSalesVolume = getBaseValue(ChestType.DIAMOND);
//Raise the sales volume if needed
uint adjustedSalesVolume = (rawSalesVolume<minSalesVolume) ? minSalesVolume : rawSalesVolume;
//Now we figure out our "available balance"
uint availableBalance = getContractFAMEBalance() - calculateCurrentLiability();
//Calculate raw demand ratio
uint rawDemandRatio = (availableBalance * 10000) / adjustedSalesVolume;
//Then clamp the demand ratio within min/max bounds set in constants above
uint demandRatio = (rawDemandRatio<MIN_DEMAND_RATIO)?MIN_DEMAND_RATIO:(rawDemandRatio>MAX_DEMAND_RATIO)?MAX_DEMAND_RATIO:rawDemandRatio;
//And finally calculate the price based on resulting demand ratio
price = (NEW_FAME_ICO_VALUE * 10000) / demandRatio;
}
/**
*@notice Calculate the current price in Ether (wei) for the specified chest type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return price The current ETH price (in wei) of a chest of that type
*/
function getPrice(ChestType chestType) public view returns (uint price) {
uint8 discountedPriceMultiplier = uint8(100 - (VOLUME_DISCOUNT_PERCENT * (2**(uint(chestType)-1))));
price = getCurrentFAMEPrice() * getBaseValue(chestType) * discountedPriceMultiplier / 100;
}
/**
*@notice Calculate the Ether Price we will pay to buy back FAME from a user (in Wei)
*@param amount The amount of FAME tokens on offer (the total price returned will be for this full amount)
*@return price The current ETH price (in wei) that will be paid for the full amount specified
*/
function getBuyBackPrice(uint amount) public view returns (uint price) {
//Determine current FAME price, and then we multiply down because our buyback percentage is 90% of current market price
//We also multiply by the amount to find the (perfect world) amount we will pay
price = (getCurrentFAMEPrice() * 9 / 10) * amount;
//Now we determine the max we will pay in a single transaction (capped at 25% of our current holdings in ETH, to prevent abuse)
//This means that if one user tries to dump a large amount to take advantage of a favorable price, they will only be paid a limited amount
//Forcing them to reduce their transaction (or risk being under-paid), and do a second transaction.
uint maxPayout = address(this).balance / 4;
//Next we cap the payout based on the maxPayout:
price = price > maxPayout ? maxPayout : price;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Utility Functions
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@dev Internal Helper Function to determine random roll when opening chests. Crude RNG, should be good enough, but is manipulable by miner theoretically
*@param seedOffset Integer seed offset used for additional randomization
*@return result Random roll from 0-10000 (random percentage to 2 decimal places)
*/
function roll(uint seedOffset) internal view returns (uint16 result) {
uint randomUint = uint(keccak256(abi.encodePacked(block.timestamp,blockhash(block.number),seedOffset)));
result = uint16(randomUint % 10000);
}
/**
*@notice ADMIN FUNCTION: Update the FAME Token ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setFAMEContractAddress(address newContract) public onlyOwner {
FAMEContract = IERC1155(newContract);
}
/**
*@notice ADMIN FUNCTION: Set the internal Token ID for FAME Tokens within the ERC1155 Contract
*@param id The new Token ID
*/
function setFAMETokenID(uint256 id) public onlyOwner {
FAMETokenID = id;
}
/**
*@notice ADMIN FUNCTION: Update the Warrior NFT ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setWarriorContractAddress(address newContract) public onlyOwner {
WarriorContract = IWarrior(newContract);
}
/**
*@notice ADMIN FUNCTION: Update the Region NFT ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setRegionContractAddress(address newContract) public onlyOwner {
RegionContract = IRegion(newContract);
}
/**
*@dev Utility/Helper function for internal use whenever we need to transfer fame between 2 addresses
*@param sender The Sender Address (address from which the FAME will be deducted)
*@param recipient The Recipient Address (address to which the FAME will be credited)
*@param amount The amount of FAME tokens to transfer
*/
function transferFAME(
address sender,
address recipient,
uint256 amount
) internal {
FAMEContract.safeTransferFrom(
sender,
recipient,
FAMETokenID,
amount,
""
);
}
/**
*@notice Fetch the current FAME balance held within the Loot Chest Smart Contract
*@return balance The current FAME Token Balance
*/
function getContractFAMEBalance() public view returns (uint balance) {
return FAMEContract.balanceOf(address(this),FAMETokenID);
}
/**
*@dev Utility/Helper function for internal use, helps determine the worst case liability of a given chest type (amount of FAME that needs paying out)
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return fame_liability The liability (amount of FAME this countract could potentially be expected to pay out in the worst case, or maximum reward scenario)
*/
function calculateChestLiability(ChestType chestType) internal pure returns (uint fame_liability) {
return getBaseValue(chestType) * 1500 / 1000;
}
/**
*@notice The current total liability of this contract (total FAME that would be required to be paid out if all current chests in circulation contain the max reward)
*@return fame_liability The current total liability (total FAME payout required in worse case from all chests in circulation)
*/
function calculateCurrentLiability() public view returns (uint fame_liability) {
for(uint8 ct=uint8(ChestType.BRONZE);ct<=uint8(ChestType.DIAMOND);ct++)
{
//Get current chest count of chest type
uint chestCount = totalSupply(ct);
//Then multiply by the liability of that chest type
fame_liability += chestCount * calculateChestLiability(ChestType(ct));
}
}
/**
*@notice Checks based on current FAME balance, and current total liability, the max number of specified chestType that can be created safely (factoring in new liability for requested chests)
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return maxQuantity Maximum quantity of chests of specified type, that can be created safely based on current conditions.
*/
function maxSafeCreatable(ChestType chestType) public view returns (uint maxQuantity) {
maxQuantity = 0;
uint currentLiability = calculateCurrentLiability();
uint currentBalance = getContractFAMEBalance();
if(currentLiability < currentBalance){
uint freeBalance = currentBalance - currentLiability;
maxQuantity = freeBalance / calculateChestLiability(chestType);
}
}
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
interface IWarrior {
function mintCustomWarrior(address owner, uint32 generation, bool special, uint randomSeed, uint16 colorHue, uint8 armorType, uint8 shieldType, uint8 weaponType) external returns(uint theNewWarrior);
function newWarrior() external returns(uint theNewWarrior);
function getWarriorIDByName(string calldata name) external view returns(uint);
function nameExists(string calldata _name) external view returns(bool);
function setName(uint warriorID, string calldata name) external;
function ownerOf(uint _id) external view returns(address);
function getWarriorCost() external pure returns(uint);
function getWarriorName(uint warriorID) external view returns(string memory);
function payWarrior(uint warriorID, uint amount, bool tax) external;
function transferFAMEFromWarriorToWarrior(uint senderID, uint recipientID, uint amount, bool tax) external;
function transferFAMEFromWarriorToAddress(uint warriorID, address recipient, uint amount) external;
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
interface IRegion is IERC1155 {
function trustedCreateRegion() external returns (uint256 theNewRegion);
function newRegion() external returns (uint256 theNewRegion);
function getCurrentRegionCount() external view returns (uint256);
function getCurrentRegionPricingCounter() external view returns (uint256);
function ownerOf(uint256 _id) external view returns (address);
function getRegionCost(int256 offset) external view returns (uint256);
function getRegionName(uint256 regionID) external;
function payRegion(uint256 regionID, uint256 amount, bool tax) external;
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
//import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol';
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155Metadata.sol';
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155MintBurn.sol';
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title BDERC1155Tradable
* BDERC1155Tradable - BattleDrome ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract BDERC1155Tradable is ERC1155PresetMinterPauser, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
//Metadata URI (for backwards compat with old code, overrides URI functionality from openzeppelin)
string public baseMetadataURI;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(
creators[_id] == msg.sender,
"ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"
);
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(
balanceOf(msg.sender, _id) > 0,
"ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress,
string memory _metadataURI
) ERC1155PresetMinterPauser(_metadataURI) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
_setBaseMetadataURI(_metadataURI);
}
function uri(uint256 _id) public view override returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return string(abi.encodePacked(baseMetadataURI, Strings.toString(_id)));
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal {
baseMetadataURI = _newBaseMetadataURI;
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyOwner
{
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public override creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id] + _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(
creators[_id] == msg.sender,
"ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"
);
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id] + quantity;
}
_mintBatch(_to, _ids, _quantities, _data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal override {
tokenSupply[id] = tokenSupply[id] - amount;
super._burn(from,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 from,
uint256[] memory ids,
uint256[] memory amounts
) internal override {
for (uint256 i = 0; i < ids.length; i++) {
tokenSupply[ids[i]] = tokenSupply[ids[i]] - amounts[i];
}
super._burnBatch(from,ids,amounts);
}
/**
* @dev Change the creator address for given tokens
* @param _to Address of the new creator
* @param _ids Array of Token IDs to change creator
*/
function setCreator(address _to, uint256[] memory _ids) public {
require(
_to != address(0),
"ERC1155Tradable#setCreator: INVALID_ADDRESS."
);
require(
_ids.length>0,
"ERC1155Tradeable#setCreator: EMPTY_ARRAY"
);
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool isOperator)
{
//TODO: FAILING HERE ON REGION SALE
//Failing from inside the transferFAME function (inside safeTransferFrom in the FAME contract itself)
//When being called by the Region contract as the operator
//With the user being the owner.
//WHY!?!?!?
//Ideas:
// Look into the proxy contract, this code is throwing a revert and the debugger seems non-specific
// Pour over this again with debugger a couple times
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Change the creator address for given token
* @param _to Address of the new creator
* @param _id Token IDs to change creator of
*/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id) {
creators[_id] = _to;
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() internal view returns (uint256) {
return _currentTokenID + 1;
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() internal {
_currentTokenID++;
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// 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 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;
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.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.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 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;
/**
* @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;
/**
* @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;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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.8.0;
import "../ERC1155.sol";
import "../extensions/ERC1155Burnable.sol";
import "../extensions/ERC1155Pausable.sol";
import "../../../access/AccessControlEnumerable.sol";
import "../../../utils/Context.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, AccessControlEnumerable, 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) 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();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC1155)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
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.8.0;
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.8.0;
import "../ERC1155.sol";
import "../../../security/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.8.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.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _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.8.0;
import "../../utils/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.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.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 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;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @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) public view virtual 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 virtual 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
virtual
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) {
batchBalances[i] = balanceOf(accounts[i], ids[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 virtual 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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += 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 `account` 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] += 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 (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
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), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
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 (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
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.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.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.8.0;
import "../utils/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.
*/
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());
}
}
// 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;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @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) external view returns (address);
/**
* @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) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @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 override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @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 override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* 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, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override onlyRole(getRoleAdmin(role)) {
_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 override onlyRole(getRoleAdmin(role)) {
_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 override {
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
|
Get the Base Value (guaranteed FAME contents) of a given chest type chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)return value The Value (amount of FAME) included in the chest type/
|
function getBaseValue(ChestType chestType) public pure returns (uint value) {
require(chestType > ChestType.NULL && chestType <= ChestType.DIAMOND, "ILLEGAL CHEST TYPE");
value = FIXED_VALUE_BASE * (2**(uint(chestType)-1));
}
| 13,683,517 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../interface/IERC20.sol";
import "../interface/ILToken.sol";
import "./ERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title Deri Protocol liquidity provider token implementation
*/
contract LToken is IERC20, ILToken, ERC20 {
using UnsignedSafeMath for uint256;
// Pool address this LToken associated with
address private _pool;
modifier _pool_() {
require(msg.sender == _pool, "LToken: called by non-associative pool, probably the original pool has been migrated");
_;
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token
*/
constructor(string memory name_, string memory symbol_, address pool_) ERC20(name_, symbol_) {
require(pool_ != address(0), "LToken: construct with 0 address pool");
_pool = pool_;
}
/**
* @dev See {ILToken}.{setPool}
*/
function setPool(address newPool) public override {
require(newPool != address(0), "LToken: setPool to 0 address");
require(msg.sender == _pool, "LToken: setPool caller is not current pool");
_pool = newPool;
}
/**
* @dev See {ILToken}.{pool}
*/
function pool() public view override returns (address) {
return _pool;
}
/**
* @dev See {ILToken}.{mint}
*/
function mint(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: mint to 0 address");
_balances[account] = _balances[account].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev See {ILToken}.{burn}
*/
function burn(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: burn from 0 address");
require(_balances[account] >= amount, "LToken: burn amount exceeds balance");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
}
// 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 Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `amount` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @dev Emitted when `amount` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `amount` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the name.
*/
function symbol() external view returns (string memory);
/**
* @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() external view returns (uint8);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev 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 the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC20.sol";
/**
* @title Deri Protocol liquidity provider token interface
*/
interface ILToken is IERC20 {
/**
* @dev Set the pool address of this LToken
* pool is the only controller of this contract
* can only be called by current pool
*/
function setPool(address newPool) external;
/**
* @dev Returns address of pool
*/
function pool() external view returns (address);
/**
* @dev Mint LToken to `account` of `amount`
*
* Can only be called by pool
* `account` cannot be zero address
*/
function mint(address account, uint256 amount) external;
/**
* @dev Burn `amount` LToken of `account`
*
* Can only be called by pool
* `account` cannot be zero address
* `account` must owns at least `amount` LToken
*/
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../interface/IERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title ERC20 Implementation
*/
contract ERC20 is IERC20 {
using UnsignedSafeMath for uint256;
string _name;
string _symbol;
uint8 _decimals = 18;
uint256 _totalSupply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC20}.{name}
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC20}.{symbol}
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC20}.{decimals}
*/
function decimals() public view override 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}.{allowance}
*/
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20}.{approve}
*/
function approve(address spender, uint256 amount) public override returns (bool) {
require(spender != address(0), "ERC20: approve to 0 address");
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20}.{transfer}
*/
function transfer(address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transfer to 0 address");
require(_balances[msg.sender] >= amount, "ERC20: transfer amount exceeds balance");
_transfer(msg.sender, to, amount);
return true;
}
/**
* @dev See {IERC20}.{transferFrom}
*/
function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transferFrom to 0 address");
if (_allowances[from][msg.sender] != uint256(-1)) {
require(_allowances[from][msg.sender] >= amount, "ERC20: transferFrom not approved");
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(amount);
}
_transfer(from, to, amount);
return true;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`.
* Emits an {Approval} event.
*
* Parameters check should be carried out before calling this function.
*/
function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Moves tokens `amount` from `from` to `to`.
* Emits a {Transfer} event.
*
* Parameters check should be carried out before calling this function.
*/
function _transfer(address from, address to, uint256 amount) internal {
_balances[from] = _balances[from].sub(amount);
_balances[to] = _balances[to].add(amount);
emit Transfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Unsigned safe math
*/
library UnsignedSafeMath {
/**
* @dev Addition of unsigned integers, counterpart to `+`
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "UnsignedSafeMath: addition overflow");
return c;
}
/**
* @dev Subtraction of unsigned integers, counterpart to `-`
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "UnsignedSafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Multiplication of unsigned integers, counterpart to `*`
*/
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, "UnsignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Division of unsigned integers, counterpart to `/`
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: division by zero");
uint256 c = a / b;
return c;
}
/**
* @dev Modulo of unsigned integers, counterpart to `%`
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: modulo by zero");
uint256 c = a % b;
return c;
}
}
|
See {IERC20}.{transfer}/
|
function transfer(address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transfer to 0 address");
require(_balances[msg.sender] >= amount, "ERC20: transfer amount exceeds balance");
_transfer(msg.sender, to, amount);
return true;
}
| 10,376,714 |
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT AND GPL-3.0-or-later
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
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/access/AccessControl.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, 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());
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/IMintableERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of an ERC20 which implements the mint() function.
*/
interface IMintableERC20
is IERC20
{
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
}
// File: contracts/KnsTokenWork.sol
/**************************************************************************************
* *
* GENERATED FILE DO NOT EDIT *
* ___ ____ _ _ ____ ____ __ ____ ____ ____ ____ ____ __ ____ *
* / __)( ___)( \( )( ___)( _ \ /__\ (_ _)( ___)( _ \ ( ___)(_ _)( ) ( ___) *
* ( (_-. )__) ) ( )__) ) / /(__)\ )( )__) )(_) ) )__) _)(_ )(__ )__) *
* \___/(____)(_)\_)(____)(_)\_)(__)(__)(__) (____)(____/ (__) (____)(____)(____) *
* *
* GENERATED FILE DO NOT EDIT *
* *
**************************************************************************************/
pragma solidity ^0.6.0;
contract KnsTokenWork
{
/**
* Compute the work function for a seed, secured_struct_hash, and nonce.
*
* work_result[10] is the actual work function value, this is what is compared against the target.
* work_result[0] through work_result[9] (inclusive) are the values of w[y_i].
*/
function work(
uint256 seed,
uint256 secured_struct_hash,
uint256 nonce
) public pure returns (uint256[11] memory work_result)
{
uint256 w;
uint256 x;
uint256 y;
uint256 result = secured_struct_hash;
uint256 coeff_0 = (nonce % 0x0000fffd)+1;
uint256 coeff_1 = (nonce % 0x0000fffb)+1;
uint256 coeff_2 = (nonce % 0x0000fff7)+1;
uint256 coeff_3 = (nonce % 0x0000fff1)+1;
uint256 coeff_4 = (nonce % 0x0000ffef)+1;
x = secured_struct_hash % 0x0000fffd;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[0] = w;
result ^= w;
x = secured_struct_hash % 0x0000fffb;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[1] = w;
result ^= w;
x = secured_struct_hash % 0x0000fff7;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[2] = w;
result ^= w;
x = secured_struct_hash % 0x0000fff1;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[3] = w;
result ^= w;
x = secured_struct_hash % 0x0000ffef;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[4] = w;
result ^= w;
x = secured_struct_hash % 0x0000ffe5;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[5] = w;
result ^= w;
x = secured_struct_hash % 0x0000ffdf;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[6] = w;
result ^= w;
x = secured_struct_hash % 0x0000ffd9;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[7] = w;
result ^= w;
x = secured_struct_hash % 0x0000ffd3;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[8] = w;
result ^= w;
x = secured_struct_hash % 0x0000ffd1;
y = coeff_4;
y *= x;
y += coeff_3;
y *= x;
y += coeff_2;
y *= x;
y += coeff_1;
y *= x;
y += coeff_0;
y %= 0x0000ffff;
w = uint256( keccak256( abi.encode( seed, y ) ) );
work_result[9] = w;
result ^= w;
work_result[10] = result;
return work_result;
}
}
// File: contracts/KnsTokenMining.sol
pragma solidity ^0.6.0;
contract KnsTokenMining
is AccessControl,
KnsTokenWork
{
IMintableERC20 public token;
mapping (uint256 => uint256) private user_pow_height;
uint256 public constant ONE_KNS = 100000000;
uint256 public constant MINEABLE_TOKENS = 100 * 1000000 * ONE_KNS;
uint256 public constant FINAL_PRINT_RATE = 1500; // basis points
uint256 public constant TOTAL_EMISSION_TIME = 180 days;
uint256 public constant EMISSION_COEFF_1 = (MINEABLE_TOKENS * (20000 - FINAL_PRINT_RATE) * TOTAL_EMISSION_TIME);
uint256 public constant EMISSION_COEFF_2 = (MINEABLE_TOKENS * (10000 - FINAL_PRINT_RATE));
uint256 public constant HC_RESERVE_DECAY_TIME = 5 days;
uint256 public constant RECENT_BLOCK_LIMIT = 96;
uint256 public start_time;
uint256 public token_reserve;
uint256 public hc_reserve;
uint256 public last_mint_time;
bool public is_testing;
event Mine( address[] recipients, uint256[] split_percents, uint256 hc_submit, uint256 hc_decay, uint256 token_virtual_mint, uint256[] tokens_mined );
constructor( address tok, uint256 start_t, uint256 start_hc_reserve, bool testing )
public
{
token = IMintableERC20(tok);
_setupRole( DEFAULT_ADMIN_ROLE, _msgSender() );
start_time = start_t;
last_mint_time = start_t;
hc_reserve = start_hc_reserve;
token_reserve = 0;
is_testing = testing;
_initial_mining_event( start_hc_reserve );
}
function _initial_mining_event( uint256 start_hc_reserve ) internal
{
address[] memory recipients = new address[](1);
uint256[] memory split_percents = new uint256[](1);
uint256[] memory tokens_mined = new uint256[](1);
recipients[0] = address(0);
split_percents[0] = 10000;
tokens_mined[0] = 0;
emit Mine( recipients, split_percents, start_hc_reserve, 0, 0, tokens_mined );
}
/**
* Get the hash of the secured struct.
*
* Basically calls keccak256() on parameters. Mainly exists for readability purposes.
*/
function get_secured_struct_hash(
address[] memory recipients,
uint256[] memory split_percents,
uint256 recent_eth_block_number,
uint256 recent_eth_block_hash,
uint256 target,
uint256 pow_height
) public pure returns (uint256)
{
return uint256( keccak256( abi.encode( recipients, split_percents, recent_eth_block_number, recent_eth_block_hash, target, pow_height ) ) );
}
/**
* Require w[0]..w[9] are all distinct values.
*
* w[10] is untouched.
*/
function check_uniqueness(
uint256[11] memory w
) public pure
{
// Implement a simple direct comparison algorithm, unroll to optimize gas usage.
require( (w[0] != w[1]) && (w[0] != w[2]) && (w[0] != w[3]) && (w[0] != w[4]) && (w[0] != w[5]) && (w[0] != w[6]) && (w[0] != w[7]) && (w[0] != w[8]) && (w[0] != w[9])
&& (w[1] != w[2]) && (w[1] != w[3]) && (w[1] != w[4]) && (w[1] != w[5]) && (w[1] != w[6]) && (w[1] != w[7]) && (w[1] != w[8]) && (w[1] != w[9])
&& (w[2] != w[3]) && (w[2] != w[4]) && (w[2] != w[5]) && (w[2] != w[6]) && (w[2] != w[7]) && (w[2] != w[8]) && (w[2] != w[9])
&& (w[3] != w[4]) && (w[3] != w[5]) && (w[3] != w[6]) && (w[3] != w[7]) && (w[3] != w[8]) && (w[3] != w[9])
&& (w[4] != w[5]) && (w[4] != w[6]) && (w[4] != w[7]) && (w[4] != w[8]) && (w[4] != w[9])
&& (w[5] != w[6]) && (w[5] != w[7]) && (w[5] != w[8]) && (w[5] != w[9])
&& (w[6] != w[7]) && (w[6] != w[8]) && (w[6] != w[9])
&& (w[7] != w[8]) && (w[7] != w[9])
&& (w[8] != w[9]),
"Non-unique work components" );
}
/**
* Check proof of work for validity.
*
* Throws if the provided fields have any problems.
*/
function check_pow(
address[] memory recipients,
uint256[] memory split_percents,
uint256 recent_eth_block_number,
uint256 recent_eth_block_hash,
uint256 target,
uint256 pow_height,
uint256 nonce
) public view
{
require( recent_eth_block_hash != 0, "Zero block hash not allowed" );
require( recent_eth_block_number <= block.number, "Recent block in future" );
require( recent_eth_block_number + RECENT_BLOCK_LIMIT > block.number, "Recent block too old" );
require( nonce >= recent_eth_block_hash, "Nonce too small" );
require( (recent_eth_block_hash + (1 << 128)) > nonce, "Nonce too large" );
require( uint256( blockhash( recent_eth_block_number ) ) == recent_eth_block_hash, "Block hash mismatch" );
require( recipients.length <= 5, "Number of recipients cannot exceed 5" );
require( recipients.length == split_percents.length, "Recipient and split percent array size mismatch" );
array_check( split_percents );
require( get_pow_height( _msgSender(), recipients, split_percents ) + 1 == pow_height, "pow_height mismatch" );
uint256 h = get_secured_struct_hash( recipients, split_percents, recent_eth_block_number, recent_eth_block_hash, target, pow_height );
uint256[11] memory w = work( recent_eth_block_hash, h, nonce );
check_uniqueness( w );
require( w[10] < target, "Work missed target" ); // always fails if target == 0
}
function array_check( uint256[] memory arr )
internal pure
{
uint256 sum = 0;
for (uint i = 0; i < arr.length; i++)
{
require( arr[i] <= 10000, "Percent array element cannot exceed 10000" );
sum += arr[i];
}
require( sum == 10000, "Split percentages do not add up to 10000" );
}
function get_emission_curve( uint256 t )
public view returns (uint256)
{
if( t < start_time )
t = start_time;
if( t > start_time + TOTAL_EMISSION_TIME )
t = start_time + TOTAL_EMISSION_TIME;
t -= start_time;
return ((EMISSION_COEFF_1 - (EMISSION_COEFF_2*t))*t) / (10000 * TOTAL_EMISSION_TIME * TOTAL_EMISSION_TIME);
}
function get_hc_reserve_multiplier( uint256 dt )
public pure returns (uint256)
{
if( dt >= HC_RESERVE_DECAY_TIME )
return 0x80000000;
int256 idt = (int256( dt ) << 32) / int32(HC_RESERVE_DECAY_TIME);
int256 y = -0xa2b23f3;
y *= idt;
y >>= 32;
y += 0x3b9d3bec;
y *= idt;
y >>= 32;
y -= 0xb17217f7;
y *= idt;
y >>= 32;
y += 0x100000000;
if( y < 0 )
y = 0;
return uint256( y );
}
function get_background_activity( uint256 current_time ) public view
returns (uint256 hc_decay, uint256 token_virtual_mint)
{
hc_decay = 0;
token_virtual_mint = 0;
if( current_time <= last_mint_time )
return (hc_decay, token_virtual_mint);
uint256 dt = current_time - last_mint_time;
uint256 f_prev = get_emission_curve( last_mint_time );
uint256 f_now = get_emission_curve( current_time );
if( f_now <= f_prev )
return (hc_decay, token_virtual_mint);
uint256 mul = get_hc_reserve_multiplier( dt );
uint256 new_hc_reserve = (hc_reserve * mul) >> 32;
hc_decay = hc_reserve - new_hc_reserve;
token_virtual_mint = f_now - f_prev;
return (hc_decay, token_virtual_mint);
}
function process_background_activity( uint256 current_time ) internal
returns (uint256 hc_decay, uint256 token_virtual_mint)
{
(hc_decay, token_virtual_mint) = get_background_activity( current_time );
hc_reserve -= hc_decay;
token_reserve += token_virtual_mint;
last_mint_time = current_time;
return (hc_decay, token_virtual_mint);
}
/**
* Calculate value in tokens the given hash credits are worth
**/
function get_hash_credits_conversion( uint256 hc )
public view
returns (uint256)
{
require( hc > 1, "HC underflow" );
require( hc < (1 << 128), "HC overflow" );
// xyk algorithm
uint256 x0 = token_reserve;
uint256 y0 = hc_reserve;
require( x0 < (1 << 128), "Token balance overflow" );
require( y0 < (1 << 128), "HC balance overflow" );
uint256 y1 = y0 + hc;
require( y1 < (1 << 128), "HC balance overflow" );
// x0*y0 = x1*y1 -> x1 = (x0*y0)/y1
// NB above require() ensures overflow safety
uint256 x1 = ((x0*y0)/y1)+1;
require( x1 < x0, "No tokens available" );
return x0-x1;
}
/**
* Executes the trade of hash credits to tokens
* Returns number of minted tokens
**/
function convert_hash_credits(
uint256 hc ) internal
returns (uint256)
{
uint256 tokens_minted = get_hash_credits_conversion( hc );
hc_reserve += hc;
token_reserve -= tokens_minted;
return tokens_minted;
}
function increment_pow_height(
address[] memory recipients,
uint256[] memory split_percents ) internal
{
user_pow_height[uint256( keccak256( abi.encode( _msgSender(), recipients, split_percents ) ) )] += 1;
}
function mine_impl(
address[] memory recipients,
uint256[] memory split_percents,
uint256 recent_eth_block_number,
uint256 recent_eth_block_hash,
uint256 target,
uint256 pow_height,
uint256 nonce,
uint256 current_time ) internal
{
check_pow(
recipients,
split_percents,
recent_eth_block_number,
recent_eth_block_hash,
target,
pow_height,
nonce
);
uint256 hc_submit = uint256(-1)/target;
uint256 hc_decay;
uint256 token_virtual_mint;
(hc_decay, token_virtual_mint) = process_background_activity( current_time );
uint256 token_mined;
token_mined = convert_hash_credits( hc_submit );
uint256[] memory distribution = distribute( recipients, split_percents, token_mined );
increment_pow_height( recipients, split_percents );
emit Mine( recipients, split_percents, hc_submit, hc_decay, token_virtual_mint, distribution );
}
/**
* Get the total number of proof-of-work submitted by a user.
*/
function get_pow_height(
address from,
address[] memory recipients,
uint256[] memory split_percents
)
public view
returns (uint256)
{
return user_pow_height[uint256( keccak256( abi.encode( from, recipients, split_percents ) ) )];
}
/**
* Executes the distribution, minting the tokens to the recipient addresses
**/
function distribute(address[] memory recipients, uint256[] memory split_percents, uint256 token_mined)
internal returns ( uint256[] memory )
{
uint256 remaining = token_mined;
uint256[] memory distribution = new uint256[]( recipients.length );
for (uint i = distribution.length-1; i > 0; i--)
{
distribution[i] = (token_mined * split_percents[i]) / 10000;
token.mint( recipients[i], distribution[i] );
remaining -= distribution[i];
}
distribution[0] = remaining;
token.mint( recipients[0], remaining );
return distribution;
}
function mine(
address[] memory recipients,
uint256[] memory split_percents,
uint256 recent_eth_block_number,
uint256 recent_eth_block_hash,
uint256 target,
uint256 pow_height,
uint256 nonce ) public
{
require( now >= start_time, "Mining has not started" );
mine_impl( recipients, split_percents, recent_eth_block_number, recent_eth_block_hash, target, pow_height, nonce, now );
}
function test_process_background_activity( uint256 current_time )
public
{
require( is_testing, "Cannot call test method" );
process_background_activity( current_time );
}
function test_mine(
address[] memory recipients,
uint256[] memory split_percents,
uint256 recent_eth_block_number,
uint256 recent_eth_block_hash,
uint256 target,
uint256 pow_height,
uint256 nonce,
uint256 current_time ) public
{
require( is_testing, "Cannot call test method" );
mine_impl( recipients, split_percents, recent_eth_block_number, recent_eth_block_hash, target, pow_height, nonce, current_time );
}
}
|
Calculate value in tokens the given hash credits are worth/ xyk algorithm x0y0 = x1y1 -> x1 = (x0y0)/y1 NB above require() ensures overflow safety
|
function get_hash_credits_conversion( uint256 hc )
public view
returns (uint256)
{
require( hc > 1, "HC underflow" );
require( hc < (1 << 128), "HC overflow" );
uint256 x0 = token_reserve;
uint256 y0 = hc_reserve;
require( x0 < (1 << 128), "Token balance overflow" );
require( y0 < (1 << 128), "HC balance overflow" );
uint256 y1 = y0 + hc;
require( y1 < (1 << 128), "HC balance overflow" );
uint256 x1 = ((x0*y0)/y1)+1;
require( x1 < x0, "No tokens available" );
return x0-x1;
}
| 11,987,862 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/ICapitalPool.sol";
import "./interfaces/IClaimingRegistry.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/ILeveragePortfolio.sol";
import "./interfaces/ILiquidityRegistry.sol";
import "./interfaces/IPolicyBook.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IYieldGenerator.sol";
import "./interfaces/ILeveragePortfolioView.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract CapitalPool is ICapitalPool, OwnableUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
IClaimingRegistry public claimingRegistry;
IPolicyBookRegistry public policyBookRegistry;
IYieldGenerator public yieldGenerator;
ILeveragePortfolio public reinsurancePool;
ILiquidityRegistry public liquidityRegistry;
ILeveragePortfolioView public leveragePortfolioView;
ERC20 public stblToken;
// reisnurance pool vStable balance updated by(premium, interest from defi)
uint256 public reinsurancePoolBalance;
// user leverage pool vStable balance updated by(premium, addliq, withdraw liq)
mapping(address => uint256) public leveragePoolBalance;
// policy books vStable balances updated by(premium, addliq, withdraw liq)
mapping(address => uint256) public regularCoverageBalance;
// all hStable capital balance , updated by (all pool transfer + deposit to dfi + liq cushion)
uint256 public hardUsdtAccumulatedBalance;
// all vStable capital balance , updated by (all pool transfer + withdraw from liq cushion)
uint256 public override virtualUsdtAccumulatedBalance;
// pool balances tracking
uint256 public override liquidityCushionBalance;
address public maintainer;
uint256 public stblDecimals;
// new state post v2 deployemnt
bool public isLiqCushionPaused;
bool public automaticHardRebalancing;
uint256 public override rebalanceDuration;
event PoolBalancesUpdated(
uint256 hardUsdtAccumulatedBalance,
uint256 virtualUsdtAccumulatedBalance,
uint256 liquidityCushionBalance,
uint256 reinsurancePoolBalance
);
event LiquidityCushionRebalanced(
uint256 liquidityNeede,
uint256 liquidityWithdraw,
uint256 liquidityDeposit
);
modifier broadcastBalancing() {
_;
emit PoolBalancesUpdated(
hardUsdtAccumulatedBalance,
virtualUsdtAccumulatedBalance,
liquidityCushionBalance,
reinsurancePoolBalance
);
}
modifier onlyPolicyBook() {
require(policyBookRegistry.isPolicyBook(msg.sender), "CAPL: Not a PolicyBook");
_;
}
modifier onlyReinsurancePool() {
require(
address(reinsurancePool) == _msgSender(),
"RP: Caller is not a reinsurance pool contract"
);
_;
}
modifier onlyMaintainer() {
require(_msgSender() == maintainer, "CP: not maintainer");
_;
}
function __CapitalPool_init() external initializer {
__Ownable_init();
maintainer = _msgSender();
rebalanceDuration = 3 days;
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract());
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
stblToken = ERC20(_contractsRegistry.getUSDTContract());
yieldGenerator = IYieldGenerator(_contractsRegistry.getYieldGeneratorContract());
reinsurancePool = ILeveragePortfolio(_contractsRegistry.getReinsurancePoolContract());
liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract());
leveragePortfolioView = ILeveragePortfolioView(
_contractsRegistry.getLeveragePortfolioViewContract()
);
stblDecimals = stblToken.decimals();
}
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external override onlyPolicyBook broadcastBalancing returns (uint256) {
PremiumFactors memory factors;
factors.vStblOfCP = regularCoverageBalance[_msgSender()];
factors.premiumPrice = _stblAmount.sub(_protocolFee);
factors.policyBookFacade = IPolicyBookFacade(IPolicyBook(_msgSender()).policyBookFacade());
factors.vStblDeployedByRP = DecimalsConverter.convertFrom18(
factors.policyBookFacade.VUreinsurnacePool(),
stblDecimals
);
factors.userLeveragePoolsCount = factors.policyBookFacade.countUserLeveragePools();
factors.epochsNumber = _epochsNumber;
uint256 reinsurancePoolPremium;
uint256 coveragePoolPremium;
if (factors.vStblDeployedByRP == 0 && factors.userLeveragePoolsCount == 0) {
coveragePoolPremium = factors.premiumPrice;
} else {
(reinsurancePoolPremium, coveragePoolPremium) = _calcPremiumForAllPools(factors);
}
uint256 reinsurancePoolTotalPremium = reinsurancePoolPremium.add(_protocolFee);
reinsurancePoolBalance = reinsurancePoolBalance.add(reinsurancePoolTotalPremium);
reinsurancePool.addPolicyPremium(
_epochsNumber,
DecimalsConverter.convertTo18(reinsurancePoolTotalPremium, stblDecimals)
);
regularCoverageBalance[_msgSender()] = regularCoverageBalance[_msgSender()].add(
coveragePoolPremium
);
hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount);
virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount);
return DecimalsConverter.convertTo18(coveragePoolPremium, stblDecimals);
}
function _calcPremiumForAllPools(PremiumFactors memory factors)
internal
returns (uint256 reinsurancePoolPremium, uint256 coveragePoolPremium)
{
uint256 _totalCoverTokens =
DecimalsConverter.convertFrom18(
(IPolicyBook(_msgSender())).totalCoverTokens(),
stblDecimals
);
factors.poolUtilizationRation = _totalCoverTokens.mul(PERCENTAGE_100).div(
factors.vStblOfCP
);
uint256 _participatedLeverageAmounts;
if (factors.userLeveragePoolsCount > 0) {
address[] memory _userLeverageArr =
factors.policyBookFacade.listUserLeveragePools(0, factors.userLeveragePoolsCount);
for (uint256 i = 0; i < _userLeverageArr.length; i++) {
_participatedLeverageAmounts = _participatedLeverageAmounts.add(
clacParticipatedLeverageAmount(factors, _userLeverageArr[i])
);
}
}
uint256 totalLiqforPremium =
factors.vStblOfCP.add(factors.vStblDeployedByRP).add(_participatedLeverageAmounts);
factors.premiumPerDeployment = (factors.premiumPrice.mul(PRECISION)).div(
totalLiqforPremium
);
reinsurancePoolPremium = _calcReinsurancePoolPremium(factors);
if (factors.userLeveragePoolsCount > 0) {
_calcUserLeveragePoolPremium(factors);
}
coveragePoolPremium = _calcCoveragePoolPremium(factors);
}
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount)
external
override
onlyPolicyBook
broadcastBalancing
{
regularCoverageBalance[_msgSender()] = regularCoverageBalance[_msgSender()].add(
_stblAmount
);
hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount);
virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount);
}
//// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount)
external
override
onlyPolicyBook
broadcastBalancing
{
leveragePoolBalance[_msgSender()] = leveragePoolBalance[_msgSender()].add(_stblAmount);
hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount);
virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount);
}
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount)
external
override
onlyReinsurancePool
broadcastBalancing
{
reinsurancePoolBalance = reinsurancePoolBalance.add(_stblAmount);
hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount);
virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount);
}
/// TODO if user not withdraw the amount after request withdraw , should the amount returned back to capital pool
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() public override broadcastBalancing onlyMaintainer {
//check defi protocol balances
(, uint256 _lostAmount) = yieldGenerator.reevaluateDefiProtocolBalances();
if (_lostAmount > 0) {
isLiqCushionPaused = true;
if (automaticHardRebalancing) {
defiHardRebalancing();
}
}
// hard rebalancing - Stop all withdrawals from all pools
if (isLiqCushionPaused) {
hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance);
liquidityCushionBalance = 0;
return;
}
uint256 _pendingClaimAmount = claimingRegistry.getAllPendingClaimsAmount();
uint256 _pendingWithdrawlAmount =
liquidityRegistry.getAllPendingWithdrawalRequestsAmount();
uint256 _requiredLiquidity = _pendingWithdrawlAmount.add(_pendingClaimAmount);
_requiredLiquidity = DecimalsConverter.convertFrom18(_requiredLiquidity, stblDecimals);
(uint256 _deposit, uint256 _withdraw) = getDepositAndWithdraw(_requiredLiquidity);
liquidityCushionBalance = _requiredLiquidity;
hardUsdtAccumulatedBalance = 0;
uint256 _actualAmount;
if (_deposit > 0) {
stblToken.safeApprove(address(yieldGenerator), 0);
stblToken.safeApprove(address(yieldGenerator), _deposit);
_actualAmount = yieldGenerator.deposit(_deposit);
if (_actualAmount < _deposit) {
hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(
(_deposit.sub(_actualAmount))
);
}
} else if (_withdraw > 0) {
_actualAmount = yieldGenerator.withdraw(_withdraw);
if (_actualAmount < _withdraw) {
liquidityCushionBalance = liquidityCushionBalance.sub(
(_withdraw.sub(_actualAmount))
);
}
}
emit LiquidityCushionRebalanced(_requiredLiquidity, _withdraw, _deposit);
}
/// @param _rebalanceDuration parameter passes in seconds
function setRebalanceDuration(uint256 _rebalanceDuration) public onlyOwner {
require(_rebalanceDuration <= 7 days, "CP: invalid rebalance duration");
rebalanceDuration = _rebalanceDuration;
}
function defiHardRebalancing() public onlyOwner {
(uint256 _totalDeposit, uint256 _lostAmount) =
yieldGenerator.reevaluateDefiProtocolBalances();
///TODO use threshold to evaluate lost amount
if (_lostAmount > 0 && _totalDeposit > _lostAmount) {
uint256 _lostPercentage = _lostAmount.mul(PERCENTAGE_100).div(_totalDeposit);
address[] memory _policyBooksArr =
policyBookRegistry.list(0, policyBookRegistry.count());
///@dev we should update all coverage pools liquidity before leverage pool
/// in order to do leverage rebalancing for all pools
for (uint256 i = 0; i < _policyBooksArr.length; i++) {
if (policyBookRegistry.isUserLeveragePool(_policyBooksArr[i])) continue;
_updatePoolLiquidity(_policyBooksArr[i], 0, _lostPercentage, PoolType.COVERAGE);
}
address[] memory _userLeverageArr =
policyBookRegistry.listByType(
IPolicyBookFabric.ContractType.VARIOUS,
0,
policyBookRegistry.countByType(IPolicyBookFabric.ContractType.VARIOUS)
);
for (uint256 i = 0; i < _userLeverageArr.length; i++) {
_updatePoolLiquidity(_userLeverageArr[i], 0, _lostPercentage, PoolType.LEVERAGE);
}
yieldGenerator.defiHardRebalancing();
}
}
/// @dev when calling this function we have to have either _lostAmount == 0 or _lostPercentage == 0
function _updatePoolLiquidity(
address _poolAddress,
uint256 _lostAmount,
uint256 _lostPercentage,
PoolType poolType
) internal {
IPolicyBook _pool = IPolicyBook(_poolAddress);
if (_lostPercentage > 0) {
uint256 _currentLiquidity = _pool.totalLiquidity();
_lostAmount = _currentLiquidity.mul(_lostPercentage).div(PERCENTAGE_100);
}
_pool.updateLiquidity(_lostAmount);
uint256 _stblLostAmount = DecimalsConverter.convertFrom18(_lostAmount, stblDecimals);
if (poolType == PoolType.COVERAGE) {
regularCoverageBalance[_poolAddress] = regularCoverageBalance[_poolAddress].sub(
_stblLostAmount
);
} else if (poolType == PoolType.LEVERAGE) {
leveragePoolBalance[_poolAddress] = leveragePoolBalance[_poolAddress].sub(
_stblLostAmount
);
} else if (poolType == PoolType.REINSURANCE) {
reinsurancePoolBalance = reinsurancePoolBalance.sub(_stblLostAmount);
}
if (_lostPercentage > 0) {
virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.sub(_stblLostAmount);
}
}
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _claimAmount uint256 amount to of the claim
function fundClaim(address _claimer, uint256 _claimAmount) external override onlyPolicyBook {
_withdrawFromLiquidityCushion(
_claimer,
DecimalsConverter.convertFrom18(_claimAmount, stblDecimals)
);
_dispatchLiquidities(_msgSender(), _claimAmount);
}
function _dispatchLiquidities(address _policyBookAddress, uint256 _claimAmount) internal {
IPolicyBook policyBook = IPolicyBook(_policyBookAddress);
IPolicyBookFacade policyBookFacade = policyBook.policyBookFacade();
uint256 totalCoveragedLiquidity = policyBook.totalLiquidity();
uint256 totalLeveragedLiquidity = policyBookFacade.totalLeveragedLiquidity();
uint256 totalPoolLiquidity = totalCoveragedLiquidity.add(totalLeveragedLiquidity);
// COVERAGE CONTRIBUTION
uint256 coverageContribution =
totalCoveragedLiquidity.mul(PERCENTAGE_100).div(totalPoolLiquidity);
uint256 coverageLoss = _claimAmount.mul(coverageContribution).div(PERCENTAGE_100);
_updatePoolLiquidity(_policyBookAddress, coverageLoss, 0, PoolType.COVERAGE);
// LEVERAGE CONTRIBUTION
address[] memory _userLeverageArr =
policyBookFacade.listUserLeveragePools(0, policyBookFacade.countUserLeveragePools());
for (uint256 i = 0; i < _userLeverageArr.length; i++) {
uint256 leverageContribution =
policyBookFacade.LUuserLeveragePool(_userLeverageArr[i]).mul(PERCENTAGE_100).div(
totalPoolLiquidity
);
uint256 leverageLoss = _claimAmount.mul(leverageContribution).div(PERCENTAGE_100);
_updatePoolLiquidity(_userLeverageArr[i], leverageLoss, 0, PoolType.LEVERAGE);
}
// REINSURANCE CONTRIBUTION
uint256 reinsuranceContribution =
(policyBookFacade.LUreinsurnacePool().add(policyBookFacade.VUreinsurnacePool()))
.mul(PERCENTAGE_100)
.div(totalPoolLiquidity);
uint256 reinsuranceLoss = _claimAmount.mul(reinsuranceContribution).div(PERCENTAGE_100);
_updatePoolLiquidity(address(reinsurancePool), reinsuranceLoss, 0, PoolType.REINSURANCE);
}
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external override onlyPolicyBook broadcastBalancing {
_withdrawFromLiquidityCushion(_sender, _stblAmount);
if (_isLeveragePool) {
leveragePoolBalance[_msgSender()] = leveragePoolBalance[_msgSender()].sub(_stblAmount);
} else {
regularCoverageBalance[_msgSender()] = regularCoverageBalance[_msgSender()].sub(
_stblAmount
);
}
}
function setMaintainer(address _newMainteiner) public onlyOwner {
require(_newMainteiner != address(0), "CP: invalid maintainer address");
maintainer = _newMainteiner;
}
function pauseLiquidityCushionRebalancing(bool _paused) public onlyOwner {
require(_paused != isLiqCushionPaused, "CP: invalid paused state");
isLiqCushionPaused = _paused;
}
function automateHardRebalancing(bool _isAutomatic) public onlyOwner {
require(_isAutomatic != automaticHardRebalancing, "CP: invalid state");
automaticHardRebalancing = _isAutomatic;
}
function _withdrawFromLiquidityCushion(address _sender, uint256 _stblAmount)
internal
broadcastBalancing
{
require(liquidityCushionBalance >= _stblAmount, "CP: insuficient liquidity");
liquidityCushionBalance = liquidityCushionBalance.sub(_stblAmount);
virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.sub(_stblAmount);
stblToken.safeTransfer(_sender, _stblAmount);
}
function _calcReinsurancePoolPremium(PremiumFactors memory factors)
internal
pure
returns (uint256)
{
return (factors.premiumPerDeployment.mul(factors.vStblDeployedByRP).div(PRECISION));
}
function _calcUserLeveragePoolPremium(PremiumFactors memory factors) internal {
address[] memory _userLeverageArr =
factors.policyBookFacade.listUserLeveragePools(0, factors.userLeveragePoolsCount);
uint256 premium;
uint256 _participatedLeverageAmount;
for (uint256 i = 0; i < _userLeverageArr.length; i++) {
_participatedLeverageAmount = clacParticipatedLeverageAmount(
factors,
_userLeverageArr[i]
);
premium = (
factors.premiumPerDeployment.mul(_participatedLeverageAmount).div(PRECISION)
);
leveragePoolBalance[_userLeverageArr[i]] = leveragePoolBalance[_userLeverageArr[i]]
.add(premium);
ILeveragePortfolio(_userLeverageArr[i]).addPolicyPremium(
factors.epochsNumber,
DecimalsConverter.convertTo18(premium, stblDecimals)
);
}
}
function clacParticipatedLeverageAmount(
PremiumFactors memory factors,
address userLeveragePool
) internal view returns (uint256) {
return
DecimalsConverter
.convertFrom18(
factors.policyBookFacade.LUuserLeveragePool(userLeveragePool),
stblDecimals
)
.mul(leveragePortfolioView.calcM(factors.poolUtilizationRation, userLeveragePool))
.div(PERCENTAGE_100);
}
function _calcCoveragePoolPremium(PremiumFactors memory factors)
internal
pure
returns (uint256)
{
return factors.premiumPerDeployment.mul(factors.vStblOfCP).div(PRECISION);
}
function getDepositAndWithdraw(uint256 _requiredLiquidity)
internal
view
returns (uint256 deposit, uint256 withdraw)
{
uint256 _availableBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance);
if (_requiredLiquidity > _availableBalance) {
withdraw = _requiredLiquidity.sub(_availableBalance);
} else if (_requiredLiquidity < _availableBalance) {
deposit = _availableBalance.sub(_requiredLiquidity);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFacade.sol";
interface ICapitalPool {
struct PremiumFactors {
uint256 epochsNumber;
uint256 premiumPrice;
uint256 vStblDeployedByRP;
uint256 vStblOfCP;
uint256 poolUtilizationRation;
uint256 premiumPerDeployment;
uint256 userLeveragePoolsCount;
IPolicyBookFacade policyBookFacade;
}
enum PoolType {COVERAGE, LEVERAGE, REINSURANCE}
function virtualUsdtAccumulatedBalance() external view returns (uint256);
function liquidityCushionBalance() external view returns (uint256);
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() external;
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external;
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
/// @param _isLeveragePool bool wether the pool is ULP or CP(policybook)
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
function rebalanceDuration() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityBridgeContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a1_ProtocolConstant uint256 A1 protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
function updateLiquidity(uint256 _lostLiquidity) external;
function forceUpdateBMICoverStakingRewardMultiplier() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./ILeveragePortfolio.sol";
import "./IUserLeveragePool.sol";
interface ILeveragePortfolioView {
function calcM(uint256 poolUR, address leveragePoolAddress) external view returns (uint256);
function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors)
external
view
returns (uint256);
function calcBMIMultiplier(IUserLeveragePool.BMIMultiplierFactors memory factors)
external
view
returns (uint256);
function getPolicyBookFacade(address _policybookAddress)
external
view
returns (IPolicyBookFacade _coveragePool);
function calcNetMPLn(
ILeveragePortfolio.LeveragePortfolio leveragePoolType,
address _policyBookFacade
) external view returns (uint256 _netMPLn);
function calcMaxVirtualFunds(address policyBookAddress, uint256 vStableWeight)
external
returns (uint256 _amountToDeploy, uint256 _maxAmount);
function calcvStableFormulaforAllPools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityRegistry {
struct LiquidityInfo {
address policyBookAddr;
uint256 lockedAmount;
uint256 availableAmount;
uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin
}
struct WithdrawalRequestInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableLiquidity;
uint256 readyToWithdrawDate;
uint256 endWithdrawDate;
}
struct WithdrawalSetInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableSTBLAmount;
}
function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external;
function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external;
function removeExpiredWithdrawalRequest(address _userAddr, address _policyBookAddr) external;
function getPolicyBooksArrLength(address _userAddr) external view returns (uint256);
function getPolicyBooksArr(address _userAddr)
external
view
returns (address[] memory _resultArr);
function getLiquidityInfos(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (LiquidityInfo[] memory _resultArr);
function getWithdrawalRequests(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr);
function getWithdrawalSet(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr);
function registerWithdrawl(address _policyBook, address _users) external;
function getAllPendingWithdrawalRequestsAmount()
external
returns (uint256 _totalWithdrawlAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external returns (uint256);
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
///@notice for doing defi hard rebalancing, access: policyBookFacade
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
address _insuranceContract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
function addLiquidityAndStakeFor(
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
///@dev in case ur changed of the pools by commit a claim or policy expired
function reevaluateProvidedLeverageStable() external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
function listUserLeveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _userLeveragePools);
function countUserLeveragePools() external view returns (uint256);
/// @notice get utilization rate of the pool on chain
function getUtilizationRatioPercentage(bool withLeverage) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IUserLeveragePool {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BMIMultiplierFactors {
uint256 poolMultiplier;
uint256 leverageProvided;
uint256 multiplier;
}
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function userLiquidity(address account) external view returns (uint256);
function a2_ProtocolConstant() external view returns (uint256);
function EPOCH_DURATION() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function epochStartTime() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __UserLeveragePool_init(
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liqudityAmount) external;
// /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
// /// @param _liquidityHolderAddr is address of address to assign cover
// /// @param _liqudityAmount is amount of stable coin tokens to secure
// function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
function getAPY() external view returns (uint256);
function whitelisted() external view returns (bool);
function whitelist(bool _whitelisted) external;
/// @notice set max total liquidity for the pool
/// @param _maxCapacities uint256 the max total liquidity
function setMaxCapacities(uint256 _maxCapacities) external;
function setA2_ProtocolConstant(uint256 _a2_ProtocolConstant) external;
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max liquidity of the pool
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is becuase to follow the same function in policy book
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is becuase to follow the same function in policy book
/// @return _bmiXRatio is multiplied by 10**18. To get STBL representation
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is becuase to follow the same function in policy book
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IYieldGenerator {
enum DefiProtocols {AAVE, COMPOUND, YEARN}
struct DefiProtocol {
uint256 targetAllocation;
uint256 currentAllocation;
uint256 rebalanceWeight;
uint256 depositedAmount;
bool whiteListed;
bool threshold;
bool withdrawMax;
// new state post v2
uint256 totalValue;
uint256 depositCost;
}
/// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to deposit
function deposit(uint256 amount) external returns (uint256);
/// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to withdraw
function withdraw(uint256 amount) external returns (uint256);
/// @notice set the protocol settings for each defi protocol (allocations, whitelisted, depositCost), access: owner
/// @param whitelisted bool[] list of whitelisted values for each protocol
/// @param allocations uint256[] list of allocations value for each protocol
/// @param depositCost uint256[] list of depositCost values for each protocol
function setProtocolSettings(
bool[] calldata whitelisted,
uint256[] calldata allocations,
uint256[] calldata depositCost
) external;
/// @notice Claims farmed tokens and sends it to the reinsurance pool
function claimRewards() external;
/// @notice returns defi protocol info by its index
/// @param index uint256 the index of the defi protocol
function defiProtocol(uint256 index)
external
view
returns (
uint256 _targetAllocation,
uint256 _currentAllocation,
uint256 _rebalanceWeight,
uint256 _depositedAmount,
bool _whiteListed,
bool _threshold,
uint256 _totalValue,
uint256 _depositCost
);
function reevaluateDefiProtocolBalances()
external
returns (uint256 _totalDeposit, uint256 _lostAmount);
function defiHardRebalancing() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
/**
* @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.7.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) {
_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.7.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.7.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: MIT
pragma solidity ^0.7.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) {
// 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);
}
}
}
}
|
_rebalanceDuration parameter passes in seconds
|
function setRebalanceDuration(uint256 _rebalanceDuration) public onlyOwner {
require(_rebalanceDuration <= 7 days, "CP: invalid rebalance duration");
rebalanceDuration = _rebalanceDuration;
}
| 1,171,469 |
pragma solidity ^0.4.8;
import "./SmsCoin.sol";
contract SMSReward {
SMSCoin smscoin; // SMS contract instance
address[] whiteListAddress;
event Log(string, uint);
address owner;
uint public totalSupply;
uint256 public constant decimals = 3;
uint256 public constant UNIT = 10 ** decimals;
mapping(address => address) public userStructs;
event Exists(string exists);
event Message(uint256 holderProfit);
event Transfer(address indexedFrom, address indexedTo, uint value);
mapping(address => bool) reward; // mapping to store user reward status
mapping(address => bool) profitAllowances;
mapping(address => uint) profitOnAddress;
uint bronzeRatio = 24;
uint goldRatio = 32;
uint platinumRatio = 44;
uint public totalClassRatio = 0;
uint public etherBalance = 0;
uint public lastProfitInETH;
mapping(address => uint) public classRatios;
// Modifier for owner
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
// Constructor which takes address of smart contract
function SMSReward(address smsCoinAddress) public {
owner = msg.sender;
smscoin = SMSCoin(smsCoinAddress);
}
// Whitelist address to be allowed in Profit distribution list
function addWhiteListAddress(address[] addresses) external onlyOwner {
for (uint i = 0; i < addresses.length; i++) {
profitAllowances[addresses[i]] = true;
if (whiteListAddress.length > 0) {
if (userStructs[addresses[i]] != addresses[i]) {
userStructs[addresses[i]] = addresses[i];
whiteListAddress.push(addresses[i]);
}
} else {
userStructs[addresses[i]] = addresses[i];
whiteListAddress.push(addresses[i]);
}
}
}
// Whitelist address to remove from Profit distribution list
function removeWhiteListAddress(address[] addresses) external onlyOwner {
for (uint i = 0; i < addresses.length; i++) {
profitAllowances[addresses[i]] = false;
for (uint j = 0; j < whiteListAddress.length; j++) {
if (whiteListAddress[j] == addresses[i]) {
delete whiteListAddress[j];
}
}
}
}
// Checking if the address is in the whitelist
function checkWhitelistExist(address addr) external returns(bool success) {
if (profitAllowances[addr]) {
Exists("Exist");
return true;
} else {
Exists("Not Exist");
return false;
}
}
// Should be called after adding all the whitelist addresses
function sendEthToContract() external payable onlyOwner {
// ------------ Get ETH into contract ------------
lastProfitInETH = msg.value;
etherBalance += msg.value;
// ------------ Calculating Class ratio ------------
totalClassRatio = 0;
for (uint i = 0; i < whiteListAddress.length; i++) {
// Calculating class ratio
if (smscoin.balanceOf(whiteListAddress[i]) < 10 * UNIT) // Less than 10 tokens
classRatios[whiteListAddress[i]] = (smscoin.balanceOf(whiteListAddress[i]) * bronzeRatio) / 100;
else if (smscoin.balanceOf(whiteListAddress[i]) < 20 * UNIT) // Less than 20 tokens
classRatios[whiteListAddress[i]] = (smscoin.balanceOf(whiteListAddress[i]) * goldRatio) / 100;
else // From 20 tokens
classRatios[whiteListAddress[i]] = (smscoin.balanceOf(whiteListAddress[i]) * platinumRatio) / 100;
// Accumulating class ratio
totalClassRatio += classRatios[whiteListAddress[i]];
}
// ------------ Calculating Profit ------------
for (i = 0; i < whiteListAddress.length; i++) {
profitOnAddress[whiteListAddress[i]] += (classRatios[whiteListAddress[i]] * lastProfitInETH) / totalClassRatio;
// Set reward availability
setRewardStatus(whiteListAddress[i], true);
}
}
function checkProfit(address addr) public constant returns(uint) {
return profitOnAddress[addr];
}
// Function to get dividendend on requesting
function requestDividends() external {
if (!getRewardStatus(msg.sender))
revert();
if (!profitAllowances[msg.sender] && profitOnAddress[msg.sender] > 0)
revert();
// Checking enough ETH on balance to be transferred
if (etherBalance - profitOnAddress[msg.sender] >= 0) {
etherBalance -= profitOnAddress[msg.sender];
msg.sender.transfer(profitOnAddress[msg.sender]);
profitOnAddress[msg.sender] = 0;
} else
revert();
// Reset reward status
setRewardStatus(msg.sender, false);
}
// Transfer available ETH from the contract to owner
// STRANGE BEHAVIOR, NEED TO BE CHECKED
function drainETH() external onlyOwner {
owner.transfer(this.balance);
etherBalance = 0;
}
// Get reward status
function getRewardStatus(address addr) view private returns(bool isReward) {
return reward[addr];
}
// Set reward status
function setRewardStatus(address addr, bool status) private {
reward[addr] = status;
}
}
|
Constructor which takes address of smart contract
|
function SMSReward(address smsCoinAddress) public {
owner = msg.sender;
smscoin = SMSCoin(smsCoinAddress);
}
| 5,526,983 |
/**
*Submitted for verification at Etherscan.io on 2022-04-13
*/
// Sources flattened with hardhat v2.8.2 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File @openzeppelin/contracts/utils/[email protected]
// 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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^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 Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts/proxy/beacon/[email protected]
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File @openzeppelin/contracts/proxy/ERC1967/[email protected]
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @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 Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @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 Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// File @openzeppelin/contracts/proxy/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is ERC1967Upgrade {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
}
// File contracts/upgrade/Owned.sol
pragma solidity ^0.8.0;
// Modified from https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
/// @dev Change constructor to initialize function for upgradeable contract
function initializeOwner(address _owner) internal {
require(owner == address(0), "Already initialized");
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File contracts/upgrade/Pausable.sol
pragma solidity ^0.8.0;
// Modified from https://docs.synthetix.io/contracts/source/contracts/pausable
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
/// @dev Change constructor to initialize function for upgradeable contract
function initializePausable(address _owner) internal {
super.initializeOwner(_owner);
require(owner != address(0), "Owner must be set");
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = block.timestamp;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
// File contracts/upgrade/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 aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
/// @dev Change constructor to initialize function for upgradeable contract
function initializeReentrancyGuard() internal {
require(_guardCounter == 0, "Already initialized");
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File contracts/interfaces/IDepositCompound.sol
pragma solidity >=0.5.0 <0.9.0;
// Curve DepositCompound contract interface
interface IDepositCompound {
function underlying_coins(int128 arg0) external view returns (address);
function token() external view returns (address);
function add_liquidity(uint256[2] calldata uamounts, uint256 min_mint_amount) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata min_uamounts) external;
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust) external;
}
// File contracts/interfaces/IConvexBaseRewardPool.sol
pragma solidity >=0.5.0 <0.9.0;
interface IConvexBaseRewardPool {
// Views
function rewards(address account) external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function stakingToken() external view returns (address);
function rewardToken() external view returns (address);
function totalSupply() external view returns (uint256);
// Mutative
function getReward(address _account, bool _claimExtras) external returns (bool);
function stake(uint256 _amount) external returns (bool);
function withdraw(uint256 amount, bool claim) external returns (bool);
function withdrawAll(bool claim) external returns (bool);
function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);
function withdrawAllAndUnwrap(bool claim) external returns (bool);
}
// File contracts/interfaces/IConvexBooster.sol
pragma solidity >=0.5.0 <0.9.0;
interface IConvexBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function poolInfo(uint256 _pid) view external returns (PoolInfo memory);
function crv() external view returns (address);
function minter() external view returns (address);
function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool);
function depositAll(uint256 _pid, bool _stake) external returns(bool);
}
// File contracts/interfaces/IPancakePair.sol
pragma solidity >=0.5.0 <0.9.0;
interface IPancakePair {
function token0() external returns (address);
function token1() external returns (address);
}
// File contracts/interfaces/IConverterUniV3.sol
pragma solidity >=0.5.0 <0.9.0;
interface IConverterUniV3 {
function NATIVE_TOKEN() external view returns (address);
function convert(
address _inTokenAddress,
uint256 _amount,
uint256 _convertPercentage,
address _outTokenAddress,
uint256 _minReceiveAmount,
address _recipient
) external;
function convertAndAddLiquidity(
address _inTokenAddress,
uint256 _amount,
address _outTokenAddress,
uint256 _minReceiveAmountSwap,
uint256 _minInTokenAmountAddLiq,
uint256 _minOutTokenAmountAddLiq,
address _recipient
) external;
function removeLiquidityAndConvert(
IPancakePair _lp,
uint256 _lpAmount,
uint256 _minToken0Amount,
uint256 _minToken1Amount,
uint256 _token0Percentage,
address _recipient
) external;
function convertUniV3(
address _inTokenAddress,
uint256 _amount,
uint256 _convertPercentage,
address _outTokenAddress,
uint256 _minReceiveAmount,
address _recipient,
bytes memory _path
) external;
}
// File contracts/interfaces/IWeth.sol
pragma solidity >=0.7.0;
interface IWETH {
function balanceOf(address account) external view returns (uint256);
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address dst, uint256 wad) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 wad
) external returns (bool);
}
// File contracts/curve_convex_farm/AutoCompoundCurveConvex.sol
pragma solidity ^0.8.0;
// Modified from https://docs.synthetix.io/contracts/source/contracts/stakingrewards
/// @title A wrapper contract over Convex Booster and BaseRewardPool contract that allows single asset in/out.
/// 1. User provide token0 or token1
/// 2. contract converts half to the other token and provide liquidity on Curve
/// 3. stake LP token via Convex Booster contract
/// @dev Be aware that staking entry is Convex Booster contract while withdraw/getReward entry is BaseRewardPool contract.
/// @notice Asset tokens are token0 and token1. Staking token is the LP token of token0/token1.
contract AutoCompoundCurveConvex is ReentrancyGuard, Pausable, UUPSUpgradeable {
using SafeERC20 for IERC20;
struct BalanceDiff {
uint256 balBefore;
uint256 balAfter;
uint256 balDiff;
}
/* ========== STATE VARIABLES ========== */
string public name;
uint256 public pid; // Pool ID in Convex Booster
IConverterUniV3 public converter;
IERC20 public lp;
IERC20 public token0;
IERC20 public token1;
IERC20 public crv;
IERC20 public cvx;
IERC20 public BCNT;
IDepositCompound public curveDepositCompound;
IConvexBooster public convexBooster;
IConvexBaseRewardPool public convexBaseRewardPool;
/// @dev Piggyback on BaseRewardPool' reward accounting
mapping(address => uint256) internal _userRewardPerTokenPaid;
mapping(address => uint256) internal _rewards;
uint256 internal _totalSupply;
mapping(address => uint256) internal _balances;
uint256 public lpAmountCompounded;
address public operator;
bytes public cvxUniV3SwapPath;
bytes public bcntUniV3SwapPath;
/* ========== FALLBACKS ========== */
receive() external payable {}
/* ========== CONSTRUCTOR ========== */
function initialize(
string memory _name,
uint256 _pid,
address _owner,
address _operator,
IConverterUniV3 _converter,
address _curveDepositCompound,
address _convexBooster,
address _convexBaseRewardPool,
address _BCNT
) external {
require(keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("")), "Already initialized");
super.initializePausable(_owner);
super.initializeReentrancyGuard();
name = _name;
pid = _pid;
operator = _operator;
converter = _converter;
curveDepositCompound = IDepositCompound(_curveDepositCompound);
lp = IERC20(curveDepositCompound.token());
token0 = IERC20(curveDepositCompound.underlying_coins(0));
token1 = IERC20(curveDepositCompound.underlying_coins(1));
convexBooster = IConvexBooster(_convexBooster);
convexBaseRewardPool = IConvexBaseRewardPool(_convexBaseRewardPool);
crv = IERC20(convexBaseRewardPool.rewardToken());
require(address(convexBooster.crv()) == address(crv));
cvx = IERC20(convexBooster.minter());
BCNT = IERC20(_BCNT);
}
/* ========== VIEWS ========== */
/// @dev Get the implementation contract of this proxy contract.
/// Only to be used on the proxy contract. Otherwise it would return zero address.
function implementation() external view returns (address) {
return _getImplementation();
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/// @notice Get the reward share earned by specified account.
function _share(address account) public view returns (uint256) {
uint256 rewardPerToken = convexBaseRewardPool.rewardPerToken();
return (_balances[account] * (rewardPerToken - _userRewardPerTokenPaid[account]) / (1e18)) + _rewards[account];
}
/// @notice Get the total reward share in this contract.
/// @notice Total reward is tracked with `_rewards[address(this)]` and `_userRewardPerTokenPaid[address(this)]`
function _shareTotal() public view returns (uint256) {
uint256 rewardPerToken = convexBaseRewardPool.rewardPerToken();
return (_totalSupply * (rewardPerToken - _userRewardPerTokenPaid[address(this)]) / (1e18)) + _rewards[address(this)];
}
/// @notice Get the compounded LP amount earned by specified account.
function earned(address account) public view returns (uint256) {
uint256 rewardsShare;
if (account == address(this)){
rewardsShare = _shareTotal();
} else {
rewardsShare = _share(account);
}
uint256 earnedCompoundedLPAmount;
if (rewardsShare > 0) {
uint256 totalShare = _shareTotal();
// Earned compounded LP amount is proportional to how many rewards this account has
// among total rewards
earnedCompoundedLPAmount = lpAmountCompounded * rewardsShare / totalShare;
}
return earnedCompoundedLPAmount;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _convertAndAddLiquidity(
bool isToken0,
bool shouldTransferFromSender,
uint256 amount,
uint256 minLiqAddedAmount
) internal returns (uint256 lpAmount) {
require(amount > 0, "Cannot stake 0");
uint256 lpAmountBefore = lp.balanceOf(address(this));
uint256 token0AmountBefore = token0.balanceOf(address(this));
uint256 token1AmountBefore = token1.balanceOf(address(this));
// Add liquidity
uint256[2] memory uamounts;
if (isToken0) {
if (shouldTransferFromSender) {
token0.safeTransferFrom(msg.sender, address(this), amount);
}
uamounts[0] = amount;
uamounts[1] = 0;
token0.safeApprove(address(curveDepositCompound), amount);
curveDepositCompound.add_liquidity(uamounts, minLiqAddedAmount);
} else {
if (shouldTransferFromSender) {
token1.safeTransferFrom(msg.sender, address(this), amount);
}
uamounts[0] = 0;
uamounts[1] = amount;
token1.safeApprove(address(curveDepositCompound), amount);
curveDepositCompound.add_liquidity(uamounts, minLiqAddedAmount);
}
uint256 lpAmountAfter = lp.balanceOf(address(this));
uint256 token0AmountAfter = token0.balanceOf(address(this));
uint256 token1AmountAfter = token1.balanceOf(address(this));
lpAmount = (lpAmountAfter - lpAmountBefore);
// Return leftover token to msg.sender
if (shouldTransferFromSender && (token0AmountAfter - token0AmountBefore) > 0) {
token0.safeTransfer(msg.sender, (token0AmountAfter - token0AmountBefore));
}
if (shouldTransferFromSender && (token1AmountAfter - token1AmountBefore) > 0) {
token1.safeTransfer(msg.sender, (token1AmountAfter - token1AmountBefore));
}
}
/// @dev Be aware that staking entry is Convex Booster contract while withdraw/getReward entry is BaseRewardPool contract.
/// This is because staking token for BaseRewardPool is the deposit token that can only minted by Booster.
/// Booster.deposit() will do some processing and stake into BaseRewardPool for us.
function _stake(address staker, uint256 lpAmount) internal {
lp.safeApprove(address(convexBooster), lpAmount);
convexBooster.deposit(
pid,
lpAmount,
true // True indicate to also stake into BaseRewardPool
);
_totalSupply = _totalSupply + lpAmount;
_balances[staker] = _balances[staker] + lpAmount;
emit Staked(staker, lpAmount);
}
/// @notice Taken token0 or token1 in, provide liquidity in Curve and stake
/// the LP token into Convex contract. Leftover token0 or token1 will be returned to msg.sender.
/// @param isToken0 Determine if token0 is the token msg.sender going to use for staking, token1 otherwise
/// @param amount Amount of token0 or token1 to stake
/// @param minLiqAddedAmount The minimum amount of LP token received when adding liquidity
function stake(
bool isToken0,
uint256 amount,
uint256 minLiqAddedAmount
) public nonReentrant notPaused updateReward(msg.sender) {
uint256 lpAmount = _convertAndAddLiquidity(isToken0, true, amount, minLiqAddedAmount);
_stake(msg.sender, lpAmount);
}
/// @notice Take LP tokens and stake into Convex contract.
/// @param lpAmount Amount of LP tokens to stake
function stakeWithLP(uint256 lpAmount) public nonReentrant notPaused updateReward(msg.sender) {
lp.safeTransferFrom(msg.sender, address(this), lpAmount);
_stake(msg.sender, lpAmount);
}
// /// @notice Take native tokens, convert to wrapped native tokens, convert half to the other token, provide liquidity and stake
// /// the LP tokens into Convex contract. Leftover token0 or token1 will be returned to msg.sender.
// /// @param minReceivedTokenAmountSwap Minimum amount of token0 or token1 received when swapping one for the other
// /// @param minToken0AmountAddLiq The minimum amount of token0 received when adding liquidity
// /// @param minToken1AmountAddLiq The minimum amount of token1 received when adding liquidity
// function stakeWithNative(
// uint256 minReceivedTokenAmountSwap,
// uint256 minToken0AmountAddLiq,
// uint256 minToken1AmountAddLiq
// ) public payable nonReentrant notPaused updateReward(msg.sender) {
// revert("Not supported");
// }
function _removeLP(IERC20 token, bool toToken0, uint256 amount, uint256 minAmountReceived) internal returns (uint256) {
uint256 balBefore = token.balanceOf(address(this));
lp.safeApprove(address(curveDepositCompound), amount);
curveDepositCompound.remove_liquidity_one_coin(
amount,
toToken0 ? int128(0) : int128(1),
minAmountReceived,
true // Donate dust
);
uint256 balAfter = token.balanceOf(address(this));
return balAfter - balBefore;
}
/// @notice Withdraw stake from BaseRewardPool, remove liquidity and convert one asset to another.
/// @param toToken0 Determine to convert all to token0 or token 1
/// @param minAmountReceived The minimum amount of token0 or token1 received when removing liquidity
/// @param amount Amount of stake to withdraw
function withdraw(
bool toToken0,
uint256 minAmountReceived,
uint256 amount
) public nonReentrant updateReward(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
// Update records:
// substract withdrawing LP amount from total LP amount staked
_totalSupply = (_totalSupply - amount);
// substract withdrawing LP amount from user's balance
_balances[msg.sender] = (_balances[msg.sender] - amount);
// Withdraw and unwrap to LP token
convexBaseRewardPool.withdrawAndUnwrap(
amount,
false // No need to getReward when withdraw
);
IERC20 token = toToken0 ? token0 : token1;
uint256 receivedTokenAmount = _removeLP(token, toToken0, amount, minAmountReceived);
token.safeTransfer(msg.sender, receivedTokenAmount);
emit Withdrawn(msg.sender, amount);
}
/// @notice Withdraw LP tokens from BaseRewardPool contract and return to user.
/// @param lpAmount Amount of LP tokens to withdraw
function withdrawWithLP(uint256 lpAmount) public nonReentrant notPaused updateReward(msg.sender) {
require(lpAmount > 0, "Cannot withdraw 0");
// Update records:
// substract withdrawing LP amount from total LP amount staked
_totalSupply = (_totalSupply - lpAmount);
// substract withdrawing LP amount from user's balance
_balances[msg.sender] = (_balances[msg.sender] - lpAmount);
// Withdraw and unwrap to LP token
convexBaseRewardPool.withdrawAndUnwrap(
lpAmount,
false // No need to getReward when withdraw
);
lp.safeTransfer(msg.sender, lpAmount);
emit Withdrawn(msg.sender, lpAmount);
}
// function _validateIsNativeToken() internal view returns (address, bool) {
// address NATIVE_TOKEN = converter.NATIVE_TOKEN();
// bool isToken0 = NATIVE_TOKEN == address(token0);
// require(isToken0 || NATIVE_TOKEN == address(token1), "Native token is not either token0 or token1");
// return (NATIVE_TOKEN, isToken0);
// }
// /// @notice Withdraw stake from BaseRewardPool, remove liquidity and convert one asset to another.
// /// @param minToken0AmountConverted The minimum amount of token0 received when removing liquidity
// /// @param minToken1AmountConverted The minimum amount of token1 received when removing liquidity
// /// @param amount Amount of stake to withdraw
// function withdrawWithNative(
// uint256 minToken0AmountConverted,
// uint256 minToken1AmountConverted,
// uint256 amount
// ) public nonReentrant updateReward(msg.sender) {
// revert("Not supported");
// }
/// @notice Get the reward out and convert one asset to another. Note that reward is LP token.
/// @param minAmountToken0Received The minimum amount of token0 received when removing liquidity
/// @param minAmountBCNTReceived The minimum amount of BCNT received when converting token0 to BCNT
function getReward(
uint256 minAmountToken0Received,
uint256 minAmountBCNTReceived
) public updateReward(msg.sender) {
uint256 reward = _rewards[msg.sender];
uint256 totalReward = _rewards[address(this)];
if (reward > 0) {
// compoundedLPRewardAmount: based on user's reward and totalReward,
// determine how many compouned(read: extra) LP amount can user take away.
// NOTE: totalReward = _rewards[address(this)];
uint256 compoundedLPRewardAmount = lpAmountCompounded * reward / totalReward;
// Update records:
// substract user's rewards from totalReward
_rewards[msg.sender] = 0;
_rewards[address(this)] = (totalReward - reward);
// substract compoundedLPRewardAmount from lpAmountCompounded
lpAmountCompounded = (lpAmountCompounded - compoundedLPRewardAmount);
// Withdraw compounded LP and unwrap
convexBaseRewardPool.withdrawAndUnwrap(
compoundedLPRewardAmount,
false // No need to getReward when withdraw
);
// Remove LP and convert to token0
uint256 receivedToken0Amount = _removeLP(token0, true, compoundedLPRewardAmount, minAmountToken0Received);
// Convert token0 to BCNT via UniswapV3 pool
token0.approve(address(converter), receivedToken0Amount);
converter.convertUniV3(address(token0), receivedToken0Amount, 100, address(BCNT), minAmountBCNTReceived, msg.sender, bcntUniV3SwapPath);
emit RewardPaid(msg.sender, compoundedLPRewardAmount);
}
}
/// @notice Withdraw all stake from BaseRewardPool, remove liquidity, get the reward out and convert one asset to another.
/// @param toToken0 Determine to convert all to token0 or token 1
/// @param minAmountReceived The minimum amount of token0 or token1 received when removing liquidity
function exit(bool toToken0, uint256 minAmountReceived, uint256 minAmountBCNTReceived) external {
withdraw(toToken0, minAmountReceived, _balances[msg.sender]);
getReward(minAmountReceived, minAmountBCNTReceived);
}
/// @notice Withdraw all stake from BaseRewardPool, get the reward out and convert one asset to another.
/// @param minAmountReceived The minimum amount of token0 or token1 received when removing liquidity
function exitWithLP(uint256 minAmountReceived, uint256 minAmountBCNTReceived) external {
withdrawWithLP(_balances[msg.sender]);
getReward(minAmountReceived, minAmountBCNTReceived);
}
// /// @notice Withdraw all stake from BaseRewardPool, remove liquidity, get the reward out and convert one asset to another
// /// @param token0Percentage Determine what percentage of token0 to return to user. Any number between 0 to 100
// /// @param minToken0AmountConverted The minimum amount of token0 received when removing liquidity
// /// @param minToken1AmountConverted The minimum amount of token1 received when removing liquidity
// /// @param minTokenAmountConverted The minimum amount of token0 or token1 received when converting reward token to either one of them
// function exitWithNative(uint256 token0Percentage, uint256 minToken0AmountConverted, uint256 minToken1AmountConverted, uint256 minTokenAmountConverted) external {
// revert("Not supported");
// }
/* ========== RESTRICTED FUNCTIONS ========== */
/// @notice Get all reward out from BaseRewardPool contract, convert rewards to token0 and token1, provide liquidity and stake
/// the LP tokens back into BaseRewardPool contract.
/// @dev LP tokens staked this way will be tracked in `lpAmountCompounded`.
/// @param minCrvToToken0Swap The minimum amount of token0 received when swapping CRV to token0
/// @param minCvxToToken0Swap The minimum amount of token0 received when swapping CVX to token0
/// @param minLiqAddedAmount The minimum amount of LP token received when adding liquidity
function compound(
uint256 minCrvToToken0Swap,
uint256 minCvxToToken0Swap,
uint256 minLiqAddedAmount
) external nonReentrant updateReward(address(0)) onlyOperator {
// getReward will get us CRV and CVX
convexBaseRewardPool.getReward(address(this), true);
BalanceDiff memory lpAmountDiff;
lpAmountDiff.balBefore = lp.balanceOf(address(this));
BalanceDiff memory token0Diff;
token0Diff.balBefore = token0.balanceOf(address(this));
// Try convert CRV to token0
uint256 crvBalance = crv.balanceOf(address(this));
if (crvBalance > 0) {
crv.approve(address(converter), crvBalance);
try converter.convert(address(crv), crvBalance, 100, address(token0), minCrvToToken0Swap, address(this)) {
} catch Error(string memory reason) {
emit ConvertFailed(address(crv), address(token0), crvBalance, reason, bytes(""));
} catch (bytes memory lowLevelData) {
emit ConvertFailed(address(crv), address(token0), crvBalance, "", lowLevelData);
}
}
// Try convert CVX to token0
uint256 cvxBalance = cvx.balanceOf(address(this));
if (cvxBalance > 0) {
// Use UniV3 for CVX since CVX does not have enough liquidity in UniV2
cvx.approve(address(converter), cvxBalance);
try converter.convertUniV3(address(cvx), cvxBalance, 100, address(token0), minCvxToToken0Swap, address(this), cvxUniV3SwapPath) {
} catch Error(string memory reason) {
emit ConvertFailed(address(cvx), address(token0), cvxBalance, reason, bytes(""));
} catch (bytes memory lowLevelData) {
emit ConvertFailed(address(cvx), address(token0), cvxBalance, "", lowLevelData);
}
}
token0Diff.balAfter = token0.balanceOf(address(this));
token0Diff.balDiff = (token0Diff.balAfter - token0Diff.balBefore);
// Add liquidity if there are token0 converted
if (token0Diff.balDiff > 0) {
uint256[2] memory uamounts;
uamounts[0] = token0Diff.balDiff;
uamounts[1] = 0;
token0.safeApprove(address(curveDepositCompound), token0Diff.balDiff);
curveDepositCompound.add_liquidity(uamounts, minLiqAddedAmount);
lpAmountDiff.balAfter = lp.balanceOf(address(this));
lpAmountDiff.balDiff = (lpAmountDiff.balAfter - lpAmountDiff.balBefore);
// Add compounded LP tokens to lpAmountCompounded
lpAmountCompounded = lpAmountCompounded + lpAmountDiff.balDiff;
// Stake the compounded LP tokens back in
lp.safeApprove(address(convexBooster), lpAmountDiff.balDiff);
convexBooster.deposit(
pid,
lpAmountDiff.balDiff,
true // True indicate to also stake into BaseRewardPool
);
emit Compounded(lpAmountDiff.balDiff);
}
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
require(tokenAddress != address(lp), "Cannot withdraw the staking token");
IERC20(tokenAddress).safeTransfer(owner, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function updateCVXUniV3SwapPath(bytes calldata newPath) external onlyOperator {
cvxUniV3SwapPath = newPath;
emit UpdateCVXUniV3SwapPath(newPath);
}
function updateBCNTUniV3SwapPath(bytes calldata newPath) external onlyOperator {
bcntUniV3SwapPath = newPath;
emit UpdateBCNTUniV3SwapPath(newPath);
}
function updateOperator(address newOperator) external onlyOwner {
operator = newOperator;
emit UpdateOperator(newOperator);
}
function _authorizeUpgrade(address newImplementation) internal view override onlyOwner {}
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
uint256 rewardPerTokenStored = convexBaseRewardPool.rewardPerToken();
if (account != address(0)) {
_rewards[account] = _share(account);
_userRewardPerTokenPaid[account] = rewardPerTokenStored;
// Use _rewards[address(this)] to keep track of rewards earned by all accounts.
// NOTE: it does not count into the compounded reward because compouned reward
// are continuosly converted to LP tokens and user will be rewarded with
// compounded LP tokens instead of compounded rewards.
_rewards[address(this)] = _shareTotal();
_userRewardPerTokenPaid[address(this)] = rewardPerTokenStored;
}
_;
}
modifier onlyOperator() {
require(msg.sender == operator, "Only the contract operator may perform this action");
_;
}
/* ========== EVENTS ========== */
event UpdateCVXUniV3SwapPath(bytes newPath);
event UpdateBCNTUniV3SwapPath(bytes newPath);
event UpdateOperator(address newOperator);
event Staked(address indexed user, uint256 amount);
event ConvertFailed(address fromToken, address toToken, uint256 fromAmount, string reason, bytes lowLevelData);
event Compounded(uint256 lpAmount);
event RewardPaid(address indexed user, uint256 rewardLPAmount);
event Withdrawn(address indexed user, uint256 amount);
event Recovered(address token, uint256 amount);
}
|
Withdraw LP tokens from BaseRewardPool contract and return to user. lpAmount Amount of LP tokens to withdraw Update records: substract withdrawing LP amount from total LP amount staked substract withdrawing LP amount from user's balance Withdraw and unwrap to LP token
|
function withdrawWithLP(uint256 lpAmount) public nonReentrant notPaused updateReward(msg.sender) {
require(lpAmount > 0, "Cannot withdraw 0");
_totalSupply = (_totalSupply - lpAmount);
_balances[msg.sender] = (_balances[msg.sender] - lpAmount);
convexBaseRewardPool.withdrawAndUnwrap(
lpAmount,
);
lp.safeTransfer(msg.sender, lpAmount);
emit Withdrawn(msg.sender, lpAmount);
}
| 10,510,040 |
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint256 a, uint256 b)
internal
pure
returns (MathError, uint256)
{
uint256 c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (MathError, uint256) {
(MathError err0, uint256 sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
pragma solidity ^0.5.16;
//import "./CarefulMath.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint256 rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b)
internal
pure
returns (MathError, Exp memory)
{
(MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b)
internal
pure
returns (MathError, Exp memory)
{
(MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint256 scalar)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint256 scalar)
internal
pure
returns (MathError, uint256)
{
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 descaledMantissa) = divUInt(
a.mantissa,
scalar
);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp memory divisor)
internal
pure
returns (MathError, Exp memory)
{
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint256 numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint256 scalar, Exp memory divisor)
internal
pure
returns (MathError, uint256)
{
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b)
internal
pure
returns (MathError, Exp memory)
{
(MathError err0, uint256 doubleScaledProduct) = mulUInt(
a.mantissa,
b.mantissa
);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(
halfExpScale,
doubleScaledProduct
);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint256 product) = divUInt(
doubleScaledProductWithHalfScale,
expScale
);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint256 a, uint256 b)
internal
pure
returns (MathError, Exp memory)
{
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(
Exp memory a,
Exp memory b,
Exp memory c
) internal pure returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b)
internal
pure
returns (MathError, Exp memory)
{
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage)
internal
pure
returns (uint224)
{
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return
Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
contract CToken {
/*** User Interface ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account)
external
view
returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
}
contract getAccountLiquidity is Exponential, ComptrollerErrorReporter {
struct AccountLiquidityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowPlusEffects;
uint256 cTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
function getHypotheticalAccountLiquidity(
address account,
CToken[] memory assets,
uint256[] memory collateralFactorMantissa,
uint256[] memory underlyingPrice
)
public
view
returns (
Error,
uint256,
uint256,
uint256,
uint256
)
{
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint256 oErr;
MathError mErr;
// For each asset the account is in
//CToken[] memory assets = accountAssets[account];
for (uint256 i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(
oErr,
vars.cTokenBalance,
vars.borrowBalance,
vars.exchangeRateMantissa
) = asset.getAccountSnapshot(account);
if (oErr != 0) {
// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0, 0, 0);
}
//vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.collateralFactor = Exp({mantissa: collateralFactorMantissa[i]});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
//vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
vars.oraclePriceMantissa = underlyingPrice[i];
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(
vars.collateralFactor,
vars.exchangeRate,
vars.oraclePrice
);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0, 0, 0);
}
// sumCollateral += tokensToDenom * cTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(
vars.tokensToDenom,
vars.cTokenBalance,
vars.sumCollateral
);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrowPlusEffects
);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0, 0, 0);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (
Error.NO_ERROR,
vars.sumCollateral - vars.sumBorrowPlusEffects,
0,
vars.sumCollateral,
vars.sumBorrowPlusEffects
);
} else {
return (
Error.NO_ERROR,
0,
vars.sumBorrowPlusEffects - vars.sumCollateral,
vars.sumCollateral,
vars.sumBorrowPlusEffects
);
}
}
}
|
Divide a scalar by an Exp, then truncate to return an unsigned integer./
|
function divScalarByExpTruncate(uint256 scalar, Exp memory divisor)
internal
pure
returns (MathError, uint256)
{
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
| 1,271,128 |
./partial_match/1/0x102a796Eb323C90Ea233Cf0cf454AfA7D0441252/sources/UiPoolDataProvider.sol
|
IVariableDebtToken Aave Defines the basic interface for a variable debt token./
|
interface IVariableDebtToken is IScaledBalanceToken {
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
event Burn(address indexed user, uint256 amount, uint256 index);
function burn(
address user,
uint256 amount,
uint256 index
) external;
}
}
| 3,879,268 |
pragma solidity ^0.4.17;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
// function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
contract FootballerAccessControl{
///@dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
//The address of manager (the account or contracts) that can execute action within the role.
address public managerAddress;
///@dev keeps track whether the contract is paused.
bool public paused = false;
function FootballerAccessControl() public {
managerAddress = msg.sender;
}
/// @dev Access modifier for manager-only functionality
modifier onlyManager() {
require(msg.sender == managerAddress);
_;
}
///@dev assigns a new address to act as the Manager.Only available to the current Manager.
function setManager(address _newManager) external onlyManager {
require(_newManager != address(0));
managerAddress = _newManager;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by manager to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyManager whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the manager,
/// since one reason we may pause the contract is when manager accounts are compromised.
/// @notice This is public rather than external so it can be called by derived contracts.
function unpause() public onlyManager {
// can't unpause if contract was upgraded
paused = false;
}
}
contract FootballerBase is FootballerAccessControl {
using SafeMath for uint256;
/*** events ***/
event Create(address owner, uint footballerId);
event Transfer(address _from, address _to, uint256 tokenId);
uint private randNonce = 0;
//球员/球星 属性
struct footballer {
uint price; //球员-价格 , 球星-一口价 单位wei
//球员的战斗属性
uint defend; //防御
uint attack; //进攻
uint quality; //素质
}
//存球星和球员
footballer[] public footballers;
//将球员的id和球员的拥有者对应起来
mapping (uint256 => address) public footballerToOwner;
//记录拥有者有多少球员,在balanceOf()内部使用来解决所有权计数
mapping (address => uint256) public ownershipTokenCount;
//从footballID 到 已批准调用transferFrom()的地址的映射
//每个球员只能有一个批准的地址。零值表示没有批准
mapping (uint256 => address) public footballerToApproved;
// 将特定球员的所有权 赋给 某个地址
function _transfer(address _from, address _to, uint256 _tokenId) internal {
footballerToApproved[_tokenId] = address(0);
ownershipTokenCount[_to] = ownershipTokenCount[_to].add(1);
footballerToOwner[_tokenId] = _to;
ownershipTokenCount[_from] = ownershipTokenCount[_from].sub(1);
emit Transfer(_from, _to, _tokenId);
}
//管理员用于投放球星,和createStar函数一起使用,才能将球星完整信息保存起来
function _createFootballerStar(uint _price,uint _defend,uint _attack, uint _quality) internal onlyManager returns(uint) {
footballer memory _player = footballer({
price:_price,
defend:_defend,
attack:_attack,
quality:_quality
});
uint newFootballerId = footballers.push(_player) - 1;
footballerToOwner[newFootballerId] = managerAddress;
ownershipTokenCount[managerAddress] = ownershipTokenCount[managerAddress].add(1);
//记录这个球星可以进行交易
footballerToApproved[newFootballerId] = managerAddress;
require(newFootballerId == uint256(uint32(newFootballerId)));
emit Create(managerAddress, newFootballerId);
return newFootballerId;
}
//用于当用户买卡包时,随机生成球员
function createFootballer () internal returns (uint) {
footballer memory _player = footballer({
price: 0,
defend: _randMod(20,80),
attack: _randMod(20,80),
quality: _randMod(20,80)
});
uint newFootballerId = footballers.push(_player) - 1;
// require(newFootballerId == uint256(uint32(newFootballerId)));
footballerToOwner[newFootballerId] = msg.sender;
ownershipTokenCount[msg.sender] =ownershipTokenCount[msg.sender].add(1);
emit Create(msg.sender, newFootballerId);
return newFootballerId;
}
// 生成一个从 _min 到 _max 范围内的随机数(不包括 _max)
function _randMod(uint _min, uint _max) private returns(uint) {
randNonce++;
uint modulus = _max - _min;
return uint(keccak256(now, msg.sender, randNonce)) % modulus + _min;
}
}
contract FootballerOwnership is FootballerBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CyptoWorldCup";
string public constant symbol = "CWC";
function implementsERC721() public pure returns (bool) {
return true;
}
//判断一个给定的地址是不是现在某个球员的拥有者
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return footballerToOwner[_tokenId] == _claimant;
}
//判断一个给定的地址现在对于某个球员 是不是有 transferApproval
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return footballerToApproved[_tokenId] == _claimant;
}
//给某地址的用户 对 球员有transfer的权利
function _approve(uint256 _tokenId, address _approved) internal {
footballerToApproved[_tokenId] = _approved;
}
//返回 owner 拥有的球员数
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
//转移 球员 给 另一个地址
function transfer(address _to, uint256 _tokenId) public whenNotPaused {
require(_to != address(0));
require(_to != address(this));
//只能send自己的球员
require(_owns(msg.sender, _tokenId));
//重新分配所有权,清除待批准 approvals ,发出转移事件
_transfer(msg.sender, _to, _tokenId);
}
//授予另一个地址通过transferFrom()转移特定球员的权利。
function approve(address _to, uint256 _tokenId) external whenNotPaused {
//只有球员的拥有者才有资格决定要把这个权利给谁
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
emit Approval(msg.sender, _to, _tokenId);
}
//转让由另一个地址所拥有的球员,该地址之前已经获得所有者的转让批准
function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused {
require(_to != address(0));
//不允许转让本合同以防止意外滥用。
// 合约不应该拥有任何球员(除非 在创建球星之后并且在拍卖之前 非常短)。
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
//该函数定义在FootballerBase
_transfer(_from, _to, _tokenId);
}
//返回现在一共有多少(球员+球星)
function totalSupply() public view returns (uint) {
return footballers.length;
}
//返回该特定球员的拥有者的地址
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = footballerToOwner[_tokenId];
require(owner != address(0));
}
//返回该地址的用户拥有的球员的id
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if(tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalpalyers = totalSupply();
uint256 resultIndex = 0;
uint256 footballerId;
for (footballerId = 0; footballerId < totalpalyers; footballerId++) {
if(footballerToOwner[footballerId] == _owner) {
result[resultIndex] = footballerId;
resultIndex++;
}
}
return result;
}
}
}
contract FootballerAction is FootballerOwnership {
//创建球星
function createFootballerStar(uint _price,uint _defend,uint _attack, uint _quality) public returns(uint) {
return _createFootballerStar(_price,_defend,_attack,_quality);
}
//抽卡包得球星
function CardFootballers() public payable returns (uint) {
uint price = 4000000000000 wei; //0.04 eth
require(msg.value >= price);
uint ballerCount = 14;
uint newFootballerId = 0;
for (uint i = 0; i < ballerCount; i++) {
newFootballerId = createFootballer();
}
managerAddress.transfer(msg.value);
return price;
}
function buyStar(uint footballerId,uint price) public payable {
require(msg.value >= price);
//将球星的拥有权 交给 购买的用户
address holder = footballerToApproved[footballerId];
require(holder != address(0));
_transfer(holder,msg.sender,footballerId);
//给卖家转钱
holder.transfer(msg.value);
}
//用户出售自己拥有的球员或球星
function sell(uint footballerId,uint price) public returns(uint) {
require(footballerToOwner[footballerId] == msg.sender);
require(footballerToApproved[footballerId] == address(0));
footballerToApproved[footballerId] = msg.sender;
footballers[footballerId].price = price;
}
//显示球队
function getTeamBallers(address actor) public view returns (uint[]) {
uint len = footballers.length;
uint count=0;
for(uint i = 0; i < len; i++) {
if(_owns(actor, i)){
if(footballerToApproved[i] == address(0)){
count++;
}
}
}
uint[] memory res = new uint256[](count);
uint index = 0;
for(i = 0; i < len; i++) {
if(_owns(actor, i)){
if(footballerToApproved[i] == address(0)){
res[index] = i;
index++;
}
}
}
return res;
}
//显示出售的球星+球员
function getSellBallers() public view returns (uint[]) {
uint len = footballers.length;
uint count = 0;
for(uint i = 0; i < len; i++) {
if(footballerToApproved[i] != address(0)){
count++;
}
}
uint[] memory res = new uint256[](count);
uint index = 0;
for( i = 0; i < len; i++) {
if(footballerToApproved[i] != address(0)){
res[index] = i;
index++;
}
}
return res;
}
//获得球员+球星的总数量
function getAllBaller() public view returns (uint) {
uint len = totalSupply();
return len;
}
}
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;
}
}
|
生成一个从 _min 到 _max 范围内的随机数(不包括 _max)
|
function _randMod(uint _min, uint _max) private returns(uint) {
randNonce++;
uint modulus = _max - _min;
return uint(keccak256(now, msg.sender, randNonce)) % modulus + _min;
}
| 1,223,217 |
./partial_match/8453/0xb01DB992BFa6f7eC5AA15C93e9e0Ab1077010594/sources/WritingEditions.sol
|
> [[[[[[[[[[[ Modifiers ]]]]]]]]]]]
|
function treasuryConfiguration() external view returns (address);
function transferFunds(address payable to, uint256 value) external;
function transferERC20(
address token,
address to,
uint256 value
) external;
function transferERC721(
address token,
address from,
address to,
uint256 tokenId
) external;
function contributeWithTributary(address tributary) external payable;
function contribute(uint256 amount) external payable;
}
}
}
}
modifier onlyOwner() {
require(isOwner(), "caller is not the owner.");
_;
}
| 16,800,919 |
// 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: Apache-2.0
pragma solidity 0.7.6;
interface IERC1155 {
/****************************************|
| Events |
|_______________________________________*/
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/****************************************|
| Functions |
|_______________________________________*/
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory);
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool isOperator);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external returns (bytes4);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-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);
}
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.7.6;
/**
* Utility library of inline functions on addresses
*/
library Address {
// Default hash for EOA accounts returned by extcodehash
bytes32 internal constant ACCOUNT_HASH =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract.
* @param _address address of the account to check
* @return Whether the target address is a contract
*/
function isContract(address _address) internal view returns (bool) {
bytes32 codehash;
// 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 or if it has a non-zero code hash or account hash
assembly {
codehash := extcodehash(_address)
}
return (codehash != 0x0 && codehash != ACCOUNT_HASH);
}
/**
* @dev Performs a Solidity function call using a low level `call`.
*
* 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.
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal 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(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 AND Apache-2.0
pragma solidity 0.7.6;
import '../interfaces/IERC20.sol';
import '../utils/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);
_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: Apache-2.0
pragma solidity 0.7.6;
/**
* @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, 'SafeMath#mul: OVERFLOW');
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, 'SafeMath#div: DIVISION_BY_ZERO');
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, 'SafeMath#sub: UNDERFLOW');
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, 'SafeMath#add: OVERFLOW');
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, 'SafeMath#mod: DIVISION_BY_ZERO');
return a % b;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/* solhint-disable func-name-mixedcase */
abstract contract ICurveFiDepositY {
function add_liquidity(uint256[4] calldata uAmounts, uint256 minMintAmount)
external
virtual;
function remove_liquidity(uint256 amount, uint256[4] calldata minUAmounts)
external
virtual;
function remove_liquidity_imbalance(
uint256[4] calldata uAmounts,
uint256 maxBurnAmount
) external virtual;
function calc_withdraw_one_coin(uint256 wrappedAmount, int128 coinIndex)
external
view
virtual
returns (uint256 underlyingAmount);
function remove_liquidity_one_coin(
uint256 wrappedAmount,
int128 coinIndex,
uint256 minAmount,
bool donateDust
) external virtual;
function coins(int128 i) external view virtual returns (address);
function underlying_coins(int128 i) external view virtual returns (address);
function underlying_coins() external view virtual returns (address[4] memory);
function curve() external view virtual returns (address);
function token() external view virtual returns (address);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/utils/Context.sol';
import '../../0xerc1155/interfaces/IERC1155.sol';
import '../../0xerc1155/interfaces/IERC1155TokenReceiver.sol';
import '../../0xerc1155/utils/SafeMath.sol';
import '../investment/interfaces/ICFolioFarm.sol'; // WOWS rewards
import '../token/interfaces/IWOWSERC1155.sol'; // SFT contract
import '../token/interfaces/IWOWSCryptofolio.sol';
import '../utils/AddressBook.sol';
import '../utils/interfaces/IAddressRegistry.sol';
import '../utils/TokenIds.sol';
import './interfaces/ICFolioItemBridge.sol';
import './interfaces/ICFolioItemHandler.sol';
import './interfaces/ISFTEvaluator.sol';
/**
* @dev CFolioItemHandlerFarm manages CFolioItems, minted in the SFT contract.
*
* Minting CFolioItem SFTs is implemented in the WOWSSFTMinter contract, which
* mints the SFT in the WowsERC1155 contract and calls setupCFolio in here.
*
* Normaly CFolioItem SFTs are locked in the main TradeFloor contract to allow
* trading or transfer into a Base SFT card's c-folio.
*
* CFolioItem SFTs only earn rewards if they are inside the cfolio of a base
* NFT. We get called from main TradeFloor every time an CFolioItem gets
* transfered and calculate the new rewardable amount based on the reward %
* of the base NFT.
*/
abstract contract CFolioItemHandlerFarm is ICFolioItemHandler, Context {
using SafeMath for uint256;
using TokenIds for uint256;
//////////////////////////////////////////////////////////////////////////////
// Routing
//////////////////////////////////////////////////////////////////////////////
// Route to SFT Minter. Only setup from SFT Minter allowed.
address public sftMinter;
// The TradeFloor contract which provides c-folio NFTs. This TradeFloor
// contract calls the IMinterCallback interface functions.
ICFolioItemBridge public immutable cfiBridge;
// SFT evaluator
ISFTEvaluator public immutable sftEvaluator;
// Reward emitter
ICFolioFarmOwnable public immutable cfolioFarm;
// Admin
address public immutable admin;
// The SFT contract needed to check if the address is a c-folio
IWOWSERC1155 public immutable sftHolder;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
/*
* @dev Emitted when a reward is updated, either increased or decreased
*
* @param previousAmount The amount before updating the reward
* @param newAmount The amount after updating the reward
*/
event RewardUpdated(uint256 previousAmount, uint256 newAmount);
/**
* @dev Emitted when a new minter is set by the admin
*
* @param minter The new minter
*/
event NewMinter(address minter);
/**
* @dev Emitted when the contract is destructed
*
* @param thisContract The address of this contract
*/
event CFolioItemHandlerDestructed(address thisContract);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyBridge() {
require(_msgSender() == address(cfiBridge), 'CFHI: Only CFIB');
_;
}
modifier onlyAdmin() {
require(_msgSender() == admin, 'CFIH: Only admin');
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Constructs the CFolioItemHandlerFarm
*
* We gather all current addresses from address registry into immutable vars.
* If one of the relevant addresses changes, the contract has to be updated.
* There is little state here, user state is completely handled in CFolioFarm.
*/
constructor(IAddressRegistry addressRegistry, bytes32 rewardFarmKey) {
// TradeFloor
cfiBridge = ICFolioItemBridge(
addressRegistry.getRegistryEntry(AddressBook.CFOLIOITEM_BRIDGE_PROXY)
);
// Admin
admin = addressRegistry.getRegistryEntry(AddressBook.MARKETING_WALLET);
// The SFT holder
sftHolder = IWOWSERC1155(
addressRegistry.getRegistryEntry(AddressBook.SFT_HOLDER)
);
// The SFT minter
sftMinter = addressRegistry.getRegistryEntry(AddressBook.SFT_MINTER);
emit NewMinter(sftMinter);
// SFT evaluator
sftEvaluator = ISFTEvaluator(
addressRegistry.getRegistryEntry(AddressBook.SFT_EVALUATOR_PROXY)
);
// WOWS rewards
cfolioFarm = ICFolioFarmOwnable(
addressRegistry.getRegistryEntry(rewardFarmKey)
);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ICFolioItemCallback} via {ICFolioItemHandler}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ICFolioItemCallback-onCFolioItemsTransferedFrom}
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata, /* tokenIds*/
address[] calldata /* cfolioHandlers*/
) external override onlyBridge {
// In case of transfer verify the target
uint256 sftTokenId;
if (
to != address(0) &&
(sftTokenId = sftHolder.addressToTokenId(to)) != uint256(-1)
) {
_verifyTransferTarget(sftTokenId);
_updateRewards(to, sftEvaluator.rewardRate(sftTokenId));
}
if (
from != address(0) &&
(sftTokenId = sftHolder.addressToTokenId(from)) != uint256(-1)
) {
_updateRewards(from, sftEvaluator.rewardRate(sftTokenId));
}
}
/**
* @dev See {ICFolioItemCallback-appendHash}
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
override
returns (bytes memory)
{
return
abi.encodePacked(
current,
address(this),
cfolioFarm.balanceOf(cfolioItem)
);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ICFolioItemHandler}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ICFolioItemHandler-sftUpgrade}
*/
function sftUpgrade(uint256 tokenId, uint32 newRate) external override {
// Validate access
require(_msgSender() == address(sftEvaluator), 'CFIH: Invalid caller');
require(tokenId.isBaseCard(), 'CFIH: Invalid token');
// CFolio address
address cfolio = sftHolder.tokenIdToAddress(tokenId);
// Update state
_updateRewards(cfolio, newRate);
}
/**
* @dev See {ICFolioItemHandler-setupCFolio}
*
* Note: We place a dummy ERC1155 token with ID 0 into the CFolioItem's
* c-folio. The reason is that we want to know if a c-folio item gets burned,
* as burning an empty c-folio will result in no transfers. This prevents
* tokens from becoming inaccessible.
*
* Refer to the Minimal ERC1155 section below to learn which functions are
* needed for this.
*/
function setupCFolio(
address payer,
uint256 sftTokenId,
uint256[] calldata amounts
) external override {
// Validate access
require(_msgSender() == sftMinter, 'CFIH: Only sftMinter');
// Validate parameters, no unmasking required, must be SFT
address cFolio = sftHolder.tokenIdToAddress(sftTokenId);
require(cFolio != address(0), 'CFIH: No cfolio');
// Verify that this function is called the first time
(, uint256 length) = IWOWSCryptofolio(cFolio).getCryptofolio(address(this));
require(length == 0, 'CFIH: Not empty');
// Transfer a dummy NFT token to cFolio so we get informed if the cFolio
// gets burned
IERC1155TokenReceiver(cFolio).onERC1155Received(
address(this),
address(0),
0,
1,
''
);
if (amounts.length > 0) {
_deposit(cFolio, payer, amounts);
}
}
/**
* @dev See {ICFolioItemHandler-deposit}
*
* Note: tokenId can be owned by a base SFT
* In this case base SFT cannot be locked
*
* There is only need to update rewards if tokenId
* is part of an unlocked base SFT
*/
function deposit(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external override {
// Validate parameters
(address baseCFolio, address itemCFolio) = _verifyAssetAccess(
baseTokenId,
tokenId
);
// Call the implementation
_deposit(itemCFolio, _msgSender(), amounts);
// Update rewards if CFI is inside cfolio
if (baseCFolio != address(0))
_updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId));
}
/**
* @dev See {ICFolioItemHandler-withdraw}
*
* Note: tokenId can be owned by a base SFT. In this case, the base SFT
* cannot be locked.
*
* There is only need to update rewards if tokenId is part of an unlocked
* base SFT.
*/
function withdraw(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external override {
// Validate parameters
(address baseCFolio, address itemCFolio) = _verifyAssetAccess(
baseTokenId,
tokenId
);
// Call the implementation
_withdraw(itemCFolio, amounts);
// Update rewards if CFI is inside cfolio
if (baseCFolio != address(0))
_updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId));
}
/**
* @dev See {ICFolioItemHandler-getRewards}
*
* Note: tokenId must be a base SFT card
*
* We allow reward pull only for unlocked SFTs.
*/
function getRewards(
address owner,
address recipient,
uint256 tokenId
) external override {
// Validate parameters
require(recipient != address(0), 'CFIH: Invalid recipient');
require(tokenId.isBaseCard(), 'CFIH: Invalid tokenId');
// Verify that tokenId has a valid cFolio address
uint256 sftTokenId = tokenId.toSftTokenId();
address cfolio = sftHolder.tokenIdToAddress(sftTokenId);
require(cfolio != address(0), 'CFHI: No cfolio');
// Verify that the tokenId is owned by owner and caller is sftMinter.
// This also verifies that the token is not locked in TradeFloor.
require(
_msgSender() == sftMinter &&
IERC1155(address(sftHolder)).balanceOf(owner, sftTokenId) == 1,
'CFHI: Forbidden'
);
cfolioFarm.getReward(cfolio, recipient);
}
/**
* @dev See {ICFolioItemHandler-getRewardInfo}
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
override
returns (bytes memory result)
{
uint256[5] memory uiData;
// Get basic data once
uiData = cfolioFarm.getUIData(address(0));
// total / rewardDuration / rewardPerDuration
result = abi.encodePacked(uiData[0], uiData[2], uiData[3]);
uint256 length = tokenIds.length;
if (length > 0) {
// Iterate through all tokenIds and collect reward info
for (uint256 i = 0; i < length; ++i) {
uint256 sftTokenId = tokenIds[i].toSftTokenId();
uint256 share = 0;
uint256 earned = 0;
if (sftTokenId.isBaseCard()) {
address cfolio = sftHolder.tokenIdToAddress(sftTokenId);
if (cfolio != address(0)) {
uiData = cfolioFarm.getUIData(cfolio);
share = uiData[1];
earned = uiData[4];
}
}
result = abi.encodePacked(result, share, earned);
}
}
}
//////////////////////////////////////////////////////////////////////////////
// Internal interface
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Deposit amounts
*/
function _deposit(
address itemCFolio,
address payer,
uint256[] calldata amounts
) internal virtual;
/**
* @dev Withdraw amounts
*/
function _withdraw(address itemCFolio, uint256[] calldata amounts)
internal
virtual;
/**
* @dev Verify if target base SFT is allowed
*/
function _verifyTransferTarget(uint256 baseSftTokenId) internal virtual;
//////////////////////////////////////////////////////////////////////////////
// Maintanace
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Destruct implementation
*/
function selfDestruct() external onlyAdmin {
// Dispatch event
CFolioItemHandlerDestructed(address(this));
// Disable high-impact Slither detector "suicidal" here. Slither explains
// that "CFolioItemHandlerFarm.selfDestruct() allows anyone to destruct the
// contract", which is not the case due to the onlyAdmin modifier.
//
// slither-disable-next-line suicidal
selfdestruct(payable(admin));
}
/**
* @dev Set a new SFT minter
*/
function setMinter(address newMinter) external onlyAdmin {
// Validate parameters
require(newMinter != address(0), 'CFIH: Invalid');
// Update state
sftMinter = newMinter;
// Dispatch event
emit NewMinter(newMinter);
}
//////////////////////////////////////////////////////////////////////////////
// Minimal ERC1155 implementation (called from SFTBase CFolio)
//////////////////////////////////////////////////////////////////////////////
// We do nothing for our dummy burn tokenId
function setApprovalForAll(address, bool) external {}
// Check for length == 1, and then return always 1
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
pure
returns (uint256[] memory)
{
// Validate parameters
require(_owners.length == 1 && _ids.length == 1, 'CFIH: Must be 1');
uint256[] memory result = new uint256[](1);
result[0] = 1;
return result;
}
/**
* @dev We don't allow burning non-empty c-folios
*/
function burnBatch(
address, /* account */
uint256[] calldata tokenIds,
uint256[] calldata
) external view {
// Validate parameters
require(tokenIds.length == 1, 'CFIH: Must be 1');
// This call originates from the c-folio. We revert if there are investment
// amounts left for this c-folio address.
require(cfolioFarm.balanceOf(_msgSender()) == 0, 'CFIH: Not empty');
}
//////////////////////////////////////////////////////////////////////////////
// Internal details
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Run through all cFolioItems collected in cFolio and select the amount
* of tokens. Update cfolioFarm.
*/
function _updateRewards(address cfolio, uint32 rate) private {
// Get c-folio items of this base cFolio
(uint256[] memory tokenIds, uint256 length) = IWOWSCryptofolio(cfolio)
.getCryptofolio(address(cfiBridge));
// Marginal increase in gas per item is around 25K. Bounding items to 100
// fits in sensible gas limits.
require(length <= 100, 'CFIH: Too many items');
// Calculate new reward amount
uint256 newRewardAmount = 0;
for (uint256 i = 0; i < length; ++i) {
address secondaryCFolio = sftHolder.tokenIdToAddress(tokenIds[i]);
require(secondaryCFolio != address(0), 'CFIH: Invalid tokenId');
if (IWOWSCryptofolio(secondaryCFolio)._tradefloors(0) == address(this))
newRewardAmount = newRewardAmount.add(
cfolioFarm.balanceOf(secondaryCFolio)
);
}
newRewardAmount = newRewardAmount.mul(rate).div(1E6);
// Calculate existing reward amount
uint256 exitingRewardAmount = cfolioFarm.balanceOf(cfolio);
// Compare amounts and add/remove shares
if (newRewardAmount > exitingRewardAmount) {
// Update state
cfolioFarm.addShares(cfolio, newRewardAmount.sub(exitingRewardAmount));
// Dispatch event
emit RewardUpdated(exitingRewardAmount, newRewardAmount);
} else if (newRewardAmount < exitingRewardAmount) {
// Update state
cfolioFarm.removeShares(cfolio, exitingRewardAmount.sub(newRewardAmount));
// Dispatch event
emit RewardUpdated(exitingRewardAmount, newRewardAmount);
}
}
/**
* @dev Verifies if an asset access operation is allowed
*
* @param baseTokenId Base card tokenId or uint(-1)
* @param cfolioItemTokenId CFolioItem tokenId handled by this contract
*
* A tokenId is "unlocked" if msg.sender is the owner of a tokenId in SFT
* contract. If baseTokenId is uint(-1), cfolioItemTokenId has to be be
* unlocked, otherwise baseTokenId has to be unlocked and the locked
* cfolioItemTokenId has to be inside its c-folio.
*/
function _verifyAssetAccess(uint256 baseTokenId, uint256 cfolioItemTokenId)
private
view
returns (address, address)
{
// Verify it's a cfolioItemTokenId
require(cfolioItemTokenId.isCFolioCard(), 'CFHI: Not cFolioCard');
// Verify that the tokenId is one of ours
address cFolio = sftHolder.tokenIdToAddress(
cfolioItemTokenId.toSftTokenId()
);
require(cFolio != address(0), 'CFIH: Invalid cFolioTokenId');
require(
IWOWSCryptofolio(cFolio)._tradefloors(0) == address(this),
'CFIH: Not our SFT'
);
address baseCFolio = address(0);
if (baseTokenId != uint256(-1)) {
// Verify it's a c-folio base card
require(baseTokenId.isBaseCard(), 'CFHI: Not baseCard');
baseCFolio = sftHolder.tokenIdToAddress(baseTokenId.toSftTokenId());
require(baseCFolio != address(0), 'CFIH: Invalid baseCFolioTokenId');
// Verify that the tokenId is owned by msg.sender in SFT contract.
// This also verifies that the token is not locked in TradeFloor.
require(
IERC1155(address(sftHolder)).balanceOf(_msgSender(), baseTokenId) == 1,
'CFHI: Access denied (B)'
);
// Verify that the cfiTokenId is owned by given baseCFolio.
// In V2 we have unlocked CFIs in baseCfolio in contrast to V1
require(
cfiBridge.balanceOf(baseCFolio, cfolioItemTokenId) == 1,
'CFHI: Access denied (CF)'
);
} else {
// Verify that the tokenId is owned by msg.sender in SFT contract.
// This also verifies that the token is not locked in TradeFloor.
require(
IERC1155(address(sftHolder)).balanceOf(
_msgSender(),
cfolioItemTokenId
) == 1,
'CFHI: Access denied'
);
}
return (baseCFolio, cFolio);
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../0xerc1155/interfaces/IERC20.sol';
import '../../0xerc1155/utils/SafeERC20.sol';
import '../../interfaces/curve/CurveDepositInterface.sol';
import './CFolioItemHandlerFarm.sol';
/**
* @dev CFolioItemHandlerSC manages CFolioItems, minted in the SFT contract.
*
* See {CFolioItemHandlerFarm}.
*/
contract CFolioItemHandlerSC is CFolioItemHandlerFarm {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// Routing
//////////////////////////////////////////////////////////////////////////////
// Curve Y pool token contract
IERC20 public immutable curveYToken;
// Curve Y pool deposit contract
ICurveFiDepositY public immutable curveYDeposit;
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Constructs the CFolioItemHandlerSC
*
* We gather all current addresses from address registry into immutable vars.
* If one of the relevant addresses changes, the contract has to be updated.
* There is little state here, user state is completely handled in CFolioFarm.
*/
constructor(IAddressRegistry addressRegistry)
CFolioItemHandlerFarm(addressRegistry, AddressBook.BOIS_REWARDS)
{
// The Y pool deposit contract
curveYDeposit = ICurveFiDepositY(
addressRegistry.getRegistryEntry(AddressBook.CURVE_Y_DEPOSIT)
);
// The Y pool token contract
curveYToken = IERC20(
addressRegistry.getRegistryEntry(AddressBook.CURVE_Y_TOKEN)
);
}
/**
* @dev One time contract initializer
*/
function initialize() public {
// Approve stablecoin spending
for (uint256 i = 0; i < 4; ++i) {
address underlyingCoin = curveYDeposit.underlying_coins(int128(i));
IERC20(underlyingCoin).safeApprove(address(curveYDeposit), uint256(-1));
}
// Approve yCRV spending
curveYToken.approve(address(curveYDeposit), uint256(-1));
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {CFolioItemHandlerFarm}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {CFolioItemHandlerFarm-_deposit}.
*/
function _deposit(
address itemCFolio,
address payer,
uint256[] calldata amounts
) internal override {
// Validate input
require(amounts.length == 5, 'CFIHSC: Amount length invalid');
// Keep track of how many Y pool tokens were received
uint256 beforeBalance = curveYToken.balanceOf(address(this));
// Keep track of amounts
uint256[4] memory stableAmounts;
uint256 totalStableAmount;
// Update state
for (uint256 i = 0; i < 4; ++i) {
address underlyingCoin = curveYDeposit.underlying_coins(int128(i));
IERC20(underlyingCoin).safeTransferFrom(payer, address(this), amounts[i]);
uint256 stableAmount = IERC20(underlyingCoin).balanceOf(address(this));
stableAmounts[i] = stableAmount;
totalStableAmount += stableAmount;
}
if (totalStableAmount > 0) {
// Call to external contract
curveYDeposit.add_liquidity(stableAmounts, 0);
// Validate state
uint256 afterStableBalance = curveYToken.balanceOf(address(this));
require(
afterStableBalance > beforeBalance,
'CFIHSC: No stable liquidity'
);
}
// Handle Y pool
uint256 yPoolAmount = amounts[4];
// Update state
if (yPoolAmount > 0) {
curveYToken.safeTransferFrom(payer, address(this), yPoolAmount);
}
// Validate state
uint256 afterBalance = curveYToken.balanceOf(address(this));
require(afterBalance > beforeBalance, 'CFIFSC: No investment');
// Record assets in Farm contract. They don't earn rewards.
//
// NOTE: {addAssets} must only be called from Investment CFolios. This
// call is allowed without any investment.
cfolioFarm.addAssets(itemCFolio, afterBalance.sub(beforeBalance));
}
/**
* @dev See {CFolioItemHandlerFarm-_withdraw}
*
* Note: tokenId can be owned by a base SFT. In this case, the base SFT
* cannot be locked.
*
* There is only need to update rewards if tokenId is part of an unlocked
* base SFT.
*
* @param itemCFolio The address of the target CFolioItem cryptofolio
* @param amounts The amounts, with the tokens being DAI/USDC/USDT/TUSD/yCRV.
* yCRV must be specified, as yCRV tokens are held by this contract.
* If all four stablecoin amounts are 0, then yCRV is withdrawn to the
* sender's wallet. If exactly one of the four stablecoin amounts is > 0,
* then yCRV will be converted to the specified stablecoin. The amount in
* the array is the minimum amount of stablecoin tokens that must be
* withdrawn.
*/
function _withdraw(address itemCFolio, uint256[] calldata amounts)
internal
override
{
// Validate input
require(amounts.length == 5, 'CFIHSC: Amount length invalid');
// Validate parameters
uint256 yPoolAmount = amounts[4];
require(yPoolAmount > 0, 'CFIHSC: yCRV amount is 0');
// Get single coin and amount
(int128 stableCoinIndex, uint256 stableCoinAmount) = _getStableCoinInfo(
amounts
);
// Keep track of how many Y pool tokens were sent
uint256 balanceBefore = curveYToken.balanceOf(address(this));
// Update state
if (stableCoinIndex != -1) {
// Call to external contract
curveYDeposit.remove_liquidity_one_coin(
yPoolAmount,
stableCoinIndex,
stableCoinAmount,
true
);
address underlyingCoin = curveYDeposit.underlying_coins(
int128(stableCoinIndex)
);
uint256 underlyingCoinAmount = IERC20(underlyingCoin).balanceOf(
address(this)
);
// Transfer stablecoins back to the sender
IERC20(underlyingCoin).safeTransfer(_msgSender(), underlyingCoinAmount);
} else {
// No stablecoins were passed, sender is withdrawing Y pool tokens directly
// Transfer Y pool tokens back to the sender
curveYToken.safeTransfer(_msgSender(), yPoolAmount);
}
// Valiate state
uint256 balanceAfter = curveYToken.balanceOf(address(this));
require(balanceAfter < balanceBefore, 'Nothing withdrawn');
// Record assets in Farm contract. They don't earn rewards.
//
// NOTE: {removeAssets} must only be called from Investment CFolios.
cfolioFarm.removeAssets(itemCFolio, balanceBefore.sub(balanceAfter));
}
/**
* @dev See {CFolioItemHandlerFarm-_verifyTransferTarget}
*/
function _verifyTransferTarget(uint256 baseSftTokenId)
internal
view
override
{
(, uint8 level) = sftHolder.getTokenData(baseSftTokenId);
require((LEVEL2BOIS & (uint256(1) << level)) > 0, 'CFIHSC: Bois only');
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ICFolioItemHandler} via {CFolioItemHandlerFarm}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ICFolioItemHandler-getAmounts}
*
* The returned token array is DAI/USDC/USDT/TUSD/yCRV. Tokens are held in
* this contract as yCRV, so the fifth item will be the amount of yCRV. The
* four stablecoin amounts are the amount that would be withdrawn if all
* yCRV were converted to the corresponding stablecoin upon withdrawal. This
* value is calculated by Curve.
*/
function getAmounts(address cfolioItem)
external
view
override
returns (uint256[] memory)
{
uint256[] memory result = new uint256[](5);
uint256 wrappedAmount = cfolioFarm.balanceOf(cfolioItem);
for (uint256 i = 0; i < 4; ++i) {
result[i] = curveYDeposit.calc_withdraw_one_coin(
wrappedAmount,
int128(i)
);
}
result[4] = wrappedAmount;
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Implementation details
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Get single coin and amount
*
* This is a helper function for {withdraw}. Per the documentation above, no
* more than one stablecoin amount can be > 0. If more than one stablecoin
* amount is specified, the revert condition below will be reached.
*
* If exactly one stablecoin amount is specified, then the return values will
* be the index of that coin and its amount.
*
* If no stablecoin amounts are > 0, then a coin index of -1 is returned,
* with a 0 amount.
*
* @param amounts The amounts array: DAI/USDC/USDT/TUSD/yCRV
*
* @return stableCoinIndex The index of the stablecoin with amount > 0, or -1
* if all four stablecoin amounts are 0
* @return stableCoinAmount The amount of the stablecoin, or 0 if all four
* stablecoin amounts are 0
*/
function _getStableCoinInfo(uint256[] calldata amounts)
private
pure
returns (int128 stableCoinIndex, uint256 stableCoinAmount)
{
stableCoinIndex = -1;
for (uint128 i = 0; i < 4; ++i) {
if (amounts[i] > 0) {
require(stableCoinIndex == -1, 'Multiple amounts > 0');
stableCoinIndex = int8(i);
stableCoinAmount = amounts[i];
}
}
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to C-folio item bridge
*/
interface ICFolioItemBridge {
/**
* @notice Send multiple types of tokens from the _from address to the _to address (with safety call)
* @param from Source addresses
* @param to Target addresses
* @param tokenIds IDs of each token type
* @param amounts Transfer amounts per token type
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes memory
) external;
/**
* @notice Burn multiple types of tokens from the from
* @param from Source addresses
* @param tokenIds IDs of each token type
* @param amounts Transfer amounts per token type
*/
function burnBatch(
address from,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) external;
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool isOperator);
/**
* @notice Get the balance of single account/token pair
* @param account The address of the token holders
* @param tokenId ID of the token
* @return The account's balance (0 or 1)
*/
function balanceOf(address account, uint256 tokenId)
external
view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param accounts The addresses of the token holders
* @param tokenIds ID of the Tokens
* @return The accounts's balances (0 or 1)
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory tokenIds)
external
view
returns (uint256[] memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../token/interfaces/ICFolioItemCallback.sol';
/**
* @dev Interface to C-folio item contracts
*/
interface ICFolioItemHandler is ICFolioItemCallback {
/**
* @dev Called when a SFT tokens grade needs re-evaluation
*
* @param tokenId The ERC-1155 token ID. Rate is in 1E6 convention: 1E6 = 100%
* @param newRate The new value rate
*/
function sftUpgrade(uint256 tokenId, uint32 newRate) external;
/**
* @dev Called from SFTMinter after an Investment SFT is minted
*
* @param payer The approved address to get investment from
* @param sftTokenId The sftTokenId whose c-folio is the owner of investment
* @param amounts The amounts of invested assets
*/
function setupCFolio(
address payer,
uint256 sftTokenId,
uint256[] calldata amounts
) external;
//////////////////////////////////////////////////////////////////////////////
// Asset access
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Adds investments into a cFolioItem SFT
*
* Transfers amounts of assets from users wallet to the contract. In general,
* an Approval call is required before the function is called.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function deposit(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Removes investments from a cFolioItem SFT
*
* Withdrawn token are transfered back to msg.sender.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function withdraw(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Get the rewards collected by an SFT base card
*
* Calls only allowed from sftMinter.
*
* @param owner The owner of the NFT token
* @param recipient Recipient of the rewards (- fees)
* @param tokenId SFT base card tokenId, must be unlocked
*/
function getRewards(
address owner,
address recipient,
uint256 tokenId
) external;
/**
* @dev Get amounts (handler specific) for a cfolioItem
*
* @param cfolioItem address of CFolioItem contract
*/
function getAmounts(address cfolioItem)
external
view
returns (uint256[] memory);
/**
* @dev Get information obout the rewardFarm
*
* @param tokenIds List of basecard tokenIds
* @return bytes of uint256[]: total, rewardDur, rewardRateForDur, [share, earned]
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
// BOIS feature bitmask
uint256 constant LEVEL2BOIS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000F;
uint256 constant LEVEL2WOLF = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000F0;
interface ISFTEvaluator {
/**
* @dev Returns the reward in 1e6 factor notation (1e6 = 100%)
*/
function rewardRate(uint256 sftTokenId) external view returns (uint32);
/**
* @dev Returns the cFolioItemType of a given cFolioItem tokenId
*/
function getCFolioItemType(uint256 tokenId) external view returns (uint256);
/**
* @dev Calculate the current reward rate, and notify TFC in case of change
*
* Optional revert on unchange to save gas on external calls.
*/
function setRewardRate(uint256 tokenId, bool revertUnchanged) external;
/**
* @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used
* sftHolder tokenId expected (without hash)
*/
function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity 0.7.6;
/**
* @title ICFolioFarm
*
* @dev ICFolioFarm is the business logic interface to c-folio farms.
*/
interface ICFolioFarm {
/**
* @dev Return total invested balance
*/
function totalSupply() external view returns (uint256);
/**
* @dev Return invested balance of account
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Return total, balances[account], rewardDuration, rewardForDuration, earned[account]
*/
function getUIData(address account) external view returns (uint256[5] memory);
/**
* @dev Increase amount of non-rewarded asset
*/
function addAssets(address account, uint256 amount) external;
/**
* @dev Remove amount of previous added assets
*/
function removeAssets(address account, uint256 amount) external;
/**
* @dev Increase amount of shares and earn rewards
*/
function addShares(address account, uint256 amount) external;
/**
* @dev Remove amount of previous added shares, rewards will not be claimed
*/
function removeShares(address account, uint256 amount) external;
/**
* @dev Claim rewards harvested during reward time
*/
function getReward(address account, address rewardRecipient) external;
/**
* @dev Remove all shares and call getRewards() in a single step
*/
function exit(address account, address rewardRecipient) external;
}
/**
* @title ICFolioFarmOwnable
*/
interface ICFolioFarmOwnable is ICFolioFarm {
/**
* @dev Transfer ownership
*/
function transferOwnership(address newOwner) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to receive callbacks when minted tokens are burnt
*/
interface ICFolioItemCallback {
/**
* @dev Called when a TradeFloor CFolioItem is transfered
*
* In case of mint `from` is address(0).
* In case of burn `to` is address(0).
*
* cfolioHandlers are passed to let each cfolioHandler filter for its own
* token. This eliminates the need for creating separate lists.
*
* @param from The account sending the token
* @param to The account receiving the token
* @param tokenIds The ERC-1155 token IDs
* @param cfolioHandlers cFolioItem handlers
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata tokenIds,
address[] calldata cfolioHandlers
) external;
/**
* @dev Append data we use later for hashing
*
* @param cfolioItem The token ID of the c-folio item
* @param current The current data being hashes
*
* @return The current data, with internal data appended
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSCryptofolio {
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Initialize the deployed contract after creation
*
* This is a one time call which sets _deployer to msg.sender.
* Subsequent calls reverts.
*/
function initialize() external;
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return tradefloor at given index
*
* @param index The 0-based index in the tradefloor array
*
* @return The address of the tradefloor and position index
*/
function _tradefloors(uint256 index) external view returns (address);
/**
* @dev Return array of cryptofolio item token IDs
*
* The token IDs belong to the contract TradeFloor.
*
* @param tradefloor The TradeFloor that items belong to
*
* @return tokenIds The token IDs in scope of operator
* @return idsLength The number of valid token IDs
*/
function getCryptofolio(address tradefloor)
external
view
returns (uint256[] memory tokenIds, uint256 idsLength);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the owner of the underlying NFT
*
* This function is called if ownership of the parent NFT has changed.
*
* The new owner gets allowance to transfer cryptofolio items. The new owner
* is allowed to transfer / burn cryptofolio items. Make sure that allowance
* is removed from previous owner.
*
* @param owner The new owner of the underlying NFT, or address(0) if the
* underlying NFT is being burned
*/
function setOwner(address owner) external;
/**
* @dev Allow owner (of parent NFT) to approve external operators to transfer
* our cryptofolio items
*
* The NFT owner is allowed to approve operator to handle cryptofolios.
*
* @param operator The operator
* @param allow True to approve for all NFTs, false to revoke approval
*/
function setApprovalForAll(address operator, bool allow) external;
/**
* @dev Burn all cryptofolio items
*
* In case an underlying NFT is burned, we also burn the cryptofolio.
*/
function burn() external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSERC1155 {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Check if the specified address is a known tradefloor
*
* @param account The address to check
*
* @return True if the address is a known tradefloor, false otherwise
*/
function isTradeFloor(address account) external view returns (bool);
/**
* @dev Get the token ID of a given address
*
* A cross check is required because token ID 0 is valid.
*
* @param tokenAddress The address to convert to a token ID
*
* @return The token ID on success, or uint256(-1) if `tokenAddress` does not
* belong to a token ID
*/
function addressToTokenId(address tokenAddress)
external
view
returns (uint256);
/**
* @dev Get the address for a given token ID
*
* @param tokenId The token ID to convert
*
* @return The address, or address(0) in case the token ID does not belong
* to an NFT
*/
function tokenIdToAddress(uint256 tokenId) external view returns (address);
/**
* @dev Get the next mintable token ID for the specified card
*
* @param level The level of the card
* @param cardId The ID of the card
*
* @return bool True if a free token ID was found, false otherwise
* @return uint256 The first free token ID if one was found, or invalid otherwise
*/
function getNextMintableTokenId(uint8 level, uint8 cardId)
external
view
returns (bool, uint256);
/**
* @dev Return the next mintable custom token ID
*/
function getNextMintableCustomToken() external view returns (uint256);
/**
* @dev Return the level and the mint timestamp of tokenId
*
* @param tokenId The tokenId to query
*
* @return mintTimestamp The timestamp token was minted
* @return level The level token belongs to
*/
function getTokenData(uint256 tokenId)
external
view
returns (uint64 mintTimestamp, uint8 level);
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the base URI for either predefined cards or custom cards
* which don't have it's own URI.
*
* The resulting uri is baseUri+[hex(tokenId)] + '.json'. where
* tokenId will be reduces to upper 16 bit (>> 16) before building the hex string.
*
*/
function setBaseMetadataURI(string memory baseContractMetadata) external;
/**
* @dev Set the contracts metadata URI
*
* @param contractMetadataURI The URI which point to the contract metadata file.
*/
function setContractMetadataURI(string memory contractMetadataURI) external;
/**
* @dev Set the URI for a custom card
*
* @param tokenId The token ID whose URI is being set.
* @param customURI The URI which point to an unique metadata file.
*/
function setCustomURI(uint256 tokenId, string memory customURI) external;
/**
* @dev Each custom card has its own level. Level will be used when
* calculating rewards and raiding power.
*
* @param tokenId The ID of the token whose level is being set
* @param cardLevel The new level of the specified token
*/
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library AddressBook {
bytes32 public constant DEPLOYER = 'DEPLOYER';
bytes32 public constant TEAM_WALLET = 'TEAM_WALLET';
bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET';
bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02';
bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM';
bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN';
bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR';
bytes32 public constant WOWS_BOOSTER_PROXY = 'WOWS_BOOSTER_PROXY';
bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER';
bytes32 public constant SFT_MINTER = 'SFT_MINTER';
bytes32 public constant SFT_HOLDER = 'SFT_HOLDER';
bytes32 public constant CFOLIOITEM_BRIDGE_PROXY = 'CFOLIOITEM_BRIDGE_PROXY';
bytes32 public constant BOIS_REWARDS = 'BOIS_REWARDS';
bytes32 public constant WOLVES_REWARDS = 'WOLVES_REWARDS';
bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY';
bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY';
bytes32 public constant CURVE_Y_TOKEN = 'CURVE_Y_TOKEN';
bytes32 public constant CURVE_Y_DEPOSIT = 'CURVE_Y_DEPOSIT';
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library TokenIds {
// 128 bit underlying hash
uint256 public constant HASH_MASK = (1 << 128) - 1;
function isBaseCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 64);
}
function isStockCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 32);
}
function isCFolioCard(uint256 tokenId) internal pure returns (bool) {
return
(tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128);
}
function toSftTokenId(uint256 tokenId) internal pure returns (uint256) {
return tokenId & HASH_MASK;
}
function maskHash(uint256 tokenId) internal pure returns (uint256) {
return tokenId & ~HASH_MASK;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
interface IAddressRegistry {
/**
* @dev Set an abitrary key / address pair into the registry
*/
function setRegistryEntry(bytes32 _key, address _location) external;
/**
* @dev Get a registry enty with by key, returns 0 address if not existing
*/
function getRegistryEntry(bytes32 _key) external view returns (address);
}
|
See {ICFolioItemHandler-getRewards} Note: tokenId must be a base SFT card We allow reward pull only for unlocked SFTs./ Validate parameters Verify that tokenId has a valid cFolio address Verify that the tokenId is owned by owner and caller is sftMinter. This also verifies that the token is not locked in TradeFloor.
|
function getRewards(
address owner,
address recipient,
uint256 tokenId
) external override {
require(recipient != address(0), 'CFIH: Invalid recipient');
require(tokenId.isBaseCard(), 'CFIH: Invalid tokenId');
uint256 sftTokenId = tokenId.toSftTokenId();
address cfolio = sftHolder.tokenIdToAddress(sftTokenId);
require(cfolio != address(0), 'CFHI: No cfolio');
require(
_msgSender() == sftMinter &&
IERC1155(address(sftHolder)).balanceOf(owner, sftTokenId) == 1,
'CFHI: Forbidden'
);
cfolioFarm.getReward(cfolio, recipient);
}
| 14,368,567 |
/*
Copyright 2021 Set Labs Inc.
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.6.10;
pragma experimental ABIEncoderV2;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { IExtension } from "../interfaces/IExtension.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { MutualUpgrade } from "../lib/MutualUpgrade.sol";
/**
* @title BaseManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality. Implements IIP-64, supporting
* a registry of protected modules that can only be upgraded with methodologist consent.
*/
contract BaseManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
using SafeERC20 for IERC20;
/* ============ Struct ========== */
struct ProtectedModule {
bool isProtected; // Flag set to true if module is protected
address[] authorizedExtensionsList; // List of Extensions authorized to call module
mapping(address => bool) authorizedExtensions; // Map of extensions authorized to call module
}
/* ============ Events ============ */
event ExtensionAdded(
address _extension
);
event ExtensionRemoved(
address _extension
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
event ExtensionAuthorized(
address _module,
address _extension
);
event ExtensionAuthorizationRevoked(
address _module,
address _extension
);
event ModuleProtected(
address _module,
address[] _extensions
);
event ModuleUnprotected(
address _module
);
event ReplacedProtectedModule(
address _oldModule,
address _newModule,
address[] _newExtensions
);
event EmergencyReplacedProtectedModule(
address _module,
address[] _extensions
);
event EmergencyRemovedProtectedModule(
address _module
);
event EmergencyResolved();
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed extension
*/
modifier onlyExtension() {
require(isExtension[msg.sender], "Must be extension");
_;
}
/**
* Throws if contract is in an emergency state following a unilateral operator removal of a
* protected module.
*/
modifier upgradesPermitted() {
require(emergencies == 0, "Upgrades paused by emergency");
_;
}
/**
* Throws if contract is *not* in an emergency state. Emergency replacement and resolution
* can only happen in an emergency
*/
modifier onlyEmergency() {
require(emergencies > 0, "Not in emergency");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed extensions
address[] internal extensions;
// Mapping to check if extension is added
mapping(address => bool) public isExtension;
// Address of operator which typically executes manager only functions on Set Protocol modules
address public operator;
// Address of methodologist which serves as providing methodology for the index
address public methodologist;
// Counter incremented when the operator "emergency removes" a protected module. Decremented
// when methodologist executes an "emergency replacement". Operator can only add modules and
// extensions when `emergencies` is zero. Emergencies can only be declared "over" by mutual agreement
// between operator and methodologist or by the methodologist alone via `resolveEmergency`
uint256 public emergencies;
// Mapping of protected modules. These cannot be called or removed except by mutual upgrade.
mapping(address => ProtectedModule) public protectedModules;
// List of protected modules, for iteration. Used when checking that an extension removal
// can happen without methodologist approval
address[] public protectedModulesList;
// Boolean set when methodologist authorizes initialization after contract deployment.
// Must be true to call via `interactManager`.
bool public initialized;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
}
/* ============ External Functions ============ */
/**
* ONLY METHODOLOGIST : Called by the methodologist to enable contract. All `interactManager`
* calls revert until this is invoked. Lets methodologist review and authorize initial protected
* module settings.
*/
function authorizeInitialization() external onlyMethodologist {
require(!initialized, "Initialization authorized");
initialized = true;
}
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
require(_newManager != address(0), "Zero address not valid");
setToken.setManager(_newManager);
}
/**
* OPERATOR ONLY: Add a new extension that the BaseManager can call.
*
* @param _extension New extension to add
*/
function addExtension(address _extension) external upgradesPermitted onlyOperator {
require(!isExtension[_extension], "Extension already exists");
require(address(IExtension(_extension).manager()) == address(this), "Extension manager invalid");
_addExtension(_extension);
}
/**
* OPERATOR ONLY: Remove an existing extension tracked by the BaseManager.
*
* @param _extension Old extension to remove
*/
function removeExtension(address _extension) external onlyOperator {
require(isExtension[_extension], "Extension does not exist");
require(!_isAuthorizedExtension(_extension), "Extension used by protected module");
extensions.removeStorage(_extension);
isExtension[_extension] = false;
emit ExtensionRemoved(_extension);
}
/**
* MUTUAL UPGRADE: Authorizes an extension for a protected module. Operator and Methodologist must
* each call this function to execute the update. Adds extension to manager if not already present.
*
* @param _module Module to authorize extension for
* @param _extension Extension to authorize for module
*/
function authorizeExtension(address _module, address _extension)
external
mutualUpgrade(operator, methodologist)
{
require(protectedModules[_module].isProtected, "Module not protected");
require(!protectedModules[_module].authorizedExtensions[_extension], "Extension already authorized");
_authorizeExtension(_module, _extension);
emit ExtensionAuthorized(_module, _extension);
}
/**
* MUTUAL UPGRADE: Revokes extension authorization for a protected module. Operator and Methodologist
* must each call this function to execute the update. In order to remove the extension completely
* from the contract removeExtension must be called by the operator.
*
* @param _module Module to revoke extension authorization for
* @param _extension Extension to revoke authorization of
*/
function revokeExtensionAuthorization(address _module, address _extension)
external
mutualUpgrade(operator, methodologist)
{
require(protectedModules[_module].isProtected, "Module not protected");
require(isExtension[_extension], "Extension does not exist");
require(protectedModules[_module].authorizedExtensions[_extension], "Extension not authorized");
protectedModules[_module].authorizedExtensions[_extension] = false;
protectedModules[_module].authorizedExtensionsList.removeStorage(_extension);
emit ExtensionAuthorizationRevoked(_module, _extension);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken. Manager initialization must
* have been authorized by methodologist. Extension making this call must be authorized
* to call module if module is protected.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactManager(address _module, bytes memory _data) external onlyExtension {
require(initialized, "Manager not initialized");
require(_module != address(setToken), "Extensions cannot call SetToken");
require(_senderAuthorizedForModule(_module, msg.sender), "Extension not authorized for module");
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Transfers _tokens held by the manager to _destination. Can be used to
* recover anything sent here accidentally. In BaseManagerV2, extensions should
* be the only contracts designated as `feeRecipient` in fee modules.
*
* @param _token ERC20 token to send
* @param _destination Address receiving the tokens
* @param _amount Quantity of tokens to send
*/
function transferTokens(address _token, address _destination, uint256 _amount) external onlyExtension {
IERC20(_token).safeTransfer(_destination, _amount);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external upgradesPermitted onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken. Any extensions associated with this
* module need to be removed in separate transactions via removeExtension.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
require(!protectedModules[_module].isProtected, "Module protected");
setToken.removeModule(_module);
}
/**
* OPERATOR ONLY: Marks a currently protected module as unprotected and deletes its authorized
* extension registries. Removes module from the SetToken. Increments the `emergencies` counter,
* prohibiting any operator-only module or extension additions until `emergencyReplaceProtectedModule`
* is executed or `resolveEmergency` is called by the methodologist.
*
* Called by operator when a module must be removed immediately for security reasons and it's unsafe
* to wait for a `mutualUpgrade` process to play out.
*
* NOTE: If removing a fee module, you can ensure all fees are distributed by calling distribute
* on the module's de-authorized fee extension after this call.
*
* @param _module Module to remove
*/
function emergencyRemoveProtectedModule(address _module) external onlyOperator {
_unProtectModule(_module);
setToken.removeModule(_module);
emergencies += 1;
emit EmergencyRemovedProtectedModule(_module);
}
/**
* OPERATOR ONLY: Marks an existing module as protected and authorizes extensions for
* it, adding them if necessary. Adds module to the protected modules list
*
* The operator uses this when they're adding new features and want to assure the methodologist
* they won't be unilaterally changed in the future. Cannot be called during an emergency because
* methodologist needs to explicitly approve protection arrangements under those conditions.
*
* NOTE: If adding a fee extension while protecting a fee module, it's important to set the
* module `feeRecipient` to the new extension's address (ideally before this call).
*
* @param _module Module to protect
* @param _extensions Array of extensions to authorize for protected module
*/
function protectModule(address _module, address[] memory _extensions)
external
upgradesPermitted
onlyOperator
{
require(setToken.getModules().contains(_module), "Module not added yet");
_protectModule(_module, _extensions);
emit ModuleProtected(_module, _extensions);
}
/**
* METHODOLOGIST ONLY: Marks a currently protected module as unprotected and deletes its authorized
* extension registries. Removes old module from the protected modules list.
*
* Called by the methodologist when they want to cede control over a protected module without triggering
* an emergency (for example, to remove it because its dead).
*
* @param _module Module to revoke protections for
*/
function unProtectModule(address _module) external onlyMethodologist {
_unProtectModule(_module);
emit ModuleUnprotected(_module);
}
/**
* MUTUAL UPGRADE: Replaces a protected module. Operator and Methodologist must each call this
* function to execute the update.
*
* > Marks a currently protected module as unprotected
* > Deletes its authorized extension registries.
* > Removes old module from SetToken.
* > Adds new module to SetToken.
* > Marks `_newModule` as protected and authorizes new extensions for it.
*
* Used when methodologists wants to guarantee that an existing protection arrangement is replaced
* with a suitable substitute (ex: upgrading a StreamingFeeSplitExtension).
*
* NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be
* the new fee extension address after this call. Any fees remaining in the old module's
* de-authorized extensions can be distributed by calling `distribute()` on the old extension.
*
* @param _oldModule Module to remove
* @param _newModule Module to add in place of removed module
* @param _newExtensions Extensions to authorize for new module
*/
function replaceProtectedModule(address _oldModule, address _newModule, address[] memory _newExtensions)
external
mutualUpgrade(operator, methodologist)
{
_unProtectModule(_oldModule);
setToken.removeModule(_oldModule);
setToken.addModule(_newModule);
_protectModule(_newModule, _newExtensions);
emit ReplacedProtectedModule(_oldModule, _newModule, _newExtensions);
}
/**
* MUTUAL UPGRADE & EMERGENCY ONLY: Replaces a module the operator has removed with
* `emergencyRemoveProtectedModule`. Operator and Methodologist must each call this function to
* execute the update.
*
* > Adds new module to SetToken.
* > Marks `_newModule` as protected and authorizes new extensions for it.
* > Adds `_newModule` to protectedModules list.
* > Decrements the emergencies counter,
*
* Used when methodologist wants to guarantee that a protection arrangement which was
* removed in an emergency is replaced with a suitable substitute. Operator's ability to add modules
* or extensions is restored after invoking this method (if this is the only emergency.)
*
* NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be
* the new fee extension address after this call. Any fees remaining in the old module's
* de-authorized extensions can be distributed by calling `accrueFeesAndDistribute` on the old extension.
*
* @param _module Module to add in place of removed module
* @param _extensions Array of extensions to authorize for replacement module
*/
function emergencyReplaceProtectedModule(
address _module,
address[] memory _extensions
)
external
mutualUpgrade(operator, methodologist)
onlyEmergency
{
setToken.addModule(_module);
_protectModule(_module, _extensions);
emergencies -= 1;
emit EmergencyReplacedProtectedModule(_module, _extensions);
}
/**
* METHODOLOGIST ONLY & EMERGENCY ONLY: Decrements the emergencies counter.
*
* Allows a methodologist to exit a state of emergency without replacing a protected module that
* was removed. This could happen if the module has no viable substitute or operator and methodologist
* agree that restoring normal operations is the best way forward.
*/
function resolveEmergency() external onlyMethodologist onlyEmergency {
emergencies -= 1;
emit EmergencyResolved();
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
/* ============ External Getters ============ */
function getExtensions() external view returns(address[] memory) {
return extensions;
}
function getAuthorizedExtensions(address _module) external view returns (address[] memory) {
return protectedModules[_module].authorizedExtensionsList;
}
function isAuthorizedExtension(address _module, address _extension) external view returns (bool) {
return protectedModules[_module].authorizedExtensions[_extension];
}
function getProtectedModules() external view returns (address[] memory) {
return protectedModulesList;
}
/* ============ Internal ============ */
/**
* Add a new extension that the BaseManager can call.
*/
function _addExtension(address _extension) internal {
extensions.push(_extension);
isExtension[_extension] = true;
emit ExtensionAdded(_extension);
}
/**
* Marks a currently protected module as unprotected and deletes it from authorized extension
* registries. Removes module from the SetToken.
*/
function _unProtectModule(address _module) internal {
require(protectedModules[_module].isProtected, "Module not protected");
// Clear mapping and array entries in struct before deleting mapping entry
for (uint256 i = 0; i < protectedModules[_module].authorizedExtensionsList.length; i++) {
address extension = protectedModules[_module].authorizedExtensionsList[i];
protectedModules[_module].authorizedExtensions[extension] = false;
}
delete protectedModules[_module];
protectedModulesList.removeStorage(_module);
}
/**
* Adds new module to SetToken. Marks `_newModule` as protected and authorizes
* new extensions for it. Adds `_newModule` module to protectedModules list.
*/
function _protectModule(address _module, address[] memory _extensions) internal {
require(!protectedModules[_module].isProtected, "Module already protected");
protectedModules[_module].isProtected = true;
protectedModulesList.push(_module);
for (uint i = 0; i < _extensions.length; i++) {
_authorizeExtension(_module, _extensions[i]);
}
}
/**
* Adds extension if not already added and marks extension as authorized for module
*/
function _authorizeExtension(address _module, address _extension) internal {
if (!isExtension[_extension]) {
_addExtension(_extension);
}
protectedModules[_module].authorizedExtensions[_extension] = true;
protectedModules[_module].authorizedExtensionsList.push(_extension);
}
/**
* Searches the extension mappings of each protected modules to determine if an extension
* is authorized by any of them. Authorized extensions cannot be unilaterally removed by
* the operator.
*/
function _isAuthorizedExtension(address _extension) internal view returns (bool) {
for (uint256 i = 0; i < protectedModulesList.length; i++) {
if (protectedModules[protectedModulesList[i]].authorizedExtensions[_extension]) {
return true;
}
}
return false;
}
/**
* Checks if `_sender` (an extension) is allowed to call a module (which may be protected)
*/
function _senderAuthorizedForModule(address _module, address _sender) internal view returns (bool) {
if (protectedModules[_module].isProtected) {
return protectedModules[_module].authorizedExtensions[_sender];
}
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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;
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");
}
}
}
/*
Copyright 2020 Set Labs Inc.
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/27/21: Added validatePairsWithArray methods
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
/*
Copyright 2021 Set Labs Inc.
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IBaseManager } from "./IBaseManager.sol";
interface IExtension {
function manager() external view returns (IBaseManager);
}
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2018 Set Labs Inc.
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.6.10;
/**
* @title MutualUpgrade
* @author Set Protocol
*
* The MutualUpgrade contract contains a modifier for handling mutual upgrades between two parties
*/
contract MutualUpgrade {
/* ============ State Variables ============ */
// Mapping of upgradable units and if upgrade has been initialized by other party
mapping(bytes32 => bool) public mutualUpgrades;
/* ============ Events ============ */
event MutualUpgradeRegistered(
bytes32 _upgradeHash
);
/* ============ Modifiers ============ */
modifier mutualUpgrade(address _signerOne, address _signerTwo) {
require(
msg.sender == _signerOne || msg.sender == _signerTwo,
"Must be authorized address"
);
address nonCaller = _getNonCaller(_signerOne, _signerTwo);
// The upgrade hash is defined by the hash of the transaction call data and sender of msg,
// which uniquely identifies the function, arguments, and sender.
bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller));
if (!mutualUpgrades[expectedHash]) {
bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender));
mutualUpgrades[newHash] = true;
emit MutualUpgradeRegistered(newHash);
return;
}
delete mutualUpgrades[expectedHash];
// Run the rest of the upgrades
_;
}
/* ============ Internal Functions ============ */
function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) {
return msg.sender == _signerOne ? _signerTwo : _signerOne;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/*
Copyright 2021 Set Labs Inc.
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.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
interface IBaseManager {
function setToken() external returns(ISetToken);
function methodologist() external returns(address);
function operator() external returns(address);
function interactManager(address _module, bytes calldata _encoded) external;
function transferTokens(address _token, address _destination, uint256 _amount) external;
}
|
METHODOLOGIST ONLY: Marks a currently protected module as unprotected and deletes its authorized extension registries. Removes old module from the protected modules list. Called by the methodologist when they want to cede control over a protected module without triggering an emergency (for example, to remove it because its dead). _module Module to revoke protections for/
|
function unProtectModule(address _module) external onlyMethodologist {
_unProtectModule(_module);
emit ModuleUnprotected(_module);
}
| 280,458 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0 || b == 0) {
return 0;
}
c = a * b;
require(c / a == b, "Mul overflow!");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity automatically throws when dividing by 0
uint256 c = a / b;
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "Sub overflow!");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "Add overflow!");
return c;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
function balanceOf(address _owner) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns(bool);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner, "Only Owner can do that!");
_;
}
function transferOwnership(address _newOwner)
external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership()
external {
require(msg.sender == newOwner, "You are not new Owner!");
owner = newOwner;
newOwner = address(0);
emit OwnershipTransferred(owner, newOwner);
}
}
contract Permissioned {
function approve(address _spender, uint256 _value) public returns(bool);
function transferFrom(address _from, address _to, uint256 _value) external returns(bool);
function allowance(address _owner, address _spender) external view returns (uint256);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Burnable {
function burn(uint256 _value) external returns(bool);
function burnFrom(address _from, uint256 _value) external returns(bool);
// This notifies clients about the amount burnt
event Burn(address indexed _from, uint256 _value);
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract Aligato is ERC20Interface, Owned, Permissioned, Burnable {
using SafeMath for uint256; //Be aware of overflows
// This creates an array with all balances
mapping(address => uint256) internal _balanceOf;
// This creates an array with all allowance
mapping(address => mapping(address => uint256)) internal _allowance;
bool public isLocked = true; //only contract Owner can transfer tokens
uint256 icoSupply = 0;
//set ICO balance and emit
function setICO(address user, uint256 amt) internal{
uint256 amt2 = amt * (10 ** uint256(decimals));
_balanceOf[user] = amt2;
emit Transfer(0x0, user, amt2);
icoSupply += amt2;
}
// As ICO been done on platform, we need set proper amouts for ppl that participate
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(string _symbol, string _name, uint256 _supply, uint8 _decimals)
public {
require(_supply != 0, "Supply required!"); //avoid accidental deplyment with zero balance
owner = msg.sender;
symbol = _symbol;
name = _name;
decimals = _decimals;
totalSupply = _supply.mul(10 ** uint256(decimals)); //supply in constuctor is w/o decimal zeros
_balanceOf[msg.sender] = totalSupply - icoSupply;
emit Transfer(address(0), msg.sender, totalSupply - icoSupply);
}
// unlock transfers for everyone
function unlock() external onlyOwner returns (bool success)
{
require (isLocked == true, "It is unlocked already!"); //you can unlock only once
isLocked = false;
return true;
}
/**
* Get the token balance for account
*
* Get token balance of `_owner` account
*
* @param _owner The address of the owner
*/
function balanceOf(address _owner)
external view
returns(uint256 balance) {
return _balanceOf[_owner];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value)
internal {
// check that contract is unlocked
require (isLocked == false || _from == owner, "Contract is locked!");
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0), "Can`t send to 0x0, use burn()");
// Check if the sender has enough
require(_balanceOf[_from] >= _value, "Not enough balance!");
// Subtract from the sender
_balanceOf[_from] = _balanceOf[_from].sub(_value);
// Add the same to the recipient
_balanceOf[_to] = _balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
}
/**
* 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)
external
returns(bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* 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)
external
returns(bool success) {
// Check allowance
require(_value <= _allowance[_from][msg.sender], "Not enough allowance!");
// Check balance
require(_value <= _balanceOf[_from], "Not enough balance!");
_allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
emit Approval(_from, _to, _allowance[_from][_to]);
return true;
}
/**
* 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;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
external
returns(bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
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)
external view
returns(uint256 value) {
return _allowance[_owner][_spender];
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value)
external
returns(bool success) {
_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)
external
returns(bool success) {
// Check allowance
require(_value <= _allowance[_from][msg.sender], "Not enough allowance!");
// Is tehere enough coins on account
require(_value <= _balanceOf[_from], "Insuffient balance!");
// Subtract from the sender's allowance
_allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);
_burn(_from, _value);
emit Approval(_from, msg.sender, _allowance[_from][msg.sender]);
return true;
}
function _burn(address _from, uint256 _value)
internal {
// Check if the targeted balance is enough
require(_balanceOf[_from] >= _value, "Insuffient balance!");
// Subtract from the sender
_balanceOf[_from] = _balanceOf[_from].sub(_value);
// Updates totalSupply
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(_from, address(0), _value);
}
// ------------------------------------------------------------------------
// Don't accept accidental ETH
// ------------------------------------------------------------------------
function () external payable {
revert("This contract is not accepting ETH.");
}
//Owner can take ETH from contract
function withdraw(uint256 _amount)
external onlyOwner
returns (bool){
require(_amount <= address(this).balance, "Not enough balance!");
owner.transfer(_amount);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint256 _value)
external onlyOwner
returns(bool success) {
return ERC20Interface(tokenAddress).transfer(owner, _value);
}
}
|
Check if the targeted balance is enough Subtract from the sender Updates totalSupply
|
function _burn(address _from, uint256 _value)
internal {
require(_balanceOf[_from] >= _value, "Insuffient balance!");
_balanceOf[_from] = _balanceOf[_from].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(_from, address(0), _value);
}
| 13,031,519 |
./full_match/1/0xDdF499e726Bfde29Ce035F6B355e55757F08B5EF/sources/contracts/amo/Ramos.sol
|
Rebalance down when `protocolToken` spot price is above TPI. Single-side WITHDRAW `quoteToken` from balancer liquidity pool to lower price. BPT tokens are withdrawn from Aura rewards staking contract and used for balancer pool exit. Ramos rebalance fees are deducted from the amount of `quoteToken` returned from the exit The remainder `quoteToken` are repaid via the token vault bptAmountIn Amount of BPT tokens to deposit into balancer pool minQuoteTokenAmountOut Minimum amount of `quoteToken` expected to receive/ Unstake and send the BPT to the poolHelper QuoteToken single side exit Collect the fees on the output quote token
|
function rebalanceDownExit(
uint256 bptAmountIn,
uint256 minQuoteTokenAmountOut
) external override onlyElevatedAccess whenNotPaused enoughCooldown {
_validateParams(minQuoteTokenAmountOut, bptAmountIn, maxRebalanceAmounts.bpt);
lastRebalanceTimeSecs = uint64(block.timestamp);
IBalancerPoolHelper _poolHelper = poolHelper;
amoStaking.withdrawAndUnwrap(bptAmountIn, false, address(_poolHelper));
uint256 quoteTokenAmountOut = _poolHelper.exitPool(
bptAmountIn, minQuoteTokenAmountOut, rebalancePercentageBoundLow, rebalancePercentageBoundUp,
postRebalanceDelta, 1-protocolTokenBalancerPoolIndex, treasuryPriceIndex(), quoteToken
);
uint256 feeAmt = quoteTokenAmountOut * rebalanceFees.rebalanceExitFeeBps / BPS_PRECISION;
if (feeAmt > 0) {
quoteToken.safeTransfer(feeCollector, feeAmt);
}
unchecked {
quoteTokenAmountOut -= feeAmt;
}
emit RebalanceDownExit(bptAmountIn, quoteTokenAmountOut, feeAmt);
if (quoteTokenAmountOut > 0) {
tokenVault.repayQuoteToken(quoteTokenAmountOut);
}
}
| 3,065,504 |
pragma solidity ^0.4.24;
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;
}
}
/**
* @title TRC21 interface
*/
interface ITRC21 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function issuer() external view returns (address);
function decimals() external view returns (uint8);
function estimateFee(uint256 value) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
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);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Fee(address indexed from, address indexed to, address indexed issuer, uint256 value);
}
/**
* @title Standard TRC21 token
* @dev Implementation of the basic standard token.
*/
contract TRC21 is ITRC21 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
uint256 private _minFee;
address private _issuer;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
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) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev The amount fee that will be lost when transferring.
*/
function minFee() public view returns (uint256) {
return _minFee;
}
/**
* @dev token's foundation
*/
function issuer() public view returns (address) {
return _issuer;
}
/**
* @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 Estimate transaction fee.
* @param value amount tokens sent
*/
function estimateFee(uint256 value) public view returns (uint256) {
return value.mul(0).add(_minFee);
}
function setMinFee(uint256 value) public {
require(msg.sender == _issuer);
_changeMinFee(value);
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner,address spender) public view returns (uint256){
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(to != address(0));
uint256 total = value.add(_minFee);
require(total <= _balances[msg.sender]);
_transfer(msg.sender, to, value);
if (_minFee > 0) {
_transfer(msg.sender, _issuer, _minFee);
emit Fee(msg.sender, to, _issuer, _minFee);
}
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
require(_balances[msg.sender] >= _minFee);
_allowed[msg.sender][spender] = value;
_transfer(msg.sender, _issuer, _minFee);
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
uint256 total = value.add(_minFee);
require(total <= _balances[from]);
require(value <= _allowed[from][msg.sender]); //msg.sender should be allowed to transfer maximum of value amount
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(total);
_transfer(from, to, value);
_transfer(from, _issuer, _minFee);
emit Fee(msg.sender, to, _issuer, _minFee);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(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 value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Transfers token's foundation to new issuer
* @param newIssuer The address to transfer ownership to.
*/
function _changeIssuer(address newIssuer) internal {
require(newIssuer != address(0));
_issuer = newIssuer;
}
/**
* @dev Change minFee
* @param value minFee
*/
function _changeMinFee(uint256 value) internal {
_minFee = value;
}
}
//Wrap token based on multisig wallet that only mints new token if there are user deposits
contract TomoBridgeWrapToken is TRC21 {
/*
* Events
*/
// event TxBurn(uint indexed transactionId);
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
event TokenBurn(uint256 indexed burnID, address indexed burner, uint256 value, bytes data);
/*
* Constants
*/
uint constant public MAX_OWNER_COUNT = 50;
uint public WITHDRAW_FEE = 0;
uint public DEPOSIT_FEE = 0;
/*
* Storage
*/
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
TokenBurnData[] public burnList;
struct TokenBurnData {
uint256 value;
address burner;
bytes data;
}
struct Transaction {
address destination;
uint value;
bytes data; //data is used in transactions altering owner list
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier onlyContractIssuer() {
require(msg.sender == issuer());
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require(transactions[transactionId].destination != 0);
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0);
_;
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor (address[] _owners,
uint _required, string memory _name,
string memory _symbol, uint8 _decimals,
uint256 cap, uint256 minFee,
uint256 depositFee, uint256 withdrawFee
) TRC21(_name, _symbol, _decimals) public validRequirement(_owners.length, _required) {
_mint(msg.sender, cap);
_changeIssuer(msg.sender);
_changeMinFee(minFee);
for (uint i=0; i<_owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
DEPOSIT_FEE = depositFee;
WITHDRAW_FEE = withdrawFee;
}
function transferContractIssuer(address newOwner) public onlyContractIssuer {
if (newOwner != address(0)) {
_changeIssuer(msg.sender);
}
}
function setDepositFee(uint256 depositFee) public onlyContractIssuer {
DEPOSIT_FEE = depositFee;
}
function setWithdrawFee(uint256 withdrawFee) public onlyContractIssuer {
WITHDRAW_FEE = withdrawFee;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
//transaction is considered as minting if no data provided, otherwise it's owner changing transaction
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Allows an user to burn the token.
function burn(uint value, bytes data)
public
{
require(value > WITHDRAW_FEE); //avoid spamming
super._burn(msg.sender, value);
if (WITHDRAW_FEE > 0) {
super._mint(issuer(), WITHDRAW_FEE);
}
uint256 burnValue = value.sub(WITHDRAW_FEE);
burnList.push(TokenBurnData({
value: burnValue,
burner: msg.sender,
data: data
}));
TokenBurn(burnList.length - 1, msg.sender, burnValue, data);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
// just need multisig for minting - freely burn
if (txn.data.length == 0) {
//execute minting transaction
txn.value = txn.value.sub(DEPOSIT_FEE);
super._mint(txn.destination, txn.value);
if (DEPOSIT_FEE > 0) {
super._mint(issuer(), DEPOSIT_FEE);
}
Execution(transactionId);
} else {
//transaction that alters the owners list
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint end = to > transactionCount? transactionCount: to;
uint[] memory transactionIdsTemp = new uint[](end - from);
uint count = 0;
uint i;
for (i = from; i < to; i++) {
if ((pending && !transactions[i].executed)
|| (executed && transactions[i].executed))
{
transactionIdsTemp[count] = i;
count += 1;
}
}
_transactionIds = new uint[](count);
for (i = 0; i < count; i++)
_transactionIds[i] = transactionIdsTemp[i];
}
function getBurnCount() public view returns (uint256) {
return burnList.length;
}
function getBurn(uint burnId) public view returns (address _burner, uint256 _value, bytes _data) {
_burner = burnList[burnId].burner;
_value = burnList[burnId].value;
_data = burnList[burnId].data;
}
}
|
Returns array with owner addresses, which confirmed transaction. transactionId Transaction ID. return Returns array of owner addresses.
|
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
| 951,371 |
./full_match/11155111/0x3f9C6646CCFa4597C45761B3e9a1Da0cF00253D5/sources/src/Streams.sol
|
Calculate the amount squeezable by a user from a single streams history entry. userId The ID of the user to squeeze streams for. historyEntry The squeezed history entry. squeezeStartCap The squeezed time range start. squeezeEndCap The squeezed time range end. return squeezedAmt The squeezed amount. Binary search for the `idx` of the first occurrence of `userId`
|
function _squeezedAmt(
uint256 userId,
StreamsHistory memory historyEntry,
uint32 squeezeStartCap,
uint32 squeezeEndCap
) private view returns (uint128 squeezedAmt) {
unchecked {
StreamReceiver[] memory receivers = historyEntry.receivers;
uint256 idx = 0;
for (uint256 idxCap = receivers.length; idx < idxCap;) {
uint256 idxMid = (idx + idxCap) / 2;
if (receivers[idxMid].userId < userId) {
idx = idxMid + 1;
idxCap = idxMid;
}
}
uint32 updateTime = historyEntry.updateTime;
uint32 maxEnd = historyEntry.maxEnd;
uint256 amt = 0;
for (; idx < receivers.length; idx++) {
StreamReceiver memory receiver = receivers[idx];
if (receiver.userId != userId) break;
(uint32 start, uint32 end) =
_streamRange(receiver, updateTime, maxEnd, squeezeStartCap, squeezeEndCap);
amt += _streamedAmt(receiver.config.amtPerSec(), start, end);
}
return uint128(amt);
}
}
| 3,824,097 |
/*
・
* ★
・ 。
・ ゚☆ 。
* ★ ゚・。 * 。
* ☆ 。・゚*.。
゚ *.。☆。★ ・
` .-:::::-.` `-::---...```
`-:` .:+ssssoooo++//:.` .-/+shhhhhhhhhhhhhyyyssooo:
.--::. .+ossso+/////++/:://-` .////+shhhhhhhhhhhhhhhhhhhhhy
`-----::. `/+////+++///+++/:--:/+/- -////+shhhhhhhhhhhhhhhhhhhhhy
`------:::-` `//-.``.-/+ooosso+:-.-/oso- -////+shhhhhhhhhhhhhhhhhhhhhy
.--------:::-` :+:.` .-/osyyyyyyso++syhyo.-////+shhhhhhhhhhhhhhhhhhhhhy
`-----------:::-. +o+:-.-:/oyhhhhhhdhhhhhdddy:-////+shhhhhhhhhhhhhhhhhhhhhy
.------------::::-- `oys+/::/+shhhhhhhdddddddddy/-////+shhhhhhhhhhhhhhhhhhhhhy
.--------------:::::-` +ys+////+yhhhhhhhddddddddhy:-////+yhhhhhhhhhhhhhhhhhhhhhy
`----------------::::::-`.ss+/:::+oyhhhhhhhhhhhhhhho`-////+shhhhhhhhhhhhhhhhhhhhhy
.------------------:::::::.-so//::/+osyyyhhhhhhhhhys` -////+shhhhhhhhhhhhhhhhhhhhhy
`.-------------------::/:::::..+o+////+oosssyyyyyyys+` .////+shhhhhhhhhhhhhhhhhhhhhy
.--------------------::/:::.` -+o++++++oooosssss/. `-//+shhhhhhhhhhhhhhhhhhhhyo
.------- ``````.......--` `-/+ooooosso+/-` `./++++///:::--...``hhhhyo
`````
*
・ 。
・ ゚☆ 。
* ★ ゚・。 * 。
* ☆ 。・゚*.。
゚ *.。☆。★ ・
* ゚。·*・。 ゚*
☆゚・。°*. ゚
・ ゚*。・゚★。
・ *゚。 *
・゚*。★・
☆∴。 *
・ 。
*/
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol";
import "./mixins/OZ/ERC721Upgradeable.sol";
import "./mixins/FoundationTreasuryNode.sol";
import "./mixins/roles/FoundationAdminRole.sol";
import "./mixins/HasSecondarySaleFees.sol";
import "./mixins/NFT721Core.sol";
import "./mixins/NFT721Market.sol";
import "./mixins/NFT721Creator.sol";
import "./mixins/NFT721Metadata.sol";
import "./mixins/NFT721Mint.sol";
/**
* @title Foundation NFTs implemented using the ERC-721 standard.
* @dev This top level file holds no data directly to ease future upgrades.
*/
contract FNDNFT721 is
FoundationTreasuryNode,
FoundationAdminRole,
ERC165Upgradeable,
HasSecondarySaleFees,
ERC721Upgradeable,
NFT721Core,
NFT721Creator,
NFT721Market,
NFT721Metadata,
NFT721Mint
{
/**
* @notice Called once to configure the contract after the initial deployment.
* @dev This farms the initialize call out to inherited contracts as needed.
*/
function initialize(
address payable treasury,
string memory name,
string memory symbol
) public initializer {
FoundationTreasuryNode._initializeFoundationTreasuryNode(treasury);
ERC721Upgradeable.__ERC721_init(name, symbol);
HasSecondarySaleFees._initializeHasSecondarySaleFees();
NFT721Creator._initializeNFT721Creator();
NFT721Mint._initializeNFT721Mint();
}
/**
* @notice Allows a Foundation admin to update NFT config variables.
* @dev This must be called right after the initial call to `initialize`.
*/
function adminUpdateConfig(address _nftMarket, string memory baseURI) public onlyFoundationAdmin {
_updateNFTMarket(_nftMarket);
_updateBaseURI(baseURI);
}
/**
* @dev This is a no-op, just an explicit override to address compile errors due to inheritance.
*/
function _burn(uint256 tokenId)
internal
virtual
override(ERC721Upgradeable, NFT721Creator, NFT721Metadata, NFT721Mint)
{
super._burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.
*/
abstract 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 virtual 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;
}
// SPDX-License-Identifier: MIT
// solhint-disable
/**
* Copied from the OpenZeppelin repository in order to make `_tokenURIs` internal instead of private.
*/
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableMapUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is
Initializable,
ContextUpgradeable,
ERC165Upgradeable,
IERC721Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.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) internal _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.
*/
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_;
// 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(
IERC721ReceiverUpgradeable(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 {}
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* @notice A mixin that stores a reference to the Foundation treasury contract.
*/
abstract contract FoundationTreasuryNode is Initializable {
using AddressUpgradeable for address payable;
address payable private treasury;
/**
* @dev Called once after the initial deployment to set the Foundation treasury address.
*/
function _initializeFoundationTreasuryNode(address payable _treasury) internal initializer {
require(_treasury.isContract(), "FoundationTreasuryNode: Address is not a contract");
treasury = _treasury;
}
/**
* @notice Returns the address of the Foundation treasury.
*/
function getFoundationTreasury() public view returns (address payable) {
return treasury;
}
// `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way.
uint256[2000] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "../../interfaces/IAdminRole.sol";
import "../FoundationTreasuryNode.sol";
/**
* @notice Allows a contract to leverage an admin role defined by the Foundation contract.
*/
abstract contract FoundationAdminRole is FoundationTreasuryNode {
// This file uses 0 data slots (other than what's included via FoundationTreasuryNode)
modifier onlyFoundationAdmin() {
require(
IAdminRole(getFoundationTreasury()).isAdmin(msg.sender),
"FoundationAdminRole: caller does not have the Admin role"
);
_;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @notice An interface for communicating fees to 3rd party marketplaces.
* @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3
*/
abstract contract HasSecondarySaleFees is Initializable, ERC165Upgradeable {
/*
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
*
* => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;
/**
* @dev Called once after the initial deployment to register the interface with ERC165.
*/
function _initializeHasSecondarySaleFees() internal initializer {
_registerInterface(_INTERFACE_ID_FEES);
}
function getFeeRecipients(uint256 id) public view virtual returns (address payable[] memory);
function getFeeBps(uint256 id) public view virtual returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
/**
* @notice A place for common modifiers and functions used by various NFT721 mixins, if any.
* @dev This also leaves a gap which can be used to add a new mixin to the top of the inheritance tree.
*/
abstract contract NFT721Core {
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../interfaces/IFNDNFTMarket.sol";
import "./FoundationTreasuryNode.sol";
import "./HasSecondarySaleFees.sol";
import "./NFT721Creator.sol";
/**
* @notice Holds a reference to the Foundation Market and communicates fees to 3rd party marketplaces.
*/
abstract contract NFT721Market is FoundationTreasuryNode, HasSecondarySaleFees, NFT721Creator {
using AddressUpgradeable for address;
event NFTMarketUpdated(address indexed nftMarket);
IFNDNFTMarket private nftMarket;
/**
* @notice Returns the address of the Foundation NFTMarket contract.
*/
function getNFTMarket() public view returns (address) {
return address(nftMarket);
}
function _updateNFTMarket(address _nftMarket) internal {
require(_nftMarket.isContract(), "NFT721Market: Market address is not a contract");
nftMarket = IFNDNFTMarket(_nftMarket);
emit NFTMarketUpdated(_nftMarket);
}
/**
* @notice Returns an array of recipient addresses to which fees should be sent.
* The expected fee amount is communicated with `getFeeBps`.
*/
function getFeeRecipients(uint256 id) public view override returns (address payable[] memory) {
require(_exists(id), "ERC721Metadata: Query for nonexistent token");
address payable[] memory result = new address payable[](2);
result[0] = getFoundationTreasury();
result[1] = getTokenCreatorPaymentAddress(id);
return result;
}
/**
* @notice Returns an array of fees in basis points.
* The expected recipients is communicated with `getFeeRecipients`.
*/
function getFeeBps(
uint256 /* id */
) public view override returns (uint256[] memory) {
(, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints) = nftMarket.getFeeConfig();
uint256[] memory result = new uint256[](2);
result[0] = secondaryF8nFeeBasisPoints;
result[1] = secondaryCreatorFeeBasisPoints;
return result;
}
/**
* @notice Get fee recipients and fees in a single call.
* The data is the same as when calling getFeeRecipients and getFeeBps separately.
*/
function getFees(uint256 tokenId)
public
view
returns (address payable[2] memory recipients, uint256[2] memory feesInBasisPoints)
{
require(_exists(tokenId), "ERC721Metadata: Query for nonexistent token");
recipients[0] = getFoundationTreasury();
recipients[1] = getTokenCreatorPaymentAddress(tokenId);
(, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints) = nftMarket.getFeeConfig();
feesInBasisPoints[0] = secondaryF8nFeeBasisPoints;
feesInBasisPoints[1] = secondaryCreatorFeeBasisPoints;
}
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./OZ/ERC721Upgradeable.sol";
/**
* @notice Allows each token to be associated with a creator.
*/
abstract contract NFT721Creator is Initializable, ERC721Upgradeable {
mapping(uint256 => address payable) private tokenIdToCreator;
/**
* @dev Stores an optional alternate address to receive creator revenue and royalty payments.
*/
mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress;
event TokenCreatorUpdated(address indexed fromCreator, address indexed toCreator, uint256 indexed tokenId);
event TokenCreatorPaymentAddressSet(
address indexed fromPaymentAddress,
address indexed toPaymentAddress,
uint256 indexed tokenId
);
/*
* bytes4(keccak256('tokenCreator(uint256)')) == 0x40c1a064
*/
bytes4 private constant _INTERFACE_TOKEN_CREATOR = 0x40c1a064;
/*
* bytes4(keccak256('getTokenCreatorPaymentAddress(uint256)')) == 0xec5f752e;
*/
bytes4 private constant _INTERFACE_TOKEN_CREATOR_PAYMENT_ADDRESS = 0xec5f752e;
modifier onlyCreatorAndOwner(uint256 tokenId) {
require(tokenIdToCreator[tokenId] == msg.sender, "NFT721Creator: Caller is not creator");
require(ownerOf(tokenId) == msg.sender, "NFT721Creator: Caller does not own the NFT");
_;
}
/**
* @dev Called once after the initial deployment to register the interface with ERC165.
*/
function _initializeNFT721Creator() internal initializer {
_registerInterface(_INTERFACE_TOKEN_CREATOR);
}
/**
* @notice Allows ERC165 interfaces which were not included originally to be registered.
* @dev Currently this is the only new interface, but later other mixins can overload this function to do the same.
*/
function registerInterfaces() public {
_registerInterface(_INTERFACE_TOKEN_CREATOR_PAYMENT_ADDRESS);
}
/**
* @notice Returns the creator's address for a given tokenId.
*/
function tokenCreator(uint256 tokenId) public view returns (address payable) {
return tokenIdToCreator[tokenId];
}
/**
* @notice Returns the payment address for a given tokenId.
* @dev If an alternate address was not defined, the creator is returned instead.
*/
function getTokenCreatorPaymentAddress(uint256 tokenId)
public
view
returns (address payable tokenCreatorPaymentAddress)
{
tokenCreatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId];
if (tokenCreatorPaymentAddress == address(0)) {
tokenCreatorPaymentAddress = tokenIdToCreator[tokenId];
}
}
function _updateTokenCreator(uint256 tokenId, address payable creator) internal {
emit TokenCreatorUpdated(tokenIdToCreator[tokenId], creator, tokenId);
tokenIdToCreator[tokenId] = creator;
}
/**
* @dev Allow setting a different address to send payments to for both primary sale revenue
* and secondary sales royalties.
* This is immutable since it's only exposed publicly when minting a new NFT.
*/
function _setTokenCreatorPaymentAddress(uint256 tokenId, address payable tokenCreatorPaymentAddress) internal {
if (tokenCreatorPaymentAddress != address(0)) {
tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress;
emit TokenCreatorPaymentAddressSet(address(0), tokenCreatorPaymentAddress, tokenId);
}
}
/**
* @notice Allows the creator to burn if they currently own the NFT.
*/
function burn(uint256 tokenId) public onlyCreatorAndOwner(tokenId) {
_burn(tokenId);
}
/**
* @dev Remove the creator record when burned.
*/
function _burn(uint256 tokenId) internal virtual override {
delete tokenIdToCreator[tokenId];
super._burn(tokenId);
}
uint256[999] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "./NFT721Core.sol";
import "./NFT721Creator.sol";
/**
* @notice A mixin to extend the OpenZeppelin metadata implementation.
*/
abstract contract NFT721Metadata is NFT721Creator {
using StringsUpgradeable for uint256;
/**
* @dev Stores hashes minted by a creator to prevent duplicates.
*/
mapping(address => mapping(string => bool)) private creatorToIPFSHashToMinted;
event BaseURIUpdated(string baseURI);
event TokenIPFSPathUpdated(uint256 indexed tokenId, string indexed indexedTokenIPFSPath, string tokenIPFSPath);
// This event was used in an order version of the contract
event NFTMetadataUpdated(string name, string symbol, string baseURI);
/**
* @notice Returns the IPFSPath to the metadata JSON file for a given NFT.
*/
function getTokenIPFSPath(uint256 tokenId) public view returns (string memory) {
return _tokenURIs[tokenId];
}
/**
* @notice Checks if the creator has already minted a given NFT.
*/
function getHasCreatorMintedIPFSHash(address creator, string memory tokenIPFSPath) public view returns (bool) {
return creatorToIPFSHashToMinted[creator][tokenIPFSPath];
}
function _updateBaseURI(string memory _baseURI) internal {
_setBaseURI(_baseURI);
emit BaseURIUpdated(_baseURI);
}
/**
* @dev The IPFS path should be the CID + file.extension, e.g.
* `QmfPsfGwLhiJrU8t9HpG4wuyjgPo9bk8go4aQqSu9Qg4h7/metadata.json`
*/
function _setTokenIPFSPath(uint256 tokenId, string memory _tokenIPFSPath) internal {
// 46 is the minimum length for an IPFS content hash, it may be longer if paths are used
require(bytes(_tokenIPFSPath).length >= 46, "NFT721Metadata: Invalid IPFS path");
require(!creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath], "NFT721Metadata: NFT was already minted");
creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath] = true;
_setTokenURI(tokenId, _tokenIPFSPath);
}
/**
* @dev When a token is burned, remove record of it allowing that creator to re-mint the same NFT again in the future.
*/
function _burn(uint256 tokenId) internal virtual override {
delete creatorToIPFSHashToMinted[msg.sender][_tokenURIs[tokenId]];
super._burn(tokenId);
}
uint256[999] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "./OZ/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./NFT721Creator.sol";
import "./NFT721Market.sol";
import "./NFT721Metadata.sol";
/**
* @notice Allows creators to mint NFTs.
*/
abstract contract NFT721Mint is Initializable, ERC721Upgradeable, NFT721Creator, NFT721Market, NFT721Metadata {
using AddressUpgradeable for address;
uint256 private nextTokenId;
event Minted(
address indexed creator,
uint256 indexed tokenId,
string indexed indexedTokenIPFSPath,
string tokenIPFSPath
);
/**
* @notice Gets the tokenId of the next NFT minted.
*/
function getNextTokenId() public view returns (uint256) {
return nextTokenId;
}
/**
* @dev Called once after the initial deployment to set the initial tokenId.
*/
function _initializeNFT721Mint() internal initializer {
// Use ID 1 for the first NFT tokenId
nextTokenId = 1;
}
/**
* @notice Allows a creator to mint an NFT.
*/
function mint(string memory tokenIPFSPath) public returns (uint256 tokenId) {
tokenId = nextTokenId++;
_mint(msg.sender, tokenId);
_updateTokenCreator(tokenId, msg.sender);
_setTokenIPFSPath(tokenId, tokenIPFSPath);
emit Minted(msg.sender, tokenId, tokenIPFSPath, tokenIPFSPath);
}
/**
* @notice Allows a creator to mint an NFT and set approval for the Foundation marketplace.
* This can be used by creators the first time they mint an NFT to save having to issue a separate
* approval transaction before starting an auction.
*/
function mintAndApproveMarket(string memory tokenIPFSPath) public returns (uint256 tokenId) {
tokenId = mint(tokenIPFSPath);
setApprovalForAll(getNFTMarket(), true);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address.
*/
function mintWithCreatorPaymentAddress(string memory tokenIPFSPath, address payable tokenCreatorPaymentAddress)
public
returns (uint256 tokenId)
{
require(tokenCreatorPaymentAddress != address(0), "NFT721Mint: tokenCreatorPaymentAddress is required");
tokenId = mint(tokenIPFSPath);
_setTokenCreatorPaymentAddress(tokenId, tokenCreatorPaymentAddress);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address.
* Also sets approval for the Foundation marketplace. This can be used by creators the first time they mint an NFT to
* save having to issue a separate approval transaction before starting an auction.
*/
function mintWithCreatorPaymentAddressAndApproveMarket(
string memory tokenIPFSPath,
address payable tokenCreatorPaymentAddress
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentAddress(tokenIPFSPath, tokenCreatorPaymentAddress);
setApprovalForAll(getNFTMarket(), true);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
*/
function mintWithCreatorPaymentFactory(
string memory tokenIPFSPath,
address paymentAddressFactory,
bytes memory paymentAddressCallData
) public returns (uint256 tokenId) {
bytes memory returnData = paymentAddressFactory.functionCall(paymentAddressCallData);
address payable tokenCreatorPaymentAddress;
// solhint-disable-next-line no-inline-assembly
assembly {
tokenCreatorPaymentAddress := mload(add(returnData, 32))
}
tokenId = mintWithCreatorPaymentAddress(tokenIPFSPath, tokenCreatorPaymentAddress);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
* Also sets approval for the Foundation marketplace. This can be used by creators the first time they mint an NFT to
* save having to issue a separate approval transaction before starting an auction.
*/
function mintWithCreatorPaymentFactoryAndApproveMarket(
string memory tokenIPFSPath,
address paymentAddressFactory,
bytes memory paymentAddressCallData
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentFactory(tokenIPFSPath, paymentAddressFactory, paymentAddressCallData);
setApprovalForAll(getNFTMarket(), true);
}
/**
* @dev Explicit override to address compile errors.
*/
function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Creator, NFT721Metadata) {
super._burn(tokenId);
}
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../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.7.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.7.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @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.7.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.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 SafeMathUpgradeable {
/**
* @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 "../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.7.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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 EnumerableMapUpgradeable {
// 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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @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--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
/**
* @notice Interface for AdminRole which wraps the default admin role from
* OpenZeppelin's AccessControl for easy integration.
*/
interface IAdminRole {
function isAdmin(address account) external view returns (bool);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
// solhint-disable
pragma solidity ^0.7.0;
interface IFNDNFTMarket {
function getFeeConfig()
external
view
returns (
uint256 primaryF8nFeeBasisPoints,
uint256 secondaryF8nFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
);
}
|
ERC-721 Non-Fungible Token Standard, optional enumeration extension/
|
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
}
| 93,032 |
./full_match/1/0x66600c4f55527C410D4067b21474c0fa1fe1331D/sources/@metalabel/solmate/src/tokens/ERC721.sol
|
Ownership check above ensures no underflow.
|
function _burn(uint256 id) internal virtual {
address owner = _tokenData[id].owner;
require(owner != address(0), "NOT_MINTED");
unchecked {
_balanceOf[owner]--;
}
delete _tokenData[id];
delete getApproved[id];
emit Transfer(owner, address(0), id);
}
INTERNAL SAFE MINT LOGIC
| 4,932,384 |
./full_match/42/0xD2830892D28ceFA2cb3aA0D67A38357654b9b16a/sources/browser/KaizenAirdropper.sol
|
--------------------------------------------------------------------------------------------------------------------------
|
{
address private admin;
address private signOwner;
IERC20 private token;
uint256 private defaultTokensAmount;
uint32 private claimedCount;
mapping(uint16 => uint256) private bitmask;
string private constant ERR_MSG_SENDER = "ERR_MSG_SENDER";
string private constant ERR_AMOUNT = "ERR_AMOUNT";
constructor(address _admin, address _signOwner, address _tokenAddress, uint256 _defaultTokensAmount) public
{
admin = _admin;
signOwner = _signOwner;
token = IERC20(_tokenAddress);
defaultTokensAmount = _defaultTokensAmount;
}
function getAdmin() external view returns (address)
{
return admin;
}
function getSignOwner() external view returns (address)
{
return signOwner;
}
function setSignOwner(address _signOwner) external
{
require(msg.sender == admin, ERR_MSG_SENDER);
signOwner = _signOwner;
}
function getTokenAddress() external view returns (address)
{
return address(token);
}
function getTotalTokensBalance() external view returns (uint256)
{
return token.balanceOf(address(this));
}
function sendTokens(address _to, uint256 _amount) external
{
require(msg.sender == admin, ERR_MSG_SENDER);
require(_amount <= token.balanceOf(address(this)), ERR_AMOUNT);
if(_amount == 0)
{
token.transfer(_to, token.balanceOf(address(this)));
}
else
{
token.transfer(_to, _amount);
}
}
function sendTokens(address _to, uint256 _amount) external
{
require(msg.sender == admin, ERR_MSG_SENDER);
require(_amount <= token.balanceOf(address(this)), ERR_AMOUNT);
if(_amount == 0)
{
token.transfer(_to, token.balanceOf(address(this)));
}
else
{
token.transfer(_to, _amount);
}
}
function sendTokens(address _to, uint256 _amount) external
{
require(msg.sender == admin, ERR_MSG_SENDER);
require(_amount <= token.balanceOf(address(this)), ERR_AMOUNT);
if(_amount == 0)
{
token.transfer(_to, token.balanceOf(address(this)));
}
else
{
token.transfer(_to, _amount);
}
}
function getDefaultTokensAmount() external view returns (uint256)
{
return defaultTokensAmount;
}
function setDefaultTokensAmount(uint256 _amount) external
{
require(msg.sender == admin, ERR_MSG_SENDER);
defaultTokensAmount = _amount;
}
function getClaimedCount() external view returns (uint32)
{
return claimedCount;
}
function claimTokens(uint16 _block, uint8 _bit, bytes memory _signature) external
{
require(!isClaimed(_block, _bit), "ERR_ALREADY_CLAIMED");
string memory message = string(abi.encodePacked(toAsciiString(msg.sender), ";", uintToString(_block), ";", uintToString(_bit)));
verify(message, _signature);
token.transfer(msg.sender, defaultTokensAmount);
setClaimed(_block, _bit);
}
function claimTokensTest(uint16 _block, uint8 _bit, bytes memory _signature) external returns (bytes32 messageHash_)
{
string memory message = string(abi.encodePacked(toAsciiString(msg.sender), ";", uintToString(_block), ";", uintToString(_bit)));
messageHash_ = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(_message))));
token.transfer(msg.sender, defaultTokensAmount);
setClaimed(_block, _bit);
}
function claimTokens(uint16 _block, uint8 _bit, uint256 _tokensCount, bytes memory _signature) external
{
require(!isClaimed(_block, _bit));
string memory message = string(abi.encodePacked(toAsciiString(msg.sender), ";", uintToString(_block), ";", uintToString(_bit), ";", uintToString(_tokensCount)));
verify(message, _signature);
token.transfer(msg.sender, _tokensCount);
setClaimed(_block, _bit);
}
function setClaimed(uint16 _block, uint8 _bit) private
{
uint256 bitBlock = bitmask[_block];
uint256 mask = uint256(1) << _bit;
bitmask[_block] = (bitBlock | mask);
++claimedCount;
}
function isClaimed(uint16 _block, uint8 _bit) public view returns (bool)
{
uint256 bitBlock = bitmask[_block];
uint256 mask = uint256(1) << _bit;
return (bitBlock & mask) > 0;
}
function verify(string memory _message, bytes memory _sig) private view
{
bytes32 messageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(_message))));
address messageSigner = recover(messageHash, _sig);
require(messageSigner == signOwner, "ERR_VERIFICATION_FAILED");
}
function verifyTest(string memory _message, bytes memory _sig) public view returns (bool)
{
bytes32 messageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(_message))));
address messageSigner = recover(messageHash, _sig);
return messageSigner == signOwner;
}
function verifyTest(string memory _message, bytes memory _sig) private view returns (bytes32 messageHash_, address messageSigner_);
{
messageHash_ = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(_message))));
messageSigner_ = recover(messageHash, _sig);
}
function recover(bytes32 _hash, bytes memory _sig) private pure returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
require(_sig.length == 65, "ERR_RECOVER_SIG_SIZE");
assembly
{
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if(v < 27)
{
v += 27;
}
require(v == 27 || v == 28, "ERR_RECOVER_INVALID_SIG");
return ecrecover(_hash, v, r, s);
}
function recover(bytes32 _hash, bytes memory _sig) private pure returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
require(_sig.length == 65, "ERR_RECOVER_SIG_SIZE");
assembly
{
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if(v < 27)
{
v += 27;
}
require(v == 27 || v == 28, "ERR_RECOVER_INVALID_SIG");
return ecrecover(_hash, v, r, s);
}
function recover(bytes32 _hash, bytes memory _sig) private pure returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
require(_sig.length == 65, "ERR_RECOVER_SIG_SIZE");
assembly
{
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if(v < 27)
{
v += 27;
}
require(v == 27 || v == 28, "ERR_RECOVER_INVALID_SIG");
return ecrecover(_hash, v, r, s);
}
function uintToString(uint _i) private pure returns (string memory)
{
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 uintToString(uint _i) private pure returns (string memory)
{
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 uintToString(uint _i) private pure returns (string memory)
{
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 uintToString(uint _i) private pure returns (string memory)
{
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 toAsciiString(address _addr) private pure returns (string memory)
{
bytes memory s = new bytes(40);
for(uint i = 0; i < 20; i++)
{
byte b = byte(uint8(uint(_addr) / (2**(8*(19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function toAsciiString(address _addr) private pure returns (string memory)
{
bytes memory s = new bytes(40);
for(uint i = 0; i < 20; i++)
{
byte b = byte(uint8(uint(_addr) / (2**(8*(19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(byte value) private pure returns (byte)
{
if(uint8(value) < 10)
{
return byte(uint8(value) + 0x30);
}
else
{
return byte(uint8(value) + 0x57);
}
}
function char(byte value) private pure returns (byte)
{
if(uint8(value) < 10)
{
return byte(uint8(value) + 0x30);
}
else
{
return byte(uint8(value) + 0x57);
}
}
function char(byte value) private pure returns (byte)
{
if(uint8(value) < 10)
{
return byte(uint8(value) + 0x30);
}
else
{
return byte(uint8(value) + 0x57);
}
}
}
| 16,203,472 |
pragma solidity ^0.4.18;
/**
* @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;
/**
* @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 {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract 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;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable, SafeMath{
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
mapping (address => uint256) public refunded;
State public state;
address[] public reserveWallet;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* @dev This constructor sets the addresses of
* 10 reserve wallets.
* and forwarding it if crowdsale is successful.
* @param _reserveWallet address[5] The addresses of reserve wallet.
*/
function RefundVault(address[] _reserveWallet) {
state = State.Active;
reserveWallet = _reserveWallet;
}
/**
* @dev This function is called when user buy tokens. Only RefundVault
* contract stores the Ether user sent which forwarded from crowdsale
* contract.
* @param investor address The address who buy the token from crowdsale.
*/
function deposit(address investor) onlyOwner payable {
require(state == State.Active);
deposited[investor] = add(deposited[investor], msg.value);
}
event Transferred(address _to, uint _value);
/**
* @dev This function is called when crowdsale is successfully finalized.
*/
function close() onlyOwner {
require(state == State.Active);
state = State.Closed;
uint256 balance = this.balance;
uint256 reserveAmountForEach = div(balance, reserveWallet.length);
for(uint8 i = 0; i < reserveWallet.length; i++){
reserveWallet[i].transfer(reserveAmountForEach);
Transferred(reserveWallet[i], reserveAmountForEach);
}
Closed();
}
/**
* @dev This function is called when crowdsale is unsuccessfully finalized
* and refund is required.
*/
function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
/**
* @dev This function allows for user to refund Ether.
*/
function refund(address investor) returns (bool) {
require(state == State.Refunding);
if (refunded[investor] > 0) {
return false;
}
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
refunded[investor] = depositedValue;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
return true;
}
}
|
This function is called when crowdsale is successfully finalized./
|
function close() onlyOwner {
require(state == State.Active);
state = State.Closed;
uint256 balance = this.balance;
uint256 reserveAmountForEach = div(balance, reserveWallet.length);
for(uint8 i = 0; i < reserveWallet.length; i++){
reserveWallet[i].transfer(reserveAmountForEach);
Transferred(reserveWallet[i], reserveAmountForEach);
}
Closed();
}
| 1,015,755 |
./full_match/1/0x6d8B6B7ce705a13f4C1F82398974F52Df3E4abC9/sources/SmileOfDAO.sol
|
_voteType = 1 : Up Vote _voteType = 2 : Down Vote _voteType = 3 : Nutral Vote
|
function voteProposal(uint256 _proposalID, uint256 _voteType) public {
require(token.balanceOf(msg.sender) >= 1, "Not enough NFT in your account");
require(proposalID >= _proposalID, "Proposal not exist");
require(proposal[_proposalID].isApproved, "Proposal not approved");
require(!proposal[_proposalID].isCompleted, "Proposal is completed");
require(!votedUser[_proposalID][msg.sender], "Already vote on this");
if(_voteType == 1){
proposal[_proposalID].upVote = proposal[_proposalID].upVote + token.balanceOf(msg.sender);
proposal[_proposalID].downVote = proposal[_proposalID].downVote + token.balanceOf(msg.sender);
proposal[_proposalID].abstainVote = proposal[_proposalID].abstainVote + token.balanceOf(msg.sender);
}
votedUser[_proposalID][msg.sender] = true;
}
| 8,401,785 |
//Address: 0xA25D01d15fC0e3cDeDE1BEbEE4124394aaE0DB33
//Contract name: FollowCoin
//Balance: 0 Ether
//Verification Date: 10/27/2017
//Transacion Count: 1113
// CODE STARTS HERE
pragma solidity ^0.4.13;
/**
* @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;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract FollowCoin is Ownable, ERC20 {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// This creates an array with all balances
mapping (address => uint256) public balances;
mapping (address => bool) public allowedAccount;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public isHolder;
address [] public holders;
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
bool public contributorsLockdown = true;
function disableLockDown() onlyOwner {
contributorsLockdown = false;
}
modifier coinsLocked() {
require(!contributorsLockdown || msg.sender == owner || allowedAccount[msg.sender]);
_;
}
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function FollowCoin(
address multiSigWallet,
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
owner = multiSigWallet;
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
balances[owner] = totalSupply; // Give the creator all initial tokens
if (isHolder[owner] != true) {
holders[holders.length++] = owner;
isHolder[owner] = true;
}
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal coinsLocked {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(balanceOf(_from) >= _value); // Check if the sender has enough
require(balanceOf(_to).add(_value) > balanceOf(_to)); // Check for overflows
balances[_from] = balanceOf(_from).sub(_value); // Subtract from the sender
balances[_to] = balanceOf(_to).add(_value); // Add the same to the recipient
if (isHolder[_to] != true) {
holders[holders.length++] = _to;
isHolder[_to] = true;
}
Transfer(_from, _to, _value);
}
/**
* 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) {
require(_to != address(this));
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in 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) returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in 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;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowance[_owner][_spender];
}
function allowAccount(address _target, bool allow) onlyOwner returns (bool success) {
allowedAccount[_target] = allow;
return true;
}
function mint(uint256 mintedAmount) onlyOwner {
balances[msg.sender] = balanceOf(msg.sender).add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
Transfer(0, owner, mintedAmount);
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) onlyOwner returns (bool success) {
require(balanceOf(msg.sender) >= _value); // Check if the sender has enough
balances[msg.sender] = balanceOf(msg.sender).sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
}
/*
* Haltable
*
* Abstract contract that allows children to implement an
* emergency stop mechanism. Differs from Pausable by requiring a state.
*
*
* Originally envisioned in FirstBlood ICO contract.
*/
contract Haltable is Ownable {
bool public halted;
modifier inNormalState {
assert(!halted);
_;
}
modifier inEmergencyState {
assert(halted);
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner inNormalState {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner inEmergencyState {
halted = false;
}
}
contract FollowCoinTokenSale is Haltable {
using SafeMath for uint256;
address public beneficiary;
address public multisig;
uint public tokenLimitPerWallet;
uint public hardCap;
uint public amountRaised;
uint public totalTokens;
uint public tokensSold = 0;
uint public investorCount = 0;
uint public startTimestamp;
uint public deadline;
uint public tokensPerEther;
FollowCoin public tokenReward;
mapping(address => uint256) public balances;
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constructor function
*
* Setup the owner
*/
function FollowCoinTokenSale(
address multiSigWallet,
uint icoTokensLimitPerWallet,
uint icoHardCap,
uint icoStartTimestamp,
uint durationInDays,
uint icoTotalTokens,
uint icoTokensPerEther,
address addressOfTokenUsedAsReward
) {
multisig = multiSigWallet;
owner = multiSigWallet;
hardCap = icoHardCap;
deadline = icoStartTimestamp + durationInDays * 1 days;
startTimestamp = icoStartTimestamp;
totalTokens = icoTotalTokens;
tokenLimitPerWallet = icoTokensLimitPerWallet;
tokensPerEther = icoTokensPerEther;
tokenReward = FollowCoin(addressOfTokenUsedAsReward);
beneficiary = multisig;
}
function changeMultisigWallet(address _multisig) onlyOwner {
require(_multisig != address(0));
multisig = _multisig;
}
function changeTokenReward(address _token) onlyOwner {
require(_token != address(0));
tokenReward = FollowCoin(_token);
beneficiary = tokenReward.owner();
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () payable preSaleActive inNormalState {
buyTokens();
}
function buyTokens() payable preSaleActive inNormalState {
require(msg.value > 0);
uint amount = msg.value;
require(balanceOf(msg.sender).add(amount) <= tokenLimitPerWallet);
uint tokens = calculateTokenAmount(amount);
require(totalTokens >= tokens);
require(tokensSold.add(tokens) <= hardCap); // hardCap limit
balances[msg.sender] = balances[msg.sender].add(amount);
amountRaised = amountRaised.add(amount);
tokensSold = tokensSold.add(tokens);
totalTokens = totalTokens.sub(tokens);
if (tokenReward.balanceOf(msg.sender) == 0) investorCount++;
tokenReward.transfer(msg.sender, tokens);
multisig.transfer(amount);
FundTransfer(msg.sender, amount, true);
}
modifier preSaleActive() {
require(now >= startTimestamp);
require(now < deadline);
_;
}
function setSold(uint tokens) onlyOwner {
tokensSold = tokensSold.add(tokens);
}
function sendTokensBackToWallet() onlyOwner {
totalTokens = 0;
tokenReward.transfer(multisig, tokenReward.balanceOf(address(this)));
}
function getTokenBalance(address _from) constant returns(uint) {
return tokenReward.balanceOf(_from);
}
function calculateTokenAmount(uint256 amount) constant returns(uint256) {
return amount.mul(tokensPerEther);
}
}
|
Transfer tokens from other address Send `_value` tokens to `_to` in behalf of `_from` _from The address of the sender _to The address of the recipient _value the amount to send/
|
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| 1,014,684 |
/*element14*/
/*CoinFlip 1% of HouseEdge*/
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize 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.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
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_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
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(tmp[i]);
b2 = uint160(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 _a, string _b) internal pure returns (int) {
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 _haystack, string _needle) internal pure returns (int) {
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 _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
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;
for (uint 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 strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
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(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
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 = oraclize_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))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(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(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(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(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 == false) return false;
// 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(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// 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(proof[ledgerProofLength+32+8]))) return false;
// 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 (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// 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 (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_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 from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
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, address) {
// 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)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
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 sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 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, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
/*element14*/
contract CoinFlip is usingOraclize {
modifier onlyAdmin() {
require(msg.sender == adminAddress);
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
event newBet(string _str);
//Setup
address public adminAddress;
//GameSetup
uint public minBet;
uint public maxProfit;
//FeeSetup
uint public oraclizeFee;
uint public adminFee;
uint public oraclizeGasLimit;
uint public maxProfitPercentage;
uint public totalPlay;
uint public totalLose;
uint public totalWon;
uint public totalWeiWon;
uint public totalWeiLose;
uint public contractBalance;
//PlayerSetup
// Array of players
mapping (bytes32 => address) playerAddress;
mapping (bytes32 => uint) playerBetAmount;
mapping (bytes32 => uint) playerBetNumber;
string public _result;
function CoinFlip() payable {
//ConstructorVars
adminAddress=msg.sender;
//minBet = (5000000000000000 * 1 wei);
//adminFee=99; //1% of houseEdge
//oraclizeGasLimit = 235000;
//maxProfitPercentage=1;
}
function __callback(bytes32 queryId, string result) onlyOraclize {
_result=result;
uint weiWon;
if( (parseInt(result)/50) == playerBetNumber[queryId] ){
totalWon++;
weiWon=( ( playerBetAmount[queryId] * adminFee/100 ) - oraclizeFee)*2;
totalWeiWon+=weiWon;
playerAddress[queryId].transfer(weiWon );
}else{
totalLose++;
}
maxProfit=(this.balance * maxProfitPercentage)/100;
delete playerAddress[queryId];
delete playerBetAmount[queryId];
delete playerBetNumber[queryId];
}
function Bet(uint _number) payable returns (bytes32){
uint betValue = msg.value;
assert(maxProfit > (betValue*2));
if(betValue < minBet) throw;
totalWeiLose+=betValue;
totalPlay++;
bytes32 queryId = oraclize_query("WolframAlpha", "random number between 0 and 99",oraclizeGasLimit);
playerAddress[queryId]=msg.sender;
playerBetAmount[queryId]=betValue;
playerBetNumber[queryId]=_number;
return queryId;
}
function setGame(uint _adminFee , uint _minBet , uint _oraclizeGasLimit , uint _maxProfitPercentage , uint _oraclizeFee , uint newGas) public onlyAdmin{
adminFee = _adminFee;
minBet = (_minBet * 1 wei);
oraclizeGasLimit = _oraclizeGasLimit ;
maxProfitPercentage= _maxProfitPercentage;
maxProfit=(this.balance*_maxProfitPercentage)/100;
oraclizeFee=(_oraclizeFee * 1 wei);
oraclize_setCustomGasPrice(newGas * 1 wei);
contractBalance=this.balance;
}
function withdraw(uint _amount , address _addr) public onlyAdmin{
_addr.transfer(_amount);
contractBalance=this.balance;
maxProfit=(contractBalance*maxProfitPercentage)/100;
}
function updateBalance() payable{
contractBalance=this.balance;
maxProfit=(contractBalance*maxProfitPercentage)/100;
}
function getGameVars() public view returns(
uint _maxProfit,
uint _minBet,
uint _totalPlay,
uint _totalLose,
uint _totalWon,
uint _maxProfitPercentage,
uint _contractbalance,
uint _totalWeiWon,
uint _totalWeiLose
){
_maxProfit=maxProfit;
_minBet=minBet;
_totalPlay=totalPlay;
_totalLose=totalLose;
_totalWon=totalWon;
_maxProfitPercentage=maxProfitPercentage;
_contractbalance=contractBalance;
_totalWeiWon=totalWeiWon;
_totalWeiLose=totalWeiLose;
}
}
|
ConstructorVarsminBet = (5000000000000000 1 wei);adminFee=99; 1% of houseEdgeoraclizeGasLimit = 235000;maxProfitPercentage=1;
|
function CoinFlip() payable {
adminAddress=msg.sender;
}
| 432,526 |
//Address: 0xdf68995f07882120b44da1d0fabf41ca1681deec
//Contract name: Provide
//Balance: 0 Ether
//Verification Date: 8/30/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.13;
/**
* Provide platform contract.
*/
contract Provide {
using SafeMath for uint;
/** Provide contract owner; has ability to update the platform robot address. */
address public owner;
/** Provide (PRVD) token. */
ProvideToken public token;
/** Provide platform robot; has ability to update the wallet contract addresses. */
address public prvd;
/** Provide platform wallet where fees owed to Provide are remitted. */
address public prvdWallet;
/** Provide platform wallet where payment amounts owed to providers are escrowed. */
address public paymentEscrow;
/**
* @param _prvd Provide platform robot contract address
* @param _prvdWallet Provide platform wallet where fees owed to Provide are remitted
* @param _paymentEscrow Provide platform wallet where payment amounts owed to providers are escrowed
*/
function Provide(
address _token,
address _prvd,
address _prvdWallet,
address _paymentEscrow
) {
owner = msg.sender;
token = ProvideToken(_token);
prvd = _prvd;
prvdWallet = _prvdWallet;
paymentEscrow = _paymentEscrow;
}
/**
* Deploy a work order contract.
* @param _peer Address of party purchasing services
* @param _identifier Provide platform work order identifier (UUIDv4)
*/
function createWorkOrder(
address _peer,
uint128 _identifier
) onlyPrvd returns(address workOrder) {
return new ProvideWorkOrder(token, prvd, prvdWallet, paymentEscrow, _peer, _identifier);
}
/**
* Allow the contract owner to update Provide platform robot.
*/
function setPrvd(address _prvd) onlyOwner {
if (_prvd == 0x0) revert();
prvd = _prvd;
}
/**
* Allow the Provide platform robot to update the Provide wallet contract address.
*/
function setPrvdWallet(address _prvdWallet) onlyPrvd {
if (_prvdWallet == 0x0) revert();
prvdWallet = _prvdWallet;
}
/**
* Allow the Provide platform robot to update the payments escrow wallet contract address.
*/
function setPaymentEscrow(address _paymentEscrow) onlyPrvd {
if (_paymentEscrow == 0x0) revert();
paymentEscrow = _paymentEscrow;
}
/**
* Only allow the Provide contract owner to execute a contract function.
*/
modifier onlyOwner() {
if (msg.sender != owner) revert();
_;
}
/**
* Only allow the Provide platform robot to execute a contract function.
*/
modifier onlyPrvd() {
if (msg.sender != prvd) revert();
_;
}
}
/**
* Base contract for work orders on the Provide platform.
*/
contract ProvideWorkOrder {
using SafeMath for uint;
/** Status of the work order contract. **/
enum Status { Pending, InProgress, Completed, Paid }
/** Provide (PRVD) token. */
ProvideToken public token;
/** Provide platform robot. */
address public prvd;
/** Provide platform wallet where fees owed to Provide are remitted. */
address public prvdWallet;
/** Provide platform wallet where payment amounts owed to providers are escrowed. */
address public paymentEscrow;
/** Peer requesting and purchasing service. */
address public peer;
/** Peer providing service; compensated in PRVD tokens. */
address public provider;
/** Provide platform work order identifier (UUIDv4). */
uint128 public identifier;
/** Current status of the work order contract. **/
Status public status;
/** Total amount of Provide (PRVD) tokens payable to provider, expressed in wei. */
uint256 public amount;
/** Encoded transaction details. */
string public details;
/** Emitted when the work order has been started. */
event WorkOrderStarted(uint128 _identifier);
/** Emitted when the work order has been completed. */
event WorkOrderCompleted(uint128 _identifier, uint256 _amount, string _details);
/** Emitted when the transaction has been completed. */
event TransactionCompleted(uint128 _identifier, uint256 _paymentAmount, uint256 feeAmount, string _details);
/**
* @param _prvd Provide platform robot contract address
* @param _paymentEscrow Provide platform wallet where payment amounts owed to providers are escrowed
* @param _peer Address of party purchasing services
* @param _identifier Provide platform work order identifier (UUIDv4)
*/
function ProvideWorkOrder(
address _token,
address _prvd,
address _prvdWallet,
address _paymentEscrow,
address _peer,
uint128 _identifier
) {
if (_token == 0x0) revert();
if (_prvd == 0x0) revert();
if (_prvdWallet == 0x0) revert();
if (_paymentEscrow == 0x0) revert();
if (_peer == 0x0) revert();
token = ProvideToken(_token);
prvd = _prvd;
prvdWallet = _prvdWallet;
paymentEscrow = _paymentEscrow;
peer = _peer;
identifier = _identifier;
status = Status.Pending;
}
/**
* Set the address of the party providing service and start the work order.
* @param _provider Address of the party providing service
*/
function start(address _provider) public onlyPrvd onlyPending {
if (provider != 0x0) revert();
provider = _provider;
status = Status.InProgress;
WorkOrderStarted(identifier);
}
/**
* Complete the work order.
* @param _amount Total amount of Provide (PRVD) tokens payable to provider, expressed in wei
* @param _details Encoded transaction details
*/
function complete(uint256 _amount, string _details) public onlyProvider onlyInProgress {
amount = _amount;
details = _details;
status = Status.Completed;
WorkOrderCompleted(identifier, amount, details);
}
/**
* Complete the transaction by remitting the exact amount of PRVD tokens due.
* The service provider's payment is escrowed in the payment escrow wallet
* and the platform fee is remitted to Provide.
*
* Partial payments will be rejected.
*/
function completeTransaction() public onlyPurchaser onlyCompleted {
uint allowance = token.allowance(msg.sender, this);
if (allowance < amount) revert();
token.transferFrom(this, paymentEscrow, amount);
uint feeAmount = allowance.sub(amount);
if (feeAmount > 0) token.transferFrom(this, prvdWallet, feeAmount);
status = Status.Paid;
TransactionCompleted(identifier, amount, feeAmount, details);
}
/**
* Only allow the Provide platform robot to execute a contract function.
*/
modifier onlyPrvd() {
if (msg.sender != prvd) revert();
_;
}
/**
* Only allow the peer purchasing services to execute a contract function.
*/
modifier onlyPurchaser() {
if (msg.sender != peer) revert();
_;
}
/**
* Only allow the service provider to execute a contract function.
*/
modifier onlyProvider() {
if (msg.sender != provider) revert();
_;
}
/**
* Only allow execution of a contract function if the work order is pending.
*/
modifier onlyPending() {
if (uint(status) != uint(Status.Pending)) revert();
_;
}
/**
* Only allow execution of a contract function if the work order is started.
*/
modifier onlyInProgress() {
if (uint(status) != uint(Status.InProgress)) revert();
_;
}
/**
* Only allow execution of a contract function if the work order is complete.
*/
modifier onlyCompleted() {
if (uint(status) != uint(Status.Completed)) revert();
_;
}
}
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
return a / b;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assertTrue(bool val) internal {
assert(val);
}
function assertFalse(bool val) internal {
assert(!val);
}
}
/**
* ERC20Basic
* Simpler version of ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* Basic token.
* Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping (address => uint) balances;
/**
* Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
/**
* transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* Standard ERC20 token
*
* Implemantation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
/**
* 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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* Controller interface.
*/
contract Controller {
/**
* Called to determine if the token allows proxy payments.
*
* @param _owner The address that sent ether to the token contract
* @return True if the ether is accepted, false if it throws
*/
function proxyPayment(address _owner) payable returns(bool);
/**
* Called to determine if the controller approves a token transfer.
*
* @param _from The origin of the transfer
* @param _to The destination of the transfer
* @param _amount The amount of the transfer
* @return False if the controller does not authorize the transfer
*/
function onTransfer(address _from, address _to, uint _amount) returns(bool);
/**
* Called to notify the controller of a transfer approval.
*
* @param _owner The address that calls `approve()`
* @param _spender The spender in the `approve()` call
* @param _amount The amount in the `approve()` call
* @return False if the controller does not authorize the approval
*/
function onApprove(address _owner, address _spender, uint _amount) returns(bool);
}
/**
* Controlled.
*/
contract Controlled {
address public controller;
function Controlled() {
controller = msg.sender;
}
function changeController(address _controller) onlyController {
controller = _controller;
}
modifier onlyController {
if (msg.sender != controller) revert();
_;
}
}
/**
* A trait that allows any token owner to decrease the token supply.
*
* We add a Burned event to differentiate from normal transfers.
* However, we still try to support some legacy Ethereum ecosystem,
* as ERC-20 has not standardized on the burn event yet.
*/
contract BurnableToken is StandardToken {
address public constant BURN_ADDRESS = 0;
event Burned(address burner, uint burnedAmount);
/**
* Burn extra tokens from a balance.
*
* Keeps token balance tracking services happy by sending the burned
* amount to BURN_ADDRESS, so that it will show up as a ERC-20 transaction
* in etherscan, etc. as there is no standardized burn event yet.
*
* @param burnAmount The amount of tokens to burn
*/
function burn(uint burnAmount) {
address burner = msg.sender;
balances[burner] = balances[burner].sub(burnAmount);
totalSupply = totalSupply.sub(burnAmount);
Burned(burner, burnAmount);
Transfer(burner, BURN_ADDRESS, burnAmount);
}
}
/**
* Mintable token.
*
* Simple ERC20 Token example, with mintable token creation
*/
contract MintableToken is StandardToken, Controlled {
event Mint(address indexed to, uint value);
event MintFinished();
bool public mintingFinished = false;
uint public totalSupply = 0;
/**
* Function to mint tokens
* @param _to The address that will recieve 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, uint _amount) onlyController canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyController returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
modifier canMint() {
if (mintingFinished) revert();
_;
}
}
/**
* LimitedTransferToken
*
* LimitedTransferToken defines the generic interface and the implementation to limit token
* transferability for different events. It is intended to be used as a base class for other token
* contracts.
* LimitedTransferToken has been designed to allow for different limiting factors,
* this can be achieved by recursively calling super.transferableTokens() until the base class is
* hit. For example:
* function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
* return min256(unlockedTokens, super.transferableTokens(holder, time));
* }
* A working example is VestedToken.sol:
*/
contract LimitedTransferToken is ERC20 {
/**
* Checks whether it can transfer or otherwise throws
*/
modifier canTransfer(address _sender, uint _value) {
if (_value > transferableTokens(_sender, uint64(now))) revert();
_;
}
/**
* Checks modifier and allows transfer if tokens are not locked.
*
* @param _to The address that will recieve the tokens
* @param _value The amount of tokens to be transferred
*/
function transfer(address _to, uint _value) canTransfer(msg.sender, _value) {
super.transfer(_to, _value);
}
/**
* Checks modifier and allows transfer if tokens are not locked.
*
* @param _from The address that will send the tokens
* @param _to The address that will receive the tokens
* @param _value The amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) {
super.transferFrom(_from, _to, _value);
}
/**
* Default transferable tokens function returns all tokens for a holder (no limit).
*
* Overriding transferableTokens(address holder, uint64 time) is the way to provide the
* specific logic for limiting token transferability for a holder over time.
*
* @param holder The address of the token holder
*/
function transferableTokens(address holder, uint64 /* time */) constant public returns (uint256) {
return balanceOf(holder);
}
}
/**
* Upgrade agent interface.
*
* Upgrade agent transfers tokens to a new contract. The upgrade agent itself
* can be the token contract, or just an intermediary contract doing the heavy lifting.
*/
contract UpgradeAgent {
uint public originalSupply;
function isUpgradeAgent() public constant returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens
* to the next smart contract revision.
*
*/
contract UpgradeableToken is StandardToken {
/** Contract/actor who can set the upgrade path. */
address public upgradeController;
/** Designated upgrade agent responsible for completing the upgrade. */
UpgradeAgent public upgradeAgent;
/** Number of tokens upgraded to date. */
uint256 public totalUpgraded;
/**
* Upgrade states:
*
* - NotAllowed: the child contract has not reached a condition where the upgrade can begin
* - WaitingForAgent: token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: the agent is set, but not a single token has been upgraded yet
* - Upgrading: upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Emitted when a token holder upgrades some portion of token holdings.
*/
event Upgrade(address indexed from, address indexed to, uint256 value);
/**
* New upgrade agent has been set.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade controller.
*/
function UpgradeableToken(address _upgradeController) {
upgradeController = _upgradeController;
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
if (!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) {
revert(); // called in an invalid state
}
if (value == 0) revert(); // validate input value
balances[msg.sender] = balances[msg.sender].sub(value);
// Take tokens out from circulation
totalSupply = totalSupply.sub(value);
totalUpgraded = totalUpgraded.add(value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that can handle.
*/
function setUpgradeAgent(address agent) external {
if (!canUpgrade()) {
revert();
}
if (agent == 0x0) revert();
if (msg.sender != upgradeController) revert(); // only upgrade controller can designate the next agent
if (getUpgradeState() == UpgradeState.Upgrading) revert(); // upgrade has already started for an agent
upgradeAgent = UpgradeAgent(agent);
if (!upgradeAgent.isUpgradeAgent()) revert(); // bad interface
if (upgradeAgent.originalSupply() != totalSupply) revert(); // ensure that token supplies match in source and target
UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public constant returns(UpgradeState) {
if (!canUpgrade()) return UpgradeState.NotAllowed;
else if (address(upgradeAgent) == 0x0) return UpgradeState.WaitingForAgent;
else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade controller.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeController(address controller) public {
if (controller == 0x0) revert();
if (msg.sender != upgradeController) revert();
upgradeController = controller;
}
/**
* Child contract can override to condition enable upgrade path.
*/
function canUpgrade() public constant returns(bool) {
return true;
}
}
/**
* Vested token.
*
* Tokens that can be vested for a group of addresses.
*/
contract VestedToken is StandardToken, LimitedTransferToken {
uint256 MAX_GRANTS_PER_ADDRESS = 20;
struct TokenGrant {
address granter; // 20 bytes
uint256 value; // 32 bytes
uint64 cliff;
uint64 vesting;
uint64 start; // 3 * 8 = 24 bytes
bool revokable;
bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes?
} // total 78 bytes = 3 sstore per operation (32 per sstore)
mapping (address => TokenGrant[]) public grants;
event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId);
/**
* Grant tokens to a specified address.
*
* @param _to address The address which the tokens will be granted to.
* @param _value uint256 The amount of tokens to be granted.
* @param _start uint64 Time of the beginning of the grant.
* @param _cliff uint64 Time of the cliff period.
* @param _vesting uint64 The vesting period.
* @param _revokable bool If the grant is revokable.
* @param _burnsOnRevoke bool When true, the tokens are burned if revoked.
*/
function grantVestedTokens(
address _to,
uint256 _value,
uint64 _start,
uint64 _cliff,
uint64 _vesting,
bool _revokable,
bool _burnsOnRevoke
) public {
// Check for date inconsistencies that may cause unexpected behavior
if (_cliff < _start || _vesting < _cliff) {
revert();
}
if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) revert(); // To prevent a user being spammed and have his balance
// locked (out of gas attack when calculating vesting).
uint count = grants[_to].push(
TokenGrant(
_revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
_value,
_cliff,
_vesting,
_start,
_revokable,
_burnsOnRevoke
)
);
transfer(_to, _value);
NewTokenGrant(msg.sender, _to, _value, count - 1);
}
/**
* Revoke the grant of tokens of a specified address.
*
* @param _holder The address which will have its tokens revoked
* @param _grantId The id of the token grant
*/
function revokeTokenGrant(address _holder, uint _grantId) public {
TokenGrant storage grant = grants[_holder][_grantId];
if (!grant.revokable) { // check if grant is revokable
revert();
}
if (grant.granter != msg.sender) { // only granter to revoke the grant
revert();
}
address receiver = grant.burnsOnRevoke ? 0x0 : msg.sender;
uint256 nonVested = nonVestedTokens(grant, uint64(now));
// remove grant from array
delete grants[_holder][_grantId];
grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)];
grants[_holder].length -= 1;
balances[receiver] = balances[receiver].add(nonVested);
balances[_holder] = balances[_holder].sub(nonVested);
Transfer(_holder, receiver, nonVested);
}
/**
* Calculate the total amount of transferable tokens of a holder at a given time.
*
* @param holder address The address of the holder
* @param time uint64 The specific time
* @return An uint representing a holder's total amount of transferable tokens
*/
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
uint256 grantIndex = tokenGrantsCount(holder);
if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants
// Iterate through all the grants the holder has, and add all non-vested tokens
uint256 nonVested = 0;
for (uint256 i = 0; i < grantIndex; i++) {
nonVested = nonVested.add(nonVestedTokens(grants[holder][i], time));
}
// Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
uint256 vestedTransferable = balanceOf(holder).sub(nonVested);
// Return the minimum of how many vested can transfer and other value
// in case there are other limiting transferability factors (default is balanceOf)
return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time));
}
/**
* Check the amount of grants that an address has.
*
* @param _holder The holder of the grants
* @return A uint representing the total amount of grants
*/
function tokenGrantsCount(address _holder) constant returns (uint index) {
return grants[_holder].length;
}
/**
* Calculate amount of vested tokens at a specific time.
*
* @param tokens uint256 The amount of tokens granted
* @param time uint64 The time to be checked
* @param start uint64 A time representing the beginning of the grant
* @param cliff uint64 The cliff period
* @param vesting uint64 The vesting period
* @return An uint representing the amount of vested tokens from a specific grant
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |(grants[_holder] == address(0)) return 0;
* | . |
* +===+===========+---------+----------> time
* Start Clift Vesting
*/
function calculateVestedTokens(uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) {
// Shortcuts for before cliff and after vesting cases.
if (time < cliff) return 0;
if (time >= vesting) return tokens;
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can use just calculate a value
// in the vesting rect (as shown in above's figure)
uint vestedTokens = tokens.mul(time.sub(start)).div(vesting.sub(start));
return vestedTokens;
}
/**
* Get all information about a specifc grant.
*
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
* @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
* revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
*/
function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
TokenGrant storage grant = grants[_holder][_grantId];
granter = grant.granter;
value = grant.value;
start = grant.start;
cliff = grant.cliff;
vesting = grant.vesting;
revokable = grant.revokable;
burnsOnRevoke = grant.burnsOnRevoke;
vested = vestedTokens(grant, uint64(now));
}
/**
* Get the amount of vested tokens at a specific time.
*
* @param grant TokenGrant The grant to be checked.
* @param time The time to be checked
* @return An uint representing the amount of vested tokens of a specific grant at a specific time.
*/
function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return calculateVestedTokens(
grant.value,
uint256(time),
uint256(grant.start),
uint256(grant.cliff),
uint256(grant.vesting)
);
}
/**
* Calculate the amount of non vested tokens at a specific time.
*
* @param grant TokenGrant The grant to be checked.
* @param time uint64 The time to be checked
* @return An uint representing the amount of non vested tokens of a specifc grant on the
* passed time frame.
*/
function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return grant.value.sub(vestedTokens(grant, time));
}
/**
* Calculate the date when the holder can trasfer all its tokens
*
* @param holder address The address of the holder
* @return An uint representing the date of the last transferable tokens.
*/
function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
date = uint64(now);
uint256 grantIndex = grants[holder].length;
for (uint256 i = 0; i < grantIndex; i++) {
date = SafeMath.max64(grants[holder][i].vesting, date);
}
}
}
/**
* Provide (PRVD) token contract.
*/
contract ProvideToken is BurnableToken, MintableToken, VestedToken, UpgradeableToken {
string public constant name = 'Provide';
string public constant symbol = 'PRVD';
uint public constant decimals = 8;
function ProvideToken() UpgradeableToken(msg.sender) { }
function() public payable {
if (isContract(controller)) {
if (!Controller(controller).proxyPayment.value(msg.value)(msg.sender)) revert();
} else {
revert();
}
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
}
|
Calculate amount of vested tokens at a specific time. tokens uint256 The amount of tokens granted time uint64 The time to be checked start uint64 A time representing the beginning of the grant cliff uint64 The cliff period vesting uint64 The vesting period return An uint representing the amount of vested tokens from a specific grant transferableTokens | _/-------- vestedTokens rect | _/ | _/ | _/ | _/ | / | .| | . | | . | | . | | . |(grants[_holder] == address(0)) return 0; | . | +===+===========+---------+----------> time Start Clift Vesting/ Shortcuts for before cliff and after vesting cases. Interpolate all vested tokens. As before cliff the shortcut returns 0, we can use just calculate a value in the vesting rect (as shown in above's figure)
|
function calculateVestedTokens(uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) {
if (time < cliff) return 0;
if (time >= vesting) return tokens;
uint vestedTokens = tokens.mul(time.sub(start)).div(vesting.sub(start));
return vestedTokens;
}
| 7,215,239 |
// 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;
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 {
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 {}
}
// 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 "../ERC721.sol";
import "../../../utils/Context.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);
}
}
// SPDX-License-Identifier: MIT
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
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;
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;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev 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;
/**
* @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);
}
// 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 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;
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];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol';
import './ERC721Ownable.sol';
import './ERC721WithRoyalties.sol';
/// @title ERC721Full
/// @dev This contains all the different overrides needed on
/// ERC721 / Enumerable / URIStorage / Royalties
/// @author Simon Fremaux (@dievardump)
abstract contract ERC721Full is
ERC721Ownable,
ERC721Burnable,
ERC721WithRoyalties
{
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, ERC721, ERC721WithRoyalties)
returns (bool)
{
return
// either ERC721Enumerable
ERC721Enumerable.supportsInterface(interfaceId) ||
// or Royalties
ERC721WithRoyalties.supportsInterface(interfaceId);
}
/// @inheritdoc ERC721
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/// @inheritdoc ERC721Ownable
function isApprovedForAll(address owner_, address operator)
public
view
override(ERC721, ERC721Ownable)
returns (bool)
{
return ERC721Ownable.isApprovedForAll(owner_, operator);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '../OpenSea/BaseOpenSea.sol';
/// @title ERC721Ownable
/// @author Simon Fremaux (@dievardump)
contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea {
/// @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)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_
) ERC721(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_);
}
}
/// @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 ERC721
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
// allows gas less trading on OpenSea
if (isOwnersOpenSeaProxy(owner, operator)) {
return true;
}
return super.isApprovedForAll(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 onlyOwner {
_setContractURI(contractURI_);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '../Royalties/ERC2981/IERC2981Royalties.sol';
import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol';
/// @dev This is a contract used for royalties on various platforms
/// @author Simon Fremaux (@dievardump)
contract ERC721WithRoyalties is IERC2981Royalties, IRaribleSecondarySales {
function supportsInterface(bytes4 interfaceId)
public
view
virtual
returns (bool)
{
return
interfaceId == type(IERC2981Royalties).interfaceId ||
interfaceId == type(IRaribleSecondarySales).interfaceId;
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256)
public
view
virtual
override
returns (address _receiver, uint256 _royaltyAmount)
{
_receiver = address(this);
_royaltyAmount = 0;
}
/// @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) = royaltyInfo(tokenId, 10000);
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) = royaltyInfo(tokenId, 10000);
if (amount != 0) {
fees = new uint256[](1);
fees[0] = amount;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's support
contract BaseOpenSea {
string private _contractURI;
ProxyRegistry 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 Helper for OpenSea gas-less trading
/// @dev Allows to check if `operator` is owner's OpenSea proxy
/// @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)
{
ProxyRegistry proxyRegistry = _proxyRegistry;
return
// we have a proxy registry address
address(proxyRegistry) != address(0) &&
// current operator is owner's proxy address
address(proxyRegistry.proxies(owner)) == operator;
}
/// @dev Internal function to set the _contractURI
/// @param contractURI_ the new contract uri
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal {
_proxyRegistry = ProxyRegistry(proxyRegistryAddress);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @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.0;
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.0;
// small library to randomize using (min, max, seed, offsetBit etc...)
library Randomize {
struct Random {
uint256 seed;
uint256 offsetBit;
}
/// @notice get an random number between (min and max) using seed and offseting bits
/// this function assumes that max is never bigger than 0xffffff (hex color with opacity included)
/// @dev this function is simply used to get random number using a seed.
/// if does bitshifting operations to try to reuse the same seed as much as possible.
/// should be enough for anyth
/// @param random the randomizer
/// @param min the minimum
/// @param max the maximum
/// @return result the resulting pseudo random number
function next(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256 result) {
uint256 newSeed = random.seed;
uint256 newOffset = random.offsetBit + 3;
uint256 maxOffset = 4;
uint256 mask = 0xf;
if (max > 0xfffff) {
mask = 0xffffff;
maxOffset = 24;
} else if (max > 0xffff) {
mask = 0xfffff;
maxOffset = 20;
} else if (max > 0xfff) {
mask = 0xffff;
maxOffset = 16;
} else if (max > 0xff) {
mask = 0xfff;
maxOffset = 12;
} else if (max > 0xf) {
mask = 0xff;
maxOffset = 8;
}
// if offsetBit is too high to get the max number
// just get new seed and restart offset to 0
if (newOffset > (256 - maxOffset)) {
newOffset = 0;
newSeed = uint256(keccak256(abi.encode(newSeed)));
}
uint256 offseted = (newSeed >> newOffset);
uint256 part = offseted & mask;
result = min + (part % (max - min));
random.seed = newSeed;
random.offsetBit = newOffset;
}
function nextInt(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (int256 result) {
result = int256(Randomize.next(random, min, max));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title IVariety interface
/// @author Simon Fremaux (@dievardump)
interface IVariety is IERC721 {
/// @notice mint `seeds.length` token(s) to `to` using `seeds`
/// @param to token recipient
/// @param seeds each token seed
function plant(address to, bytes32[] memory seeds)
external
returns (uint256);
/// @notice this function returns the seed associated to a tokenId
/// @param tokenId to get the seed of
function getTokenSeed(uint256 tokenId) external view returns (bytes32);
/// @notice This function allows an owner to ask for a seed update
/// this can be needed because although I test the contract as much as possible,
/// it might be possible that one token does not render because the seed creates
/// error or even "out of gas" computation. That's why this would allow an owner
/// in such case, to request for a seed change that will then be triggered by Sower
/// @param tokenId id to regenerate seed for
function requestSeedChange(uint256 tokenId) external;
/// @notice This function allows Sower to answer to a seed change request
/// in the event where a seed would produce errors of rendering
/// 1) this function can only be called by Sower if the token owner
/// asked for a new seed
/// 2) this function will only be called if there is a rendering error
/// or, Vitalik Buterin forbid, a duplicate
/// @param tokenId id to regenerate seed for
function changeSeedAfterRequest(uint256 tokenId) external;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/Strings.sol';
import '../Variety.sol';
import '../../Randomize.sol';
/// @title Genesis
/// @author Simon Fremaux (@dievardump)
contract Genesis is Variety {
using Strings for uint256;
using Strings for uint16;
using Strings for uint8;
using Randomize for Randomize.Random;
enum ColorTypes {
AUTO,
BLACK_WHITE,
FULL
}
struct Grid {
uint8 cols;
uint8 rows;
uint16 cellSize;
uint16 offset;
uint16 shapes;
uint16 minContentSize;
uint16 maxContentSize;
bool shadowed;
bool degen;
bool dark;
bool full;
ColorTypes colorType;
uint256 tokenId;
uint256 baseSeed;
string[5] palette;
}
struct CellData {
uint16 x;
uint16 y;
uint16 cx;
uint16 cy;
uint16 index;
}
/// @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 sower_ Sower contract
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address sower_
) Variety(name_, symbol_, contractURI_, openseaProxyRegistry_, sower_) {}
/// @dev internal function to get the name. Should be overrode by actual Variety contract
/// @param tokenId the token to get the name of
/// @return seedlingName the token name
function _getName(uint256 tokenId)
internal
view
override
returns (string memory seedlingName)
{
seedlingName = names[tokenId];
if (bytes(seedlingName).length == 0) {
seedlingName = string(
abi.encodePacked('Genesis.sol #', tokenId.toString())
);
}
}
/// @dev Rendering function; should be overrode by the actual seedling contract
/// @param tokenId the tokenId
/// @param seed the seed
/// @return the json
function _render(uint256 tokenId, bytes32 seed)
internal
view
virtual
override
returns (string memory)
{
Randomize.Random memory random = Randomize.Random({
seed: uint256(seed),
offsetBit: 0
});
uint256 result = random.next(0, 100);
Grid memory grid = Grid({
cols: 8,
rows: 8,
cellSize: 140,
offset: 40,
shapes: 0,
minContentSize: 0,
maxContentSize: 0,
colorType: result <= 80 // auto 80%, 10% B&W, 10% FULL Color
? ColorTypes.AUTO
: (result <= 90 ? ColorTypes.BLACK_WHITE : ColorTypes.FULL),
dark: random.next(0, 100) < 10, // 10% dark mode
degen: random.next(0, 100) < 10, // 10% degen (grid offseted)
shadowed: random.next(0, 100) < 3, // 3% with shadow
full: random.next(0, 100) < 1, // 1% full genesis
palette: _getPalette(random),
tokenId: tokenId,
baseSeed: uint256(seed)
});
// shadowed + full black white is not pleasing to the eye with the wrong first color
if (grid.shadowed && grid.colorType == ColorTypes.BLACK_WHITE) {
grid.palette[0] = '#99B898';
}
result = random.next(0, 16);
if (result < 1) {
grid.cols = 3;
grid.rows = 3;
grid.cellSize = 146;
grid.offset = 381;
} else if (result < 3) {
grid.cols = 4;
grid.rows = 4;
grid.offset = 320;
} else if (result < 7) {
grid.cols = 6;
grid.rows = 6;
grid.offset = 180;
} else if (result < 11) {
grid.cols = 7;
grid.rows = 7;
grid.cellSize = 146;
grid.offset = 89;
}
grid.minContentSize = (grid.cellSize * 2) / 10;
grid.maxContentSize = (grid.cellSize * 6) / 10;
bytes memory svg = abi.encodePacked(
'data:application/json;utf8,{"name":"',
_getName(tokenId),
'","image":"data:image/svg+xml;utf8,',
"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 1200 1200' width='1200' height='1200'>",
_renderGrid(grid, random),
_renderCells(grid, random)
);
svg = abi.encodePacked(
svg,
"<text style='font: bold 11px sans-serif;' text-anchor='end' x='",
(1200 - grid.offset).toString(),
"' y='",
(1220 - grid.offset).toString(),
"'",
grid.dark ? " fill='#fff'" : '',
'>#',
tokenId.toString(),
'</text>',
'</svg>"'
);
svg = abi.encodePacked(
svg,
',"license":"Full ownership with unlimited commercial rights.","creator":"@dievardump"',
',"description":"Genesis: A seed, some love, that',
"'s",
'all it takes.\\n\\nGenesis is the first of the [sol]Seedlings, an experiment of art and collectible NFTs 100% generated with Solidity.\\nby @dievardump\\n\\nLicense: Full ownership with unlimited commercial rights.\\n\\nMore info at https://solSeedlings.art"'
);
return
string(
abi.encodePacked(
svg,
',"properties":{"Colors":"',
grid.colorType == ColorTypes.AUTO
? 'Auto'
: (
grid.colorType == ColorTypes.BLACK_WHITE
? 'Black & White'
: 'Full color'
),
'","Grid":"',
grid.degen ? 'Degen' : 'Normal',
'","Mode":"',
grid.dark ? 'Dark' : 'Light',
'","Rendering":"',
grid.shadowed ? 'Ghost' : 'Normal',
'","Size":"',
abi.encodePacked(
grid.cols.toString(),
'*',
grid.rows.toString()
),
'"',
grid.shapes == grid.rows * grid.cols
? ',"Bonus":"Full Board"'
: '',
'}}'
)
);
}
function _renderGrid(Grid memory grid, Randomize.Random memory random)
internal
pure
returns (bytes memory svg)
{
uint256 offsetMore = grid.degen ? grid.cellSize / 2 : 0;
svg = abi.encodePacked(
"<defs><pattern id='genesis-grid-",
grid.baseSeed.toString(),
"' x='",
(grid.offset + offsetMore).toString(),
"' y='",
(grid.offset + offsetMore).toString(),
"' width='",
grid.cellSize.toString(),
"' height='",
grid.cellSize.toString(),
"' patternUnits='userSpaceOnUse'>"
);
svg = abi.encodePacked(
svg,
"<path d='M ",
grid.cellSize.toString(),
' 0 L 0 0 0 ',
grid.cellSize.toString(),
"' fill='none' stroke='",
grid.dark ? '#fff' : '#000',
"' stroke-width='4'/></pattern>"
);
if (!grid.dark) {
svg = abi.encodePacked(
svg,
"<linearGradient id='genesis-gradient-",
grid.baseSeed.toString(),
"' gradientTransform='rotate(",
random.next(0, 360).toString(),
")'><stop offset='0%' stop-color='",
_randomHSLA(random.next(10, 45), random),
"'/><stop offset='100%' stop-color='",
_randomHSLA(random.next(10, 45), random),
"' /></linearGradient>"
);
}
svg = abi.encodePacked(
svg,
"</defs><rect width='100%' height='100%' fill='#fff' />",
grid.dark
? "<rect width='100%' height='100%' fill='#000' />"
: string(
abi.encodePacked(
"<rect width='100%' height='100%' fill='url(#genesis-gradient-",
grid.baseSeed.toString(),
")' />"
)
),
"<rect x='",
grid.offset.toString(),
"' y='",
grid.offset.toString(),
"' width='",
(1200 - grid.offset * 2).toString(),
"' height='",
(1200 - grid.offset * 2).toString(),
"' fill='url(#genesis-grid-",
grid.baseSeed.toString(),
")' stroke='",
grid.dark ? '#fff' : '#000',
"' stroke-width='4' />"
);
}
function _getCellData(
uint16 x,
uint16 y,
Grid memory grid
) internal pure returns (CellData memory) {
uint16 left = x * grid.cellSize;
uint16 top = y * grid.cellSize;
return
CellData({
index: y * grid.cols + x,
x: left,
y: top,
cx: left + grid.cellSize / 2,
cy: top + grid.cellSize / 2
});
}
function _renderCells(Grid memory grid, Randomize.Random memory random)
internal
pure
returns (bytes memory)
{
uint256 result;
CellData memory cellData;
bytes memory cells = abi.encodePacked(
'<g ',
grid.shadowed
? string(
abi.encodePacked(
"style='filter: drop-shadow(16px 16px 20px ",
grid.palette[0],
") invert(80%);'"
)
)
: '',
" stroke-width='4' stroke-linecap='round' transform='translate(",
grid.offset.toString(),
',',
grid.offset.toString(),
")'>"
);
for (uint16 y; y < grid.rows; y++) {
for (uint16 x; x < grid.cols; x++) {
cellData = _getCellData(x, y, grid);
result = random.next(0, grid.full ? 10 : 16);
if (result <= 1) {
// 0 & 1
cells = abi.encodePacked(
cells,
_getCircle(
result != 0,
random.next(
grid.minContentSize / 2,
grid.maxContentSize / 2
),
cellData,
grid,
random
)
);
grid.shapes++;
} else if (result <= 3) {
// 2 & 3
uint256 size = random.next(
grid.minContentSize,
grid.maxContentSize
);
cells = abi.encodePacked(
cells,
_getSquare(result != 5, size, cellData, grid, random)
);
grid.shapes++;
} else if (result == 4) {
// 4
cells = abi.encodePacked(
cells,
_getSquare(
true,
grid.minContentSize,
cellData,
grid,
random
),
_getSquare(
false,
grid.maxContentSize,
cellData,
grid,
random
)
);
grid.shapes++;
} else if (result == 5) {
uint256 half = grid.maxContentSize / 2;
bytes memory color = _getColor(false, random, grid);
cells = abi.encodePacked(
cells,
_getLine(
cellData.cx - half,
cellData.cy - half,
cellData.cx + half,
cellData.cy + half,
color,
false
)
);
grid.shapes++;
} else if (result <= 8) {
uint256 half = result >= 7
? grid.minContentSize / 2
: grid.maxContentSize / 2;
bool strong = result >= 7;
bytes memory color = _getColor(false, random, grid);
bytes memory square;
if (result == 8) {
square = _getSquare(
false,
grid.maxContentSize,
cellData,
grid,
random
);
}
cells = abi.encodePacked(
cells,
square,
_getLine(
cellData.cx - half,
cellData.cy - half,
cellData.cx + half,
cellData.cy + half,
color,
strong
),
_getLine(
cellData.cx + half,
cellData.cy - half,
cellData.cx - half,
cellData.cy + half,
color,
strong
)
);
grid.shapes++;
} else if (result < 10) {
cells = abi.encodePacked(
cells,
_getCircle(
result == 8,
grid.maxContentSize / 2,
cellData,
grid,
random
),
_getCircle(
true,
grid.minContentSize / 2,
cellData,
grid,
random
)
);
grid.shapes++;
}
}
}
return abi.encodePacked(cells, '</g>');
}
function _getPalette(Randomize.Random memory random)
internal
pure
returns (string[5] memory)
{
uint256 randPalette = random.next(0, 6);
if (randPalette == 0) {
return ['#F8B195', '#F67280', '#C06C84', '#6C5B7B', '#355C7D'];
} else if (randPalette == 1) {
return ['#173F5F', '#20639B', '#3CAEA3', '#F6D55C', '#ED553B'];
} else if (randPalette == 2) {
return ['#A7226E', '#EC2049', '#F26B38', '#F7DB4F', '#2F9599'];
} else if (randPalette == 3) {
return ['#99B898', '#FECEAB', '#FF847C', '#E84A5F', '#2A363B'];
} else if (randPalette == 4) {
return ['#FFADAD', '#FDFFB6', '#9BF6FF', '#BDB2FF', '#FFC6FF'];
} else {
return ['#EA698B', '#C05299', '#973AA8', '#6D23B6', '#571089'];
}
}
function _getColor(
bool fill,
Randomize.Random memory random,
Grid memory grid
) internal pure returns (bytes memory) {
string memory color = grid.dark ? '#fff' : '#000';
if (
// if not full black & white
ColorTypes.BLACK_WHITE != grid.colorType &&
// and if either full color OR 1 out of 5, colorize
(ColorTypes.FULL == grid.colorType || random.next(0, 5) < 1)
) {
color = grid.palette[random.next(0, grid.palette.length)];
}
if (!fill) {
return abi.encodePacked(" stroke='", color, "' fill='none' ");
}
return abi.encodePacked(" fill='", color, "' stroke='none' ");
}
function _randomHSLA(uint256 maxOpacity, Randomize.Random memory random)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
'hsla(',
random.next(0, 255).toString(),
',',
random.next(0, 100).toString(),
'%,',
random.next(40, 100).toString(),
'%,0.',
maxOpacity < 10 ? '0' : '',
maxOpacity.toString(),
')'
);
}
function _getCircle(
bool fill,
uint256 size,
CellData memory cellData,
Grid memory grid,
Randomize.Random memory random
) internal pure returns (bytes memory) {
return
abi.encodePacked(
"<circle cx='",
cellData.cx.toString(),
"' cy='",
cellData.cy.toString(),
"' r='",
size.toString(),
"'",
_getColor(fill, random, grid),
'/>'
);
}
function _getSquare(
bool fill,
uint256 size,
CellData memory cellData,
Grid memory grid,
Randomize.Random memory random
) internal pure returns (bytes memory) {
return
abi.encodePacked(
"<rect x='",
(cellData.cx - size / 2).toString(),
"' y='",
(cellData.cy - size / 2).toString(),
"' width='",
size.toString(),
"' height='",
size.toString(),
"'",
_getColor(fill, random, grid),
'/>'
);
}
function _getLine(
uint256 x0,
uint256 y0,
uint256 x1,
uint256 y1,
bytes memory color,
bool strong
) internal pure returns (bytes memory) {
return
abi.encodePacked(
"<path d='M ",
x0.toString(),
' ',
y0.toString(),
' L ',
x1.toString(),
' ',
y1.toString(),
"'",
color,
'',
strong ? "stroke-width='8'" : '',
'/>'
);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//////************@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@/////*******************@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///***********************@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**************************@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**********/**************/*@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///////****/****************//@@@@@
// @@@*********@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(///////////*****************//@@@@@@
// @@@**************//////@@@@@@@@@@@@@@@@@@@((////////////***************//@@@@@@@
// @@@*********************////@@@@@@@@@@@@@((///////////////************//@@@@@@@@
// @@@@//**************//***//////@@@@@@@@@@(///////////////////*******//@@@@@@@@@@
// @@@@@/*****************////////((@@@@@@@((///((////////////////***//@@@@@@@@@@@@
// @@@@@@//*************////////////((@@@@@((//((////////////////////@@@@@@@@@@@@@@
// @@@@@@@//**********///////////////((@@@@((((//////////////////@@@@@@@@@@@@@@@@@@
// @@@@@@@@///******//////////////((//((@@@(((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@//*///////////////////(//((@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@////////////////////(((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@/((((/////////////((((/@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@((((((((@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@###(((((((((((((((((((((((((###@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@####################################@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@#############################################@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import './IVariety.sol';
import '../NFT/ERC721Helpers/ERC721Full.sol';
/// @title Variety Contract
/// @author Simon Fremaux (@dievardump)
contract Variety is IVariety, ERC721Full {
event SeedChangeRequest(uint256 indexed tokenId, address indexed operator);
// seedlings Sower
address public sower;
// last tokenId
uint256 public lastTokenId;
// each token seed
mapping(uint256 => bytes32) internal tokenSeed;
// names
mapping(uint256 => string) public names;
// useNames
mapping(bytes32 => bool) public usedNames;
// tokenIds with a request for seeds change
mapping(uint256 => bool) internal seedChangeRequests;
modifier onlySower() {
require(msg.sender == sower, 'Not Sower.');
_;
}
/// @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 sower_ Sower contract
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address sower_
) ERC721Ownable(name_, symbol_, contractURI_, openseaProxyRegistry_) {
sower = sower_;
}
/// @notice mint `seeds.length` token(s) to `to` using `seeds`
/// @param to token recipient
/// @param seeds each token seed
function plant(address to, bytes32[] memory seeds)
external
override
onlySower
returns (uint256)
{
uint256 tokenId = lastTokenId;
for (uint256 i; i < seeds.length; i++) {
tokenId++;
_safeMint(to, tokenId);
tokenSeed[tokenId] = seeds[i];
}
lastTokenId = tokenId;
return tokenId;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Full, IERC165)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/// @notice tokenURI override that returns a data:json application
/// @inheritdoc ERC721
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
return _render(tokenId, tokenSeed[tokenId]);
}
/// @notice ERC2981 support - 4% royalties sent to Sower
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256 value)
public
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = sower;
royaltyAmount = (value * 400) / 10000;
}
/// @inheritdoc IVariety
function getTokenSeed(uint256 tokenId)
external
view
override
returns (bytes32)
{
require(_exists(tokenId), 'TokenSeed query for nonexistent token');
return tokenSeed[tokenId];
}
/// @inheritdoc IVariety
function requestSeedChange(uint256 tokenId) external override {
require(ownerOf(tokenId) == msg.sender, 'Not token owner.');
seedChangeRequests[tokenId] = true;
emit SeedChangeRequest(tokenId, msg.sender);
}
/// @inheritdoc IVariety
function changeSeedAfterRequest(uint256 tokenId)
external
override
onlySower
{
require(seedChangeRequests[tokenId] == true, 'No request for token.');
seedChangeRequests[tokenId] = false;
tokenSeed[tokenId] = keccak256(
abi.encode(
tokenSeed[tokenId],
block.timestamp,
block.difficulty,
blockhash(block.number - 1)
)
);
}
/// @notice Function allowing an owner to set the seedling name
/// User needs to be extra careful. Some characters might completly break the token.
/// Since the metadata are generated in the contract.
/// if this ever happens, you can simply reset the name to nothing or for something else
/// @dev sender must be tokenId owner
/// @param tokenId the token to name
/// @param seedlingName the name
function setName(uint256 tokenId, string memory seedlingName) external {
require(ownerOf(tokenId) == msg.sender, 'Not token owner.');
bytes32 byteName = keccak256(abi.encodePacked(seedlingName));
// if the name is not empty, verify it is not used
if (bytes(seedlingName).length > 0) {
require(usedNames[byteName] == false, 'Name already used');
usedNames[byteName] = true;
}
// if it already has a name, mark all name as unused
string memory oldName = names[tokenId];
if (bytes(oldName).length > 0) {
byteName = keccak256(abi.encodePacked(oldName));
usedNames[byteName] = false;
}
names[tokenId] = seedlingName;
}
/// @notice function to get a token name
/// @dev token must exist
/// @param tokenId the token to get the name of
/// @return the token name
function getName(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), 'Unknown token');
return _getName(tokenId);
}
/// @dev internal function to get the name. Should be overrode by actual Variety contract
/// @param tokenId the token to get the name of
/// @return the token name
function _getName(uint256 tokenId)
internal
view
virtual
returns (string memory)
{
return bytes(names[tokenId]).length > 0 ? names[tokenId] : 'Variety';
}
/// @notice Function allowing to check the rendering for a given seed
/// This allows to know what a seed would render without minting
/// @param seed the seed to render
/// @return the json
function renderSeed(bytes32 seed) public view returns (string memory) {
return _render(0, seed);
}
/// @dev Rendering function; should be overrode by the actual seedling contract
/// @param tokenId the tokenId
/// @param seed the seed
/// @return the json
function _render(uint256 tokenId, bytes32 seed)
internal
view
virtual
returns (string memory)
{
seed;
return
string(
abi.encodePacked(
'data:application/json;utf8,{"name":"',
_getName(tokenId),
'"}'
)
);
}
}
|
IVariety interface Simon Fremaux (@dievardump)
|
interface IVariety is IERC721 {
function plant(address to, bytes32[] memory seeds)
external
returns (uint256);
function getTokenSeed(uint256 tokenId) external view returns (bytes32);
function requestSeedChange(uint256 tokenId) external;
function changeSeedAfterRequest(uint256 tokenId) external;
pragma solidity ^0.8.0;
}
| 9,937,778 |
./full_match/5/0xd752E6bc0ea3cC7c8f0272A2504A0424ABD96734/sources/contracts/DataSharing.sol
|
Fungsi untuk mengunggah data pasien ke IPFS
|
function uploadPatientData(string memory ipfsHash) public onlyHospital {
patients[msg.sender].ipfsHash = ipfsHash;
patients[msg.sender].hospital = msg.sender;
}
| 11,621,129 |
./partial_match/1/0x1ab8Ee0cbC2D2A2F0E09a094358f3b0aAc275268/sources/Etherland.sol
|
Allow any NFT admin to set public prices for record rights _indexedRecordOffers Array of indexed public ELAND prices of record rights return boolean indicating operation success/failure/
|
function setRecordRightsOffers(uint[] memory _indexedRecordOffers) public isNftAdmin returns (bool) {
recordRightsOffers = _indexedRecordOffers;
return true;
}
| 3,662,937 |
// 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/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/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/Counters.sol)
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
// 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/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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 Message, created from `s`. 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(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @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
// 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
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract FuDaoVerseDAN is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
using ECDSA for bytes32;
//NFT params
string public baseURI;
bool public revealed;
string public notRevealedUri;
IERC721 public OG;
//sale stages:
//stage 0: init(no minting)
//stage 1: free-mint
//stage 2: pre-sale, OGs are included in here
//stage 2.5: whitelisted can mint an extra 2, increase presaleMintMax to 4
//stage 3: public sale
Counters.Counter public tokenSupply;
uint8 public stage = 0;
mapping(uint256 => bool) public isOGMinted;
mapping(uint256 => uint8) public OGWhitelistMintCount;
uint256 public VIP_PASSES = 888;
uint256 public presaleSalePrice = 0.077 ether;
uint256 public presaleSupply = 6666;
uint256 public presaleMintMax = 2;
mapping(address => uint8) public presaleMintCount;
mapping(address => uint8) public vipMintCount; // For Whitelist Sale
mapping(address => uint256) public publicMintCount;
//public sale (stage=3)
uint256 public publicSalePrice = 0.088 ether;
uint256 public publicMintMax = 2;
uint256 public totalSaleSupply = 8888;
//others
bool public paused = false;
//sale holders
address[2] public fundRecipients = [
0xaDDfdc72494E29A131B1d4d6668184840f1Fc30C,
0xcD7BCAc7Ee5c18d8cC1374B62F09cf67e6432a08
];
uint256[] public receivePercentagePt = [7000]; //distribution in basis points
// Off-chain whitelist
address private signerAddress;
mapping(bytes => bool) private _nonceUsed;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
address _newOwner,
address _signerAddress,
address ogCollection
) ERC721(_name, _symbol) {
setNotRevealedURI(_initBaseURI);
signerAddress = _signerAddress;
transferOwnership(_newOwner);
OG = IERC721(ogCollection);
}
event VIPMint(address indexed to, uint256 tokenId);
event WhitelistMint(address indexed to, uint256 tokenId);
event PublicMint(address indexed to, uint256 mintAmount);
event DevMint(uint256 count);
event Airdrop(address indexed to, uint256 tokenId);
/**
* @notice Performs respective minting condition checks depending on stage of minting
* @param tokenIds tokenIds of VIP Pass
* @dev Stage 1: OG Mints, Free Claim for OG Pass Holders
* @dev Each Pass can only be used once to claim
* @dev Minter must be owner of OG pass to claim
*/
function vipMint(uint256[] memory tokenIds) public {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage > 0, "FuDaoVerseDAN: Minting has not started");
for (uint256 i; i < tokenIds.length; i++) {
require(
OG.ownerOf(tokenIds[i]) == msg.sender,
"FuDaoVerseDAN: Claimant is not the owner!"
);
require(
!isOGMinted[tokenIds[i]],
"FuDaoVerseDAN: OG Token has already been used!"
);
_vipMint(tokenIds[i]);
}
}
function _vipMint(uint256 tokenId) internal {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
isOGMinted[tokenId] = true;
VIP_PASSES--;
emit VIPMint(msg.sender, tokenSupply.current());
}
/**
* @notice VIP Whitelist Mint. VIPs are automatically whitelisted and can use their Mint pass to mint
* @param _mintAmount Amount minted for vipWhitelistMint
* @dev Stage 2: Presale Mints, VIP Automatically whitelisted
* @dev 2 VIP Whitelist Mints at stage 2, another 2 VIP Whitelist Mints at stage 2.5
* @dev Minter must hold an OG pass to VIP Whitelist Mint
*/
function vipWhitelistMint(uint8 _mintAmount) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 2, "FuDaoVerseDAN: Private Sale Closed!");
require(
msg.value == _mintAmount * presaleSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
tokenSupply.current() + _mintAmount <= presaleSupply,
"FuDaoVerseDAN: Max Supply for Presale Mint Reached!"
);
require(
OG.balanceOf(msg.sender) > 0,
"FuDaoVerseDAN: Claimant does not own a mint pass"
);
require(
presaleMintCount[msg.sender] + _mintAmount <= presaleMintMax,
"FuDaoVerseDAN: Claimant has exceeded VIP Whitelist Mint Max!"
);
presaleMintCount[msg.sender] += _mintAmount;
for (uint8 i; i < _mintAmount; i++) {
_vipWhitelistMint();
}
}
function _vipWhitelistMint() internal {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit VIPMint(msg.sender, tokenSupply.current());
}
/**
* @notice Performs respective minting condition checks depending on stage of minting
* @param _mintAmount Amount that is minted
* @param nonce Random bytes32 nonce
* @param signature Signature generated off-chain
* @dev Stage 1: OG Mints, Free Claim for OG Pass Holders
* @dev Each Pass can only be used once to claim
*/
function whitelistMint(
uint8 _mintAmount,
bytes memory signature,
bytes memory nonce
) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 2, "FuDaoVerseDAN: Private Sale Closed!");
require(!_nonceUsed[nonce], "FuDaoVerseDAN: Nonce already used");
_nonceUsed[nonce] = true;
require(
whitelistSigned(msg.sender, nonce, signature),
"FuDaoVerseDAN: Invalid signature!"
);
require(
tokenSupply.current() + _mintAmount <= presaleSupply,
"FuDaoVerseDAN: Max Supply for Presale Mint Reached!"
);
require(
msg.value == _mintAmount * presaleSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
presaleMintCount[msg.sender] + _mintAmount <= presaleMintMax,
"FuDaoVerseDAN: Wallet has already minted Max Amount for Presale!"
);
presaleMintCount[msg.sender] += _mintAmount;
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit WhitelistMint(msg.sender, tokenSupply.current());
}
}
/**
* @notice Public Mint
* @param _mintAmount Amount that is minted
* @dev Stage 3: Public Mint
*/
function publicMint(uint8 _mintAmount) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 3, "FuDaoVerseDAN: Public Sale Closed!");
require(
msg.value == _mintAmount * publicSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
tokenSupply.current() + _mintAmount <= totalSaleSupply - VIP_PASSES,
"FuDaoVerseDAN: Max Supply for Public Mint Reached!"
);
require(
publicMintCount[msg.sender] + _mintAmount <= publicMintMax,
"FuDaoVerseDAN: Wallet has already minted Max Amount for Public!"
);
publicMintCount[msg.sender] += _mintAmount; // FIX: Gas Optimization
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit PublicMint(msg.sender, tokenSupply.current());
}
}
/**
* @dev Mints NFTS to the owner's wallet
* @param _mintAmount Amount to mint
*/
function devMint(uint8 _mintAmount) public onlyOwner {
require(
tokenSupply.current() + _mintAmount <= totalSaleSupply,
"FuDaoVerseDAN: Max Supply Reached!"
);
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
}
emit DevMint(_mintAmount);
}
/**
* @dev Airdrops NFTs to the list of addresses provided
* @param addresses List of airdrop recepients
*/
function airdrop(address[] memory addresses) public onlyOwner {
require(
tokenSupply.current() + addresses.length <= totalSaleSupply,
"FuDaoVerseDAN: Max Supply Reached!"
);
for (uint256 i; i < addresses.length; i++) {
tokenSupply.increment();
_safeMint(addresses[i], tokenSupply.current());
emit Airdrop(addresses[i], tokenSupply.current());
}
}
/**
* @dev Checks if the the signature is signed by a valid signer for whitelists
* @param sender Address of minter
* @param nonce Random bytes32 nonce
* @param signature Signature generated off-chain
*/
function whitelistSigned(
address sender,
bytes memory nonce,
bytes memory signature
) private view returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(sender, nonce));
return signerAddress == hash.recover(signature);
}
// ------------------------- VIEW FUNCTIONS -----------------------------
/**
* @notice Returns metadata URI for sepecified token id
* @param tokenId Token Id to retrieve metadata
* @return Metadata URI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
".json"
)
)
: "";
}
/**
* @notice Total NFTs Minted
*/
function totalSupply() public view returns (uint256) {
return tokenSupply.current();
}
// ------------------------- ADMIN FUNCTIONS -----------------------------
/**
* @dev Set Mint Stage
*/
function setStage(uint8 _stage) public onlyOwner {
require(stage < 4, "FuDaoVerseDAN: Exceeded maximum number of stages");
stage = _stage;
}
/**
* @dev Set Revealed Metadata URI
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
require(!revealed);
baseURI = _newBaseURI;
}
/**
* @dev Set Presale maximum amount of mints
*/
function setPresaleMintMax(uint256 amount) public onlyOwner {
presaleMintMax = amount;
}
/**
* @dev Set the unrevealed URI
* @param _notRevealedURI unrevealed URI for metadata
*/
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
/**
* @dev Set Revealed state of NFT metadata
*/
function reveal() public onlyOwner {
revealed = true;
}
/**
* @dev Switches pause state to `_state`
* @param _state Pause State
*/
function pause(bool _state) public onlyOwner {
paused = _state;
}
/**
* @dev Emergency Function to withdraw any ETH deposited to this contract
*/
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
/**
* @dev requires currentBalance of contract to have some amount
* @dev withdraws with the fixed define distribution
*/
function withdrawFund() public onlyOwner {
uint256 currentBal = address(this).balance;
require(currentBal > 0);
for (uint256 i = 0; i < fundRecipients.length - 1; i++) {
_withdraw(
fundRecipients[i],
(currentBal * receivePercentagePt[i]) / 10000
);
}
//final address receives remainder to prevent ether dust
_withdraw(
fundRecipients[fundRecipients.length - 1],
address(this).balance
);
}
/**
* @dev private function utilized by withdrawFund
* @param _addr Address of receiver
* @param _amt Amount to withdraw
*/
function _withdraw(address _addr, uint256 _amt) private {
(bool success, ) = _addr.call{value: _amt}("");
require(success, "Transfer failed");
}
/**
* @dev retrieve base URI internally
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
}
// 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));
}
}
|
private function utilized by withdrawFund _addr Address of receiver _amt Amount to withdraw/
|
function _withdraw(address _addr, uint256 _amt) private {
require(success, "Transfer failed");
}
| 13,708,013 |
./full_match/100/0x58614A66Dcb3A6D120b8d94bE21140aC6FF8842E/sources/contracts/OrbisMain.sol
|
Interface for the ERC20 contracts created for reputation/
|
interface ReputationToken {
function getIsGovernanceActive() external view returns(bool);
function mint(address _member, uint _amount) external;
function burn(address _member, uint _amount) external;
function setMerkleRoot(uint _type, uint _id, bytes32 _merkleRoot) external;
}
| 14,270,651 |
// Prop.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./Board.sol";
/**
* @title Prop contract
* @notice implements all elements related to ERC721 NFT Property alias Prop
* @notice Royalties:
* @notice Only some addresses are allowed to transfer these tokens.
* @notice Token owner can't resell is token outside an authorized Marketplace as OpenSea or our future Marketplace.
* @author Jerome Caporossi, Stéphane Chaunard, Alexandre Gautier
*/
contract PropContract is ERC721Enumerable, AccessControl, Ownable, IERC2981 {
/// @dev structure used to store property's attribute
struct Property {
// edition number
uint16 edition;
// id of the cell of board
uint8 land;
// rarity level (as a power of 10, i.e rarity = 1 means 10^1 = 10 versions)
uint8 rarity;
// serial number
uint32 serial;
}
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
BoardContract private immutable Board;
mapping(uint256 => Property) private props;
/// @dev Number of minted properties for each (edition, land, rarity) tuple
mapping(uint16 => mapping(uint8 => mapping(uint8 => uint16))) numOfProps;
/// @dev store all allowed operators to sell NFT Prop and to redistribute royalties
mapping(address => bool) public isOperatorAllowed;
mapping(uint256 => uint96) private royaltiesValuesByTokenId;
string private baseTokenURI;
uint96 public defaultRoyaltyPercentageBasisPoints = 500; // 5%
/** Event emitted when the royalty percentage is set
* @param tokenId Prop token ID
* @param royaltyPercentageBasisPoints percentage*/
event RoyaltySet(uint256 tokenId, uint256 royaltyPercentageBasisPoints);
/** @dev Constructor
* @param BoardAddress address
* @param _name name
* @param _symbol symbol
* @param _baseTokenURI base token uri
* @dev ADMIN_ROLE, MINTER_ROLE are given to deployer*/
constructor(
address BoardAddress,
string memory _name,
string memory _symbol,
string memory _baseTokenURI
) ERC721(_name, _symbol) {
baseTokenURI = _baseTokenURI;
_setupRole(ADMIN_ROLE, msg.sender);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(MINTER_ROLE, msg.sender);
_setRoleAdmin(MINTER_ROLE, ADMIN_ROLE);
Board = BoardContract(BoardAddress);
}
/** Retrieve validity of a Prop
* @param edition board edition
* @param land land id
* @param rarity rarity
* @return bool value*/
function isValidProp(
uint16 edition,
uint8 land,
uint8 rarity
) public view returns (bool) {
return
(edition <= Board.getMaxEdition()) &&
(land <= Board.getNbLands(edition)) &&
(Board.isPurchasable(edition, land)) &&
(rarity <= Board.getRarityLevel(edition));
}
/** @dev get contract's baseURI
* @return string value*/
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
/** get token URI relative to a Prop
* @param _id Prop ID
* @return string value*/
function tokenURI(uint256 _id) public view override returns (string memory) {
string memory uri = super.tokenURI(_id);
string memory ext = ".json";
return string(abi.encodePacked(uri, ext));
}
/** Mint NFT token and set royalties default value
* @notice #### requirements :<br />
* @notice - Property must be valid
* @param _to buyer address
* @param _edition board edition
* @param _land land id
* @param _rarity rarity*/
function mint(
address _to,
uint16 _edition,
uint8 _land,
uint8 _rarity
) external onlyRole(MINTER_ROLE) returns (uint256 id_) {
require(isValidProp(_edition, _land, _rarity), "PROP cannot be minted");
id_ = generateID(_edition, _land, _rarity);
_safeMint(_to, id_);
_setRoyalties(id_);
}
/** get property struct for a Prop
* @param _id Prop ID
* @return p_ property struct*/
function get(uint256 _id) public view returns (Property memory p_) {
require(exists(_id), "This property does not exist");
p_ = props[_id];
}
/** get existence of a Prop i.e if Prop has been minted or not.
* @param _id Prop ID
* @return bool*/
function exists(uint256 _id) public view returns (bool) {
return (
(props[_id].land == 0) && (props[_id].edition == 0) && (props[_id].rarity == 0) && (props[_id].serial == 0)
? false
: true
);
}
/** get number of Props by
* @param _edition board edition
* @param _land land id
* @param _rarity rarity
* @return amount_ quantity*/
function getNbOfProps(
uint16 _edition,
uint8 _land,
uint8 _rarity
) public view returns (uint32 amount_) {
require(isValidProp(_edition, _land, _rarity), "PROP does not exist");
return numOfProps[_edition][_land][_rarity];
}
/** is contract support interface
* @param _interfaceId interface ID
* @return bool*/
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Enumerable, AccessControl, IERC165)
returns (bool)
{
if (_interfaceId == _INTERFACE_ID_ERC2981) {
return true;
}
return super.supportsInterface(_interfaceId);
}
/** @dev generate an ID for a Prop
* @param _edition board edition
* @param _land land id
* @param _rarity rarity
* @return id_ the Prop ID*/
function generateID(
uint16 _edition,
uint8 _land,
uint8 _rarity
) internal returns (uint256 id_) {
uint32 serial = numOfProps[_edition][_land][_rarity];
require(serial < 10**_rarity, "all properties already minted");
numOfProps[_edition][_land][_rarity] += 1;
id_ = uint256(keccak256(abi.encode(_edition, _land, _rarity, serial)));
props[id_] = Property(_edition, _land, _rarity, serial);
}
/** Set default royalties percentage basis point. Can be only made by admin role.
* @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/
function setDefaultRoyaltyPercentageBasisPoints(uint96 _percentageBasisPoints) public onlyRole(ADMIN_ROLE) {
defaultRoyaltyPercentageBasisPoints = _percentageBasisPoints;
}
/** Set royalties for a NFT token id at percentage basis point. Can be only made by admin role.
* @param _tokenId NFT token id
* @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/
function setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints) public onlyRole(ADMIN_ROLE) {
_setRoyalties(_tokenId, _percentageBasisPoints);
}
/** @dev Set royalties for a NFT token id at default percentage basis point.
* @dev default value should be set with this.setDefaultRoyaltyPercentageBasisPoints()
* @param _tokenId NFT token id
* @dev See this._setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints)*/
function _setRoyalties(uint256 _tokenId) internal {
_setRoyalties(_tokenId, defaultRoyaltyPercentageBasisPoints);
}
/** Set royalties for a NFT token id at a percentage basis point. Assuming that royalties receiver is contract's owner
* @param _tokenId NFT token id
* @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/
function _setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints) internal {
require(_percentageBasisPoints < 10000, "Royalty value should be < 10000");
royaltiesValuesByTokenId[_tokenId] = _percentageBasisPoints;
emit RoyaltySet(_tokenId, _percentageBasisPoints);
}
/** Return royalties information as describe at EIP-2981: NFT Royalty Standard
* @notice Return nul address and value if there is no royalty to pay.
* @param _tokenId NFT token id
* @param _salePrice sale price
* @return receiver royalty receiver address
* @return royaltyAmount royalty amount to pay to receiver
* @dev Override isApprovedForAll to auto-approve confident operator contracts
* See {ERC721-isApprovedForAll}
* See https://docs.opensea.io/docs/polygon-basic-integration#overriding-isapprovedforall-to-reduce-trading-friction
* @inheritdoc IERC2981*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
uint96 royaltyValue = royaltiesValuesByTokenId[_tokenId];
if (royaltyValue > 0) {
return (this.owner(), (_salePrice * royaltyValue) / 10000);
}
return (address(0), 0);
}
/** Return true only for allowed operators, see: isOperatorAllowed
* @param _owner owner address
* @param _operator operator address
* @return bool*/
function isApprovedForAll(address _owner, address _operator) public view override returns (bool) {
if (isOperatorAllowed[_operator]) {
return true;
}
// silent warning
_owner;
return false;
}
/** Admin role can allowed un operator
* @param _address operator address
* @param value true / false*/
function setIsOperatorAllowed(address _address, bool value) external onlyRole(ADMIN_ROLE) {
isOperatorAllowed[_address] = value;
}
/** @dev Override _isApprovedOrOwner to limit approval to confident operators only.
* @dev See {IERC721-_isApprovedOrOwner}.*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view override returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return isApprovedForAll(owner, spender); // limit allowed operator as spender
}
}
|
Admin role can allowed un operator _address operator address value true / false/
|
function setIsOperatorAllowed(address _address, bool value) external onlyRole(ADMIN_ROLE) {
isOperatorAllowed[_address] = value;
}
| 12,763,218 |
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
pragma solidity ^0.4.6;
import "./Crowdsale.sol";
import "./SafeMathLib.sol";
/**
* Collect funds from presale investors to be send to the crowdsale smart contract later.
*
* - Collect funds from pre-sale investors
* - Send funds to the crowdsale when it opens
* - Allow owner to set the crowdsale
* - Have refund after X days as a safety hatch if the crowdsale doesn't materilize
*
*/
contract PresaleFundCollector is Ownable {
using SafeMathLib for uint;
/** How many investors when can carry per a single contract */
uint public MAX_INVESTORS = 32;
/** How many investors we have now */
uint public investorCount;
/** Who are our investors (iterable) */
address[] public investors;
/** How much they have invested */
mapping(address => uint) public balances;
/** When our refund freeze is over (UNIX timestamp) */
uint public freezeEndsAt;
/** What is the minimum buy in */
uint public weiMinimumLimit;
/** Have we begun to move funds */
bool public moving;
/** Our ICO contract where we will move the funds */
Crowdsale public crowdsale;
event Invested(address investor, uint value);
event Refunded(address investor, uint value);
/**
* Create presale contract where lock up period is given days
*/
function PresaleFundCollector(address _owner, uint _freezeEndsAt, uint _weiMinimumLimit) {
owner = _owner;
// Give argument
if(_freezeEndsAt == 0) {
throw;
}
// Give argument
if(_weiMinimumLimit == 0) {
throw;
}
weiMinimumLimit = _weiMinimumLimit;
freezeEndsAt = _freezeEndsAt;
}
/**
* Participate to a presale.
*/
function invest() public payable {
// Cannot invest anymore through crowdsale when moving has begun
if(moving) throw;
address investor = msg.sender;
bool existing = balances[investor] > 0;
balances[investor] = balances[investor].plus(msg.value);
// Need to fulfill minimum limit
if(balances[investor] < weiMinimumLimit) {
throw;
}
// This is a new investor
if(!existing) {
// Limit number of investors to prevent too long loops
if(investorCount >= MAX_INVESTORS) throw;
investors.push(investor);
investorCount++;
}
Invested(investor, msg.value);
}
/**
* Load funds to the crowdsale for a single investor.
*/
function participateCrowdsaleInvestor(address investor) public {
// Crowdsale not yet set
if(address(crowdsale) == 0) throw;
moving = true;
if(balances[investor] > 0) {
uint amount = balances[investor];
delete balances[investor];
crowdsale.invest.value(amount)(investor);
}
}
/**
* Load funds to the crowdsale for all investor.
*
*/
function participateCrowdsaleAll() public {
// We might hit a max gas limit in this loop,
// and in this case you can simply call participateCrowdsaleInvestor() for all investors
for(uint i=0; i<investors.length; i++) {
participateCrowdsaleInvestor(investors[i]);
}
}
/**
* ICO never happened. Allow refund.
*/
function refund() {
// Trying to ask refund too soon
if(now < freezeEndsAt) throw;
// We have started to move funds
moving = true;
address investor = msg.sender;
if(balances[investor] == 0) throw;
uint amount = balances[investor];
delete balances[investor];
if(!investor.send(amount)) throw;
Refunded(investor, amount);
}
/**
* Set the target crowdsale where we will move presale funds when the crowdsale opens.
*/
function setCrowdsale(Crowdsale _crowdsale) public onlyOwner {
crowdsale = _crowdsale;
}
/** Explicitly call function from your wallet. */
function() payable {
throw;
}
}
|
Load funds to the crowdsale for a single investor./ Crowdsale not yet set
|
function participateCrowdsaleInvestor(address investor) public {
if(address(crowdsale) == 0) throw;
moving = true;
if(balances[investor] > 0) {
uint amount = balances[investor];
delete balances[investor];
crowdsale.invest.value(amount)(investor);
}
}
| 12,605,157 |
/// SPDX-License-Identifier: MIT
/*
▄▄█ ▄ ██ █▄▄▄▄ ▄█
██ █ █ █ █ ▄▀ ██
██ ██ █ █▄▄█ █▀▀▌ ██
▐█ █ █ █ █ █ █ █ ▐█
▐ █ █ █ █ █ ▐
█ ██ █ ▀
▀ */
/// Special thanks to Keno, Boring and Gonpachi for review and continued inspiration.
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
/// License-Identifier: MIT
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice Interface for depositing into and withdrawing from Aave lending pool.
interface IAaveBridge {
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address token,
uint256 amount,
address destination
) external;
}
/// @notice Interface for depositing into and withdrawing from BentoBox vault.
interface IBentoBridge {
function balanceOf(IERC20, address) external view returns (uint256);
function registerProtocol() external;
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external payable returns (uint256 amountOut, uint256 shareOut);
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
}
/// @notice Interface for depositing into and withdrawing from Compound finance protocol.
interface ICompoundBridge {
function underlying() external view returns (address);
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
}
/// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive.
interface IDaiPermit {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @notice Interface for depositing into and withdrawing from SushiBar.
interface ISushiBarBridge {
function enter(uint256 amount) external;
function leave(uint256 share) external;
}
/// @notice Interface for SushiSwap.
interface ISushiSwap {
function deposit() external payable;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
// File @boringcrypto/boring-solidity/contracts/interfaces/[email protected]
/// License-Identifier: MIT
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, 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);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
/// License-Identifier: MIT
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
/// License-Identifier: MIT
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
/// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
/// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {
successes = new bool[](calls.length);
results = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
require(success || !revertOnFail, _getRevertMsg(result));
successes[i] = success;
results[i] = result;
}
}
}
/// @notice Extends `BoringBatchable` with DAI `permit()`.
contract BoringBatchableWithDai is BaseBoringBatchable {
address constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // DAI token contract
/// @notice Call wrapper that performs `ERC20.permit` on `dai` using EIP 2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) public {
IDaiPermit(dai).permit(holder, spender, nonce, expiry, allowed, v, r, s);
}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1.
contract Inari is BoringBatchableWithDai {
using BoringMath for uint256;
using BoringERC20 for IERC20;
IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract
address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI
IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI
IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI
IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract
address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI
address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI
address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // ETH wrapper contract (v9)
address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract
ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap
bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash
/// @notice Initialize this Inari contract and core SUSHI strategies.
constructor() public {
bento.registerProtocol(); // register this contract with BENTO
sushiToken.approve(address(sushiBar), type(uint256).max); // max approve `sushiBar` spender to stake SUSHI into xSUSHI from this contract
sushiToken.approve(crSushiToken, type(uint256).max); // max approve `crSushiToken` spender to stake SUSHI into crSUSHI from this contract
IERC20(sushiBar).approve(address(aave), type(uint256).max); // max approve `aave` spender to stake xSUSHI into aXSUSHI from this contract
IERC20(sushiBar).approve(address(bento), type(uint256).max); // max approve `bento` spender to stake xSUSHI into BENTO from this contract
IERC20(sushiBar).approve(crXSushiToken, type(uint256).max); // max approve `crXSushiToken` spender to stake xSUSHI into crXSUSHI from this contract
IERC20(dai).approve(address(bento), type(uint256).max); // max approve `bento` spender to pull DAI into BENTO from this contract
}
/// @notice Helper function to approve this contract to spend and bridge more tokens among DeFi contracts.
function bridgeABC(IERC20[] calldata underlying, address[] calldata cToken) external {
for (uint256 i = 0; i < underlying.length; i++) {
underlying[i].approve(address(aave), type(uint256).max); // max approve `aave` spender to pull `underlying` from this contract
underlying[i].approve(address(bento), type(uint256).max); // max approve `bento` spender to pull `underlying` from this contract
underlying[i].approve(cToken[i], type(uint256).max); // max approve `cToken` spender to pull `underlying` from this contract (also serves as generalized approval bridge)
}
}
/************
SUSHI HELPERS
************/
/// @notice Stake SUSHI `amount` into xSushi for benefit of `to` by call to `sushiBar`.
function stakeSushi(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/// @notice Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`.
function stakeSushiBalance(address to) external {
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake local SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/**********
TKN HELPERS
**********/
/// @notice Token deposit function for `batch()` into strategies.
function depositToken(IERC20 token, uint256 amount) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
/// @notice Token withdraw function for `batch()` into strategies.
function withdrawToken(IERC20 token, address to, uint256 amount) external {
IERC20(token).safeTransfer(to, amount);
}
/// @notice Token local balance withdraw function for `batch()` into strategies.
function withdrawTokenBalance(IERC20 token, address to) external {
IERC20(token).safeTransfer(to, token.balanceOf(address(this)));
}
/*
██ ██ ▄ ▄███▄
█ █ █ █ █ █▀ ▀
█▄▄█ █▄▄█ █ █ ██▄▄
█ █ █ █ █ █ █▄ ▄▀
█ █ █ █ ▀███▀
█ █ █▐
▀ ▀ ▐ */
/***********
AAVE HELPERS
***********/
function toAave(address underlying, address to, uint256 amount) external {
aave.deposit(underlying, amount, to, 0);
}
function balanceToAave(address underlying, address to) external {
aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0);
}
function fromAave(address underlying, address to, uint256 amount) external {
aave.withdraw(underlying, amount, to);
}
function balanceFromAave(address aToken, address to) external {
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, IERC20(aToken).balanceOf(address(this)), to);
}
/**************************
AAVE -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`.
function aaveToBento(address aToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
bento.deposit(IERC20(underlying), address(this), to, amount, 0); // stake `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> AAVE
**************************/
/// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`.
function bentoToAave(IERC20 underlying, address to, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to`
}
/*************************
AAVE -> UNDERLYING -> COMP
*************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`.
function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/*************************
COMP -> UNDERLYING -> AAVE
*************************/
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`.
function compoundToAave(address cToken, address to, uint256 amount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract
ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying`
address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token
aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0); // stake resulting `underlying` into `aave` for `to`
}
/**********************
SUSHI -> XSUSHI -> AAVE
**********************/
/// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`.
function stakeSushiToAave(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to`
}
/**********************
AAVE -> XSUSHI -> SUSHI
**********************/
/// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`.
function unstakeSushiFromAave(address to, uint256 amount) external {
aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract
aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI
ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
███ ▄███▄ ▄ ▄▄▄▄▀ ████▄
█ █ █▀ ▀ █ ▀▀▀ █ █ █
█ ▀ ▄ ██▄▄ ██ █ █ █ █
█ ▄▀ █▄ ▄▀ █ █ █ █ ▀████
███ ▀███▀ █ █ █ ▀
█ ██ */
/// @notice Helper function to `permit()` this contract to deposit `dai` into `bento` for benefit of `to`.
function daiToBentoWithPermit(
address to, uint256 amount, uint256 nonce, uint256 expiry,
uint8 v, bytes32 r, bytes32 s
) external {
IDaiPermit(dai).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); // `permit()` this contract to spend `msg.sender` `dai`
IERC20(dai).safeTransferFrom(msg.sender, address(this), amount); // pull `dai` `amount` into this contract
bento.deposit(IERC20(dai), address(this), to, amount, 0); // stake `dai` into BENTO for `to`
}
/************
BENTO HELPERS
************/
function toBento(IERC20 token, address to, uint256 amount) external {
bento.deposit(token, address(this), to, amount, 0);
}
function balanceToBento(IERC20 token, address to) external {
bento.deposit(token, address(this), to, token.balanceOf(address(this)), 0);
}
function fromBento(IERC20 token, address to, uint256 amount) external {
bento.withdraw(token, msg.sender, to, amount, 0);
}
function balanceFromBento(IERC20 token, address to) external {
bento.withdraw(token, msg.sender, to, bento.balanceOf(token, msg.sender), 0);
}
/***********************
SUSHI -> XSUSHI -> BENTO
***********************/
/// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.
function stakeSushiToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to`
}
/***********************
BENTO -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`.
function unstakeSushiFromBento(address to, uint256 amount) external {
bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract
ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█
█▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █
█ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █
█▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █
▀███▀ █ ▀███▀ █ █
▀ █ ▀
▀ */
// - COMPOUND - //
/***********
COMP HELPERS
***********/
function toCompound(ICompoundBridge cToken, uint256 underlyingAmount) external {
cToken.mint(underlyingAmount);
}
function balanceToCompound(ICompoundBridge cToken) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
cToken.mint(underlying.balanceOf(address(this)));
}
function fromCompound(ICompoundBridge cToken, uint256 cTokenAmount) external {
ICompoundBridge(cToken).redeem(cTokenAmount);
}
function balanceFromCompound(address cToken) external {
ICompoundBridge(cToken).redeem(IERC20(cToken).balanceOf(address(this)));
}
/**************************
COMP -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`.
function compoundToBento(address cToken, address to, uint256 cTokenAmount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract
ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.deposit(underlying, address(this), to, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> COMP
**************************/
/// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`.
function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract
ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/**********************
SUSHI -> CREAM -> BENTO
**********************/
/// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`.
function sushiToCreamToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI
bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `to`
}
/**********************
BENTO -> CREAM -> SUSHI
**********************/
/// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`.
function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract
ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/***********************
SUSHI -> XSUSHI -> CREAM
***********************/
/// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`.
function stakeSushiToCream(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `to`
}
/***********************
CREAM -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCream(address to, uint256 cTokenAmount) external {
IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/********************************
SUSHI -> XSUSHI -> CREAM -> BENTO
********************************/
/// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`.
function stakeSushiToCreamToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `to`
}
/********************************
BENTO -> CREAM -> XSUSHI -> SUSHI
********************************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
▄▄▄▄▄ ▄ ▄ ██ █ ▄▄
█ ▀▄ █ █ █ █ █ █
▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀
▀▄▄▄▄▀ █ █ █ █ █ █
█ █ █ █ █
▀ ▀ █ ▀
▀ */
/// @notice SushiSwap ETH to stake SUSHI into xSUSHI for benefit of `to`.
function ethStakeSushi(address to) external payable { // SWAP `N STAKE
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
ISushiSwap(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(amountOut, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/// @notice SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`.
function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`.
function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).balanceOf(address(this));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice SushiSwap ETH `msg.value` to `toToken` for benefit of `to`.
function swapETH(address toToken, address to) external payable returns (uint256 amountOut) {
(address token0, address token1) = wETH < toToken ? (wETH, toToken) : (toToken, wETH);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
ISushiSwap(wETH).deposit{value: msg.value}();
if (toToken > wETH) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(wETH).safeTransfer(address(pair), msg.value);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(wETH).safeTransfer(address(pair), msg.value);
pair.swap(amountOut, 0, to, "");
}
}
}
|
/ Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`.
|
function stakeSushiToCreamToBento(address to, uint256 amount) external {
}
| 44,121 |
./partial_match/1/0xD42a2bB59775694c9Df4c7822BfFAb150e6c699D/sources/src/PRBProxyRegistry.sol
|
@inheritdoc IPRBProxyRegistry
|
function getPermissionByOwner(
address owner,
address envoy,
address target
)
external
view
returns (bool permission)
{
permission = _permissions[owner][envoy][target];
}
| 15,704,782 |
./full_match/56/0xE40244Ea8B851137e75638702F5F29e1F0963dA2/sources/goerlitest.sol
|
claim any tokens from reward wrapper if someone accidently sent it. token: token address to be rescued amount: amount to take out from wrapper
|
function claimStuckedTokensFromRewardWrapper (address token, uint256 amount) external onlyOwner{
rewardFundManager.claimStuckedTokens(token, amount);
}
| 3,240,386 |
// File: contracts/interfaces/IDelegable.sol
pragma solidity ^0.6.10;
interface IDelegable {
function ADDDELEGATE653(address) external; //inject NONSTANDARD NAMING
function ADDDELEGATEBYSIGNATURE882(address, address, uint, uint8, bytes32, bytes32) external; //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
interface IERC20 {
function TOTALSUPPLY521() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER582(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE506(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM451(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER75(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL533(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IVat.sol
pragma solidity ^0.6.10;
interface IVat {
// function can(address, address) external view returns (uint);
function HOPE952(address) external; //inject NONSTANDARD NAMING
function NOPE303(address) external; //inject NONSTANDARD NAMING
function LIVE610() external view returns (uint); //inject NONSTANDARD NAMING
function ILKS57(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING
function URNS490(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING
function GEM988(bytes32, address) external view returns (uint); //inject NONSTANDARD NAMING
// function dai(address) external view returns (uint);
function FROB42(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING
function FORK314(bytes32, address, address, int, int) external; //inject NONSTANDARD NAMING
function MOVE289(address, address, uint) external; //inject NONSTANDARD NAMING
function FLUX433(bytes32, address, address, uint) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IWeth.sol
pragma solidity ^0.6.10;
interface IWeth {
function DEPOSIT338() external payable; //inject NONSTANDARD NAMING
function WITHDRAW817(uint) external; //inject NONSTANDARD NAMING
function APPROVE147(address, uint) external returns (bool) ; //inject NONSTANDARD NAMING
function TRANSFER582(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM451(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IGemJoin.sol
pragma solidity ^0.6.10;
interface IGemJoin {
function RELY66(address usr) external; //inject NONSTANDARD NAMING
function DENY577(address usr) external; //inject NONSTANDARD NAMING
function CAGE307() external; //inject NONSTANDARD NAMING
function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING
function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IDaiJoin.sol
pragma solidity ^0.6.10;
interface IDaiJoin {
function RELY66(address usr) external; //inject NONSTANDARD NAMING
function DENY577(address usr) external; //inject NONSTANDARD NAMING
function CAGE307() external; //inject NONSTANDARD NAMING
function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING
function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IPot.sol
pragma solidity ^0.6.10;
interface IPot {
function CHI612() external view returns (uint256); //inject NONSTANDARD NAMING
function PIE445(address) external view returns (uint256); // Not a function, but a public variable. //inject NONSTANDARD NAMING
function RHO514() external returns (uint256); //inject NONSTANDARD NAMING
function DRIP65() external returns (uint256); //inject NONSTANDARD NAMING
function JOIN369(uint256) external; //inject NONSTANDARD NAMING
function EXIT932(uint256) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IChai.sol
pragma solidity ^0.6.10;
interface IChai {
function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER582(address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function MOVE289(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM451(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE147(address usr, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function DAI858(address usr) external returns (uint wad); //inject NONSTANDARD NAMING
function JOIN369(address dst, uint wad) external; //inject NONSTANDARD NAMING
function EXIT932(address src, uint wad) external; //inject NONSTANDARD NAMING
function DRAW289(address src, uint wad) external; //inject NONSTANDARD NAMING
function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
function NONCES538(address account) external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/ITreasury.sol
pragma solidity ^0.6.10;
interface ITreasury {
function DEBT715() external view returns(uint256); //inject NONSTANDARD NAMING
function SAVINGS903() external view returns(uint256); //inject NONSTANDARD NAMING
function PUSHDAI613(address user, uint256 dai) external; //inject NONSTANDARD NAMING
function PULLDAI166(address user, uint256 dai) external; //inject NONSTANDARD NAMING
function PUSHCHAI91(address user, uint256 chai) external; //inject NONSTANDARD NAMING
function PULLCHAI479(address user, uint256 chai) external; //inject NONSTANDARD NAMING
function PUSHWETH634(address to, uint256 weth) external; //inject NONSTANDARD NAMING
function PULLWETH548(address to, uint256 weth) external; //inject NONSTANDARD NAMING
function SHUTDOWN178() external; //inject NONSTANDARD NAMING
function LIVE610() external view returns(bool); //inject NONSTANDARD NAMING
function VAT519() external view returns (IVat); //inject NONSTANDARD NAMING
function WETH278() external view returns (IWeth); //inject NONSTANDARD NAMING
function DAI858() external view returns (IERC20); //inject NONSTANDARD NAMING
function DAIJOIN173() external view returns (IDaiJoin); //inject NONSTANDARD NAMING
function WETHJOIN654() external view returns (IGemJoin); //inject NONSTANDARD NAMING
function POT408() external view returns (IPot); //inject NONSTANDARD NAMING
function CHAI326() external view returns (IChai); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IERC2612.sol
// Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
pragma solidity ^0.6.0;
interface IERC2612 {
function PERMIT233(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
function NONCES538(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IFYDai.sol
pragma solidity ^0.6.10;
interface IFYDai is IERC20, IERC2612 {
function ISMATURE431() external view returns(bool); //inject NONSTANDARD NAMING
function MATURITY388() external view returns(uint); //inject NONSTANDARD NAMING
function CHI0242() external view returns(uint); //inject NONSTANDARD NAMING
function RATE0398() external view returns(uint); //inject NONSTANDARD NAMING
function CHIGROWTH747() external view returns(uint); //inject NONSTANDARD NAMING
function RATEGROWTH408() external view returns(uint); //inject NONSTANDARD NAMING
function MATURE589() external; //inject NONSTANDARD NAMING
function UNLOCKED182() external view returns (uint); //inject NONSTANDARD NAMING
function MINT176(address, uint) external; //inject NONSTANDARD NAMING
function BURN250(address, uint) external; //inject NONSTANDARD NAMING
function FLASHMINT22(uint, bytes calldata) external; //inject NONSTANDARD NAMING
function REDEEM906(address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING
// function transfer(address, uint) external returns (bool);
// function transferFrom(address, address, uint) external returns (bool);
// function approve(address, uint) external returns (bool);
}
// File: contracts/interfaces/IController.sol
pragma solidity ^0.6.10;
interface IController is IDelegable {
function TREASURY445() external view returns (ITreasury); //inject NONSTANDARD NAMING
function SERIES14(uint256) external view returns (IFYDai); //inject NONSTANDARD NAMING
function SERIESITERATOR268(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSERIES702() external view returns (uint256); //inject NONSTANDARD NAMING
function CONTAINSSERIES982(uint256) external view returns (bool); //inject NONSTANDARD NAMING
function POSTED950(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBTFYDAI447(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBTDAI877(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALDEBTDAI51(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function ISCOLLATERALIZED839(bytes32, address) external view returns (bool); //inject NONSTANDARD NAMING
function INDAI269(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function INFYDAI474(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function ERASE227(bytes32, address) external returns (uint256, uint256); //inject NONSTANDARD NAMING
function SHUTDOWN178() external; //inject NONSTANDARD NAMING
function POST95(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function WITHDRAW817(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function BORROW691(bytes32, uint256, address, address, uint256) external; //inject NONSTANDARD NAMING
function REPAYFYDAI426(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING
function REPAYDAI460(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IDai.sol
pragma solidity ^0.6.10;
interface IDai is IERC20 {
function NONCES538(address user) external view returns (uint256); //inject NONSTANDARD NAMING
function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, //inject NONSTANDARD NAMING
bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/interfaces/IPool.sol
pragma solidity ^0.6.10;
interface IPool is IDelegable, IERC20, IERC2612 {
function DAI858() external view returns(IERC20); //inject NONSTANDARD NAMING
function FYDAI600() external view returns(IFYDai); //inject NONSTANDARD NAMING
function GETDAIRESERVES173() external view returns(uint128); //inject NONSTANDARD NAMING
function GETFYDAIRESERVES833() external view returns(uint128); //inject NONSTANDARD NAMING
function SELLDAI400(address from, address to, uint128 daiIn) external returns(uint128); //inject NONSTANDARD NAMING
function BUYDAI253(address from, address to, uint128 daiOut) external returns(uint128); //inject NONSTANDARD NAMING
function SELLFYDAI226(address from, address to, uint128 fyDaiIn) external returns(uint128); //inject NONSTANDARD NAMING
function BUYFYDAI675(address from, address to, uint128 fyDaiOut) external returns(uint128); //inject NONSTANDARD NAMING
function SELLDAIPREVIEW300(uint128 daiIn) external view returns(uint128); //inject NONSTANDARD NAMING
function BUYDAIPREVIEW913(uint128 daiOut) external view returns(uint128); //inject NONSTANDARD NAMING
function SELLFYDAIPREVIEW69(uint128 fyDaiIn) external view returns(uint128); //inject NONSTANDARD NAMING
function BUYFYDAIPREVIEW685(uint128 fyDaiOut) external view returns(uint128); //inject NONSTANDARD NAMING
function MINT176(address from, address to, uint256 daiOffered) external returns (uint256); //inject NONSTANDARD NAMING
function BURN250(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
library SafeMath {
function ADD958(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB494(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB494(a, b, "SafeMath: subtraction overflow");
}
function SUB494(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 MUL434(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 DIV16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV16(a, b, "SafeMath: division by zero");
}
function DIV16(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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 MOD331(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD331(a, b, "SafeMath: modulo by zero");
}
function MOD331(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/helpers/DecimalMath.sol
pragma solidity ^0.6.10;
contract DecimalMath {
using SafeMath for uint256;
uint256 constant public unit17 = 1e27; //inject NONSTANDARD NAMING
function MULD379(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return x.MUL434(y).DIV16(unit17);
}
function DIVD836(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return x.MUL434(unit17).DIV16(y);
}
function MULDRUP300(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING
{
uint256 z = x.MUL434(y);
return z.MOD331(unit17) == 0 ? z.DIV16(unit17) : z.DIV16(unit17).ADD958(1);
}
function DIVDRUP370(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING
{
uint256 z = x.MUL434(unit17);
return z.MOD331(y) == 0 ? z.DIV16(y) : z.DIV16(y).ADD958(1);
}
}
// File: contracts/peripheral/YieldProxy.sol
pragma solidity ^0.6.10;
library SafeCast {
function TOUINT128897(uint256 x) internal pure returns(uint128) { //inject NONSTANDARD NAMING
require(
x <= type(uint128).max,
"YieldProxy: Cast overflow"
);
return uint128(x);
}
function TOINT256710(uint256 x) internal pure returns(int256) { //inject NONSTANDARD NAMING
require(
x <= uint256(type(int256).max),
"YieldProxy: Cast overflow"
);
return int256(x);
}
}
contract YieldProxy is DecimalMath {
using SafeCast for uint256;
IVat public vat;
IWeth public weth;
IDai public dai;
IGemJoin public wethJoin;
IDaiJoin public daiJoin;
IChai public chai;
IController public controller;
ITreasury public treasury;
IPool[] public pools;
mapping (address => bool) public poolsMap;
bytes32 public constant chai69 = "CHAI"; //inject NONSTANDARD NAMING
bytes32 public constant weth148 = "ETH-A"; //inject NONSTANDARD NAMING
bool constant public mty307 = true; //inject NONSTANDARD NAMING
bool constant public ytm282 = false; //inject NONSTANDARD NAMING
constructor(address controller_, IPool[] memory _pools) public {
controller = IController(controller_);
treasury = controller.TREASURY445();
weth = treasury.WETH278();
dai = IDai(address(treasury.DAI858()));
chai = treasury.CHAI326();
daiJoin = treasury.DAIJOIN173();
wethJoin = treasury.WETHJOIN654();
vat = treasury.VAT519();
// for repaying debt
dai.APPROVE147(address(treasury), uint(-1));
// for posting to the controller
chai.APPROVE147(address(treasury), uint(-1));
weth.APPROVE147(address(treasury), uint(-1));
// for converting DAI to CHAI
dai.APPROVE147(address(chai), uint(-1));
vat.HOPE952(address(daiJoin));
vat.HOPE952(address(wethJoin));
dai.APPROVE147(address(daiJoin), uint(-1));
weth.APPROVE147(address(wethJoin), uint(-1));
weth.APPROVE147(address(treasury), uint(-1));
// allow all the pools to pull FYDai/dai from us for LPing
for (uint i = 0 ; i < _pools.length; i++) {
dai.APPROVE147(address(_pools[i]), uint(-1));
_pools[i].FYDAI600().APPROVE147(address(_pools[i]), uint(-1));
poolsMap[address(_pools[i])]= true;
}
pools = _pools;
}
function UNPACK384(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { //inject NONSTANDARD NAMING
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
}
function ONBOARD51(address from, bytes memory daiSignature, bytes memory controllerSig) external { //inject NONSTANDARD NAMING
bytes32 r;
bytes32 s;
uint8 v;
(r, s, v) = UNPACK384(daiSignature);
dai.PERMIT233(from, address(this), dai.NONCES538(from), uint(-1), true, v, r, s);
(r, s, v) = UNPACK384(controllerSig);
controller.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s);
}
function AUTHORIZEPOOL621(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
bytes32 r;
bytes32 s;
uint8 v;
(r, s, v) = UNPACK384(daiSig);
dai.PERMIT233(from, address(pool), dai.NONCES538(from), uint(-1), true, v, r, s);
(r, s, v) = UNPACK384(fyDaiSig);
pool.FYDAI600().PERMIT233(from, address(this), uint(-1), uint(-1), v, r, s);
(r, s, v) = UNPACK384(poolSig);
pool.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s);
}
receive() external payable { }
function POST95(address to) //inject NONSTANDARD NAMING
public payable {
weth.DEPOSIT338{ value: msg.value }();
controller.POST95(weth148, address(this), to, msg.value);
}
function WITHDRAW817(address payable to, uint256 amount) //inject NONSTANDARD NAMING
public {
controller.WITHDRAW817(weth148, msg.sender, address(this), amount);
weth.WITHDRAW817(amount);
to.transfer(amount);
}
function ADDLIQUIDITY157(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
require(fyDai.ISMATURE431() != true, "YieldProxy: Only before maturity");
require(dai.TRANSFERFROM451(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed");
// calculate needed fyDai
uint256 daiReserves = dai.BALANCEOF833(address(pool));
uint256 fyDaiReserves = fyDai.BALANCEOF833(address(pool));
uint256 daiToAdd = daiUsed.MUL434(daiReserves).DIV16(fyDaiReserves.ADD958(daiReserves));
uint256 daiToConvert = daiUsed.SUB494(daiToAdd);
require(
daiToConvert <= maxFYDai,
"YieldProxy: maxFYDai exceeded"
); // 1 Dai == 1 fyDai
// convert dai to chai and borrow needed fyDai
chai.JOIN369(address(this), daiToConvert);
// look at the balance of chai in dai to avoid rounding issues
uint256 toBorrow = chai.DAI858(address(this));
controller.POST95(chai69, address(this), msg.sender, chai.BALANCEOF833(address(this)));
controller.BORROW691(chai69, fyDai.MATURITY388(), msg.sender, address(this), toBorrow);
// mint liquidity tokens
return pool.MINT176(address(this), msg.sender, daiToAdd);
}
function REMOVELIQUIDITYEARLYDAIPOOL932(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
uint256 maturity = fyDai.MATURITY388();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens);
// Exchange Dai for fyDai to pay as much debt as possible
uint256 fyDaiBought = pool.SELLDAI400(address(this), address(this), daiObtained.TOUINT128897());
require(
fyDaiBought >= MULD379(daiObtained, minimumDaiPrice),
"YieldProxy: minimumDaiPrice not reached"
);
fyDaiObtained = fyDaiObtained.ADD958(fyDaiBought);
uint256 fyDaiUsed;
if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained);
}
uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed);
if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai
require(
pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice),
"YieldProxy: minimumFYDaiPrice not reached"
);
}
WITHDRAWASSETS926(fyDai);
}
function REMOVELIQUIDITYEARLYDAIFIXED8(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
uint256 maturity = fyDai.MATURITY388();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens);
uint256 fyDaiUsed;
if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained);
}
uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed);
if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai
if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained);
}
} else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai
require(
pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice),
"YieldProxy: minimumFYDaiPrice not reached"
);
}
WITHDRAWASSETS926(fyDai);
}
function REMOVELIQUIDITYMATURE267(IPool pool, uint256 poolTokens) external { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
uint256 maturity = fyDai.MATURITY388();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens);
if (fyDaiObtained > 0) {
daiObtained = daiObtained.ADD958(fyDai.REDEEM906(address(this), address(this), fyDaiObtained));
}
// Repay debt
if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained);
}
WITHDRAWASSETS926(fyDai);
}
function WITHDRAWASSETS926(IFYDai fyDai) internal { //inject NONSTANDARD NAMING
if (controller.DEBTFYDAI447(chai69, fyDai.MATURITY388(), msg.sender) == 0) {
controller.WITHDRAW817(chai69, msg.sender, address(this), controller.POSTED950(chai69, msg.sender));
chai.EXIT932(address(this), chai.BALANCEOF833(address(this)));
}
require(dai.TRANSFER582(msg.sender, dai.BALANCEOF833(address(this))), "YieldProxy: Dai Transfer Failed");
}
function BORROWDAIFORMAXIMUMFYDAI736( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 maximumFYDai,
uint256 daiToBorrow
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiToBorrow = pool.BUYDAIPREVIEW913(daiToBorrow.TOUINT128897());
require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required");
// The collateral for this borrow needs to have been posted beforehand
controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow);
pool.BUYDAI253(address(this), to, daiToBorrow.TOUINT128897());
return fyDaiToBorrow;
}
function BORROWMINIMUMDAIFORFYDAI776( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 fyDaiToBorrow,
uint256 minimumDaiToBorrow
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
// The collateral for this borrow needs to have been posted beforehand
controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow);
uint256 boughtDai = pool.SELLFYDAI226(address(this), to, fyDaiToBorrow.TOUINT128897());
require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained");
return boughtDai;
}
function REPAYFYDAIDEBTFORMAXIMUMDAI955( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 fyDaiRepayment,
uint256 maximumRepaymentInDai
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to);
uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt
uint256 repaymentInDai = pool.BUYFYDAI675(msg.sender, address(this), fyDaiToUse.TOUINT128897());
require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required");
controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiToUse);
return repaymentInDai;
}
function REPAYMINIMUMFYDAIDEBTFORDAI862( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 minimumFYDaiRepayment,
uint256 repaymentInDai
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiRepayment = pool.SELLDAIPREVIEW300(repaymentInDai.TOUINT128897());
uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to);
if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt
pool.SELLDAI400(msg.sender, address(this), repaymentInDai.TOUINT128897());
} else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead.
pool.BUYFYDAI675(msg.sender, address(this), fyDaiDebt.TOUINT128897());
fyDaiRepayment = fyDaiDebt;
}
require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid");
controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiRepayment);
return fyDaiRepayment;
}
function SELLDAI400(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiOut = pool.SELLDAI400(msg.sender, to, daiIn);
require(
fyDaiOut >= minFYDaiOut,
"YieldProxy: Limit not reached"
);
return fyDaiOut;
}
function BUYDAI253(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn) //inject NONSTANDARD NAMING
public
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiIn = pool.BUYDAI253(msg.sender, to, daiOut);
require(
maxFYDaiIn >= fyDaiIn,
"YieldProxy: Limit exceeded"
);
return fyDaiIn;
}
function BUYDAIWITHSIGNATURE110(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
(bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature);
pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s);
return BUYDAI253(pool, to, daiOut, maxFYDaiIn);
}
function SELLFYDAI226(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut) //inject NONSTANDARD NAMING
public
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 daiOut = pool.SELLFYDAI226(msg.sender, to, fyDaiIn);
require(
daiOut >= minDaiOut,
"YieldProxy: Limit not reached"
);
return daiOut;
}
function SELLFYDAIWITHSIGNATURE545(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
(bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature);
pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s);
return SELLFYDAI226(pool, to, fyDaiIn, minDaiOut);
}
function BUYFYDAI675(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 daiIn = pool.BUYFYDAI675(msg.sender, to, fyDaiOut);
require(
maxDaiIn >= daiIn,
"YieldProxy: Limit exceeded"
);
return daiIn;
}
function REPAYDAIWITHSIGNATURE818(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature) //inject NONSTANDARD NAMING
external
returns(uint256)
{
(bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature);
dai.PERMIT233(msg.sender, address(treasury), dai.NONCES538(msg.sender), uint(-1), true, v, r, s);
controller.REPAYDAI460(collateral, maturity, msg.sender, to, daiAmount);
}
function ONLYKNOWNPOOL167(IPool pool) private view { //inject NONSTANDARD NAMING
require(poolsMap[address(pool)], "YieldProxy: Unknown pool");
}
}
|
inject NONSTANDARD NAMING
|
function TOINT256710(uint256 x) internal pure returns(int256) {
| 12,707,208 |
./full_match/3/0x87B6AED8Fc0836950788621c1241446e3946dDdd/sources/CryptoTokens.sol
|
mint a new crypto token check if thic fucntion caller is not an zero address account increment counter check if a token exists with the above token id => incremented counter check if the token URI already exists or not check if the token name already exists or not mint the token set token URI (bind token id with the passed in token URI) make passed token URI as exists make token name passed as exists creat a new crypto token (struct) and pass in new values add the token id and it's crypto token to all crypto tokens mapping
|
function mintCryptoToken(string memory _name, string memory _tokenURI, uint256 _price, string memory _tokenDesc, uint256 _dateMinted) external {
require(msg.sender != address(0));
cryptoTokenCounter++;
require(!_exists(cryptoTokenCounter));
require(!tokenURIExists[_tokenURI]);
require(!tokenNameExists[_name]);
_mint(msg.sender, cryptoTokenCounter);
_setTokenURI(cryptoTokenCounter, _tokenURI);
tokenURIExists[_tokenURI] = true;
tokenNameExists[_name] = true;
CryptoToken memory newCryptoToken = CryptoToken(
cryptoTokenCounter,
_name,
_tokenDesc,
_tokenURI,
payable(msg.sender),
payable(msg.sender),
payable(address(0)),
_price,
0,
true,
_dateMinted
);
allCryptoTokens[cryptoTokenCounter] = newCryptoToken;
}
| 14,231,466 |
./full_match/100/0x2c3DE641b0448FF29f917F9808ce63047A04d83c/sources/contracts/rari-fuse/src/core/CToken.sol
|
Sender repays their own borrow repayAmount The amount to repay return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount./ accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
|
function repayBorrowInternal(uint256 repayAmount)
internal
nonReentrant(false)
returns (uint256, uint256)
{
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
return (
fail(
Error(error),
FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED
),
0
);
}
}
| 14,267,942 |
./partial_match/1/0x6e2A189AdF666C06950169f11197aB0C549d5C42/sources/xETH.sol
|
burnShares allows for burning xETH tokens this function can only burn tokens if the contract is not paused this function can only be called by the MINTER_ROLE amount amount of xETH to be burned, it cannot be 0
|
function burnShares(
uint256 amount
) external onlyRole(MINTER_ROLE) {
if (amount == 0) revert AmountZeroProvided();
_burn(msg.sender, amount);
| 9,220,330 |
./partial_match/1/0xE4764f9cd8ECc9659d3abf35259638B20ac536E4/sources/contracts/protocol/ParticleExchange.sol
|
@inheritdoc IParticleExchange verify that auction is concluded (i.e., liquidation condition has met)
|
function withdrawEth(Lien calldata lien, uint256 lienId) external override validateLien(lien, lienId) nonReentrant {
if (msg.sender != lien.lender) {
revert Errors.Unauthorized();
}
if (lien.loanStartTime == 0) {
revert Errors.InactiveLoan();
}
if (lien.auctionStartTime == 0 || block.timestamp <= lien.auctionStartTime + _AUCTION_DURATION) {
revert Errors.LiquidationHasNotReached();
}
emit WithdrawETH(lienId);
}
==============================================================*/
| 4,052,300 |
/* 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;
}
|
Returns tokens locked and validity for a specified address and reason _of The address whose tokens are locked _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;
}
}
| 2,577,972 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./CVNX.sol";
import "./ICVNXGovernance.sol";
/// @notice Governance contract for CVNX token.
contract CVNXGovernance is ICVNXGovernance, Ownable {
CVNX private cvnx;
/// @notice Emit when new poll created.
event PollCreated(uint256 indexed pollNum);
/// @notice Emit when address vote in poll.
event PollVoted(address voterAddress, VoteType indexed voteType, uint256 indexed voteWeight);
/// @notice Emit when poll stopped.
event PollStop(uint256 indexed pollNum, uint256 indexed stopTimestamp);
/// @notice Contain all polls. Index - poll number.
Poll[] public polls;
/// @notice Contain Vote for addresses that vote in poll.
mapping(uint256 => mapping(address => Vote)) public voted;
/// @notice Shows whether tokens are locked for a certain pool at a certain address.
mapping(uint256 => mapping(address => bool)) public isTokenLockedInPoll;
/// @notice List of verified addresses for PRIVATE poll.
mapping(uint256 => mapping(address => bool)) public verifiedToVote;
/// @notice Possibility to create new poll in contract.
bool private isAvailableToCreate = true;
/// @param _cvnxTokenAddress CVNX token address.
constructor(address _cvnxTokenAddress) {
cvnx = CVNX(_cvnxTokenAddress);
}
/// @notice Return variable isAvailableToCreate.
function getIsAvailableToCreate() external view override returns (bool) {
return isAvailableToCreate;
}
/// @notice Enable or disable possibility to create new poll in contract.
function setIsAvailableToCreate() external override onlyOwner() {
isAvailableToCreate = !isAvailableToCreate;
}
/// @notice Modifier check minimal CVNX token balance before method call.
/// @param _minimalBalance Minimal balance on address (Wei)
modifier onlyWithBalanceNoLess(uint256 _minimalBalance) {
require(cvnx.balanceOf(msg.sender) > _minimalBalance, "[E-34] - Your balance is too low.");
_;
}
/// @notice Create PROPOSAL poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
function createProposalPoll(uint64 _pollDeadline, string memory _pollInfo) external override {
_createPoll(PollType.PROPOSAL, _pollDeadline, _pollInfo);
}
/// @notice Create EXECUTIVE poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
function createExecutivePoll(uint64 _pollDeadline, string memory _pollInfo) external override onlyOwner {
_createPoll(PollType.EXECUTIVE, _pollDeadline, _pollInfo);
}
/// @notice Create EVENT poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
function createEventPoll(uint64 _pollDeadline, string memory _pollInfo) external override onlyOwner {
_createPoll(PollType.EVENT, _pollDeadline, _pollInfo);
}
/// @notice Create PRIVATE poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
/// @param _verifiedAddresses Array of verified addresses for poll
function createPrivatePoll(
uint64 _pollDeadline,
string memory _pollInfo,
address[] memory _verifiedAddresses
) external override onlyOwner {
uint256 _verifiedAddressesCount = _verifiedAddresses.length;
require(_verifiedAddressesCount > 1, "[E-35] - Verified addresses not set.");
uint256 _pollNum = _createPoll(PollType.PRIVATE, _pollDeadline, _pollInfo);
for (uint256 i = 0; i < _verifiedAddressesCount; i++) {
verifiedToVote[_pollNum][_verifiedAddresses[i]] = true;
}
}
/// @notice Send tokens as vote in poll. Tokens will be lock.
/// @param _pollNum Poll number
/// @param _voteType Vote type (FOR, AGAINST)
/// @param _voteWeight Vote weight in CVNX tokens
function vote(
uint256 _pollNum,
VoteType _voteType,
uint256 _voteWeight
) external override onlyWithBalanceNoLess(10000000000000000000) {
require(polls[_pollNum].pollStopped > block.timestamp, "[E-37] - Poll ended.");
if (polls[_pollNum].pollType == PollType.PRIVATE) {
require(verifiedToVote[_pollNum][msg.sender] == true, "[E-38] - You are not verify to vote in this poll.");
}
// Lock tokens
cvnx.lock(msg.sender, _voteWeight);
isTokenLockedInPoll[_pollNum][msg.sender] = true;
uint256 _voterVoteWeightBefore = voted[_pollNum][msg.sender].voteWeight;
// Set vote type
if (_voterVoteWeightBefore > 0) {
require(
voted[_pollNum][msg.sender].voteType == _voteType,
"[E-39] - The voice type does not match the first one."
);
} else {
voted[_pollNum][msg.sender].voteType = _voteType;
}
// Increase vote weight for voter
voted[_pollNum][msg.sender].voteWeight = _voterVoteWeightBefore + _voteWeight;
// Increase vote weight in poll
if (_voteType == VoteType.FOR) {
polls[_pollNum].forWeight += _voteWeight;
} else {
polls[_pollNum].againstWeight += _voteWeight;
}
emit PollVoted(msg.sender, _voteType, _voteWeight);
}
/// @notice Unlock tokens for poll. Poll should be ended.
/// @param _pollNum Poll number
function unlockTokensInPoll(uint256 _pollNum) external override {
require(polls[_pollNum].pollStopped <= block.timestamp, "[E-81] - Poll is not ended.");
require(isTokenLockedInPoll[_pollNum][msg.sender] == true, "[E-82] - Tokens not locked for this poll.");
isTokenLockedInPoll[_pollNum][msg.sender] = false;
// Unlock tokens
cvnx.unlock(msg.sender, voted[_pollNum][msg.sender].voteWeight);
}
/// @notice Stop poll before deadline.
/// @param _pollNum Poll number
function stopPoll(uint256 _pollNum) external override {
require(
owner() == msg.sender || polls[_pollNum].pollOwner == msg.sender,
"[E-91] - Not a contract or poll owner."
);
require(block.timestamp < polls[_pollNum].pollDeadline, "[E-92] - Poll ended.");
polls[_pollNum].pollStopped = uint64(block.timestamp);
emit PollStop(_pollNum, block.timestamp);
}
/// @notice Return poll status (PENDING, APPROVED, REJECTED, DRAW).
/// @param _pollNum Poll number
/// @return Poll number and status
function getPollStatus(uint256 _pollNum) external view override returns (uint256, PollStatus) {
if (polls[_pollNum].pollStopped > block.timestamp) {
return (_pollNum, PollStatus.PENDING);
}
uint256 _forWeight = polls[_pollNum].forWeight;
uint256 _againstWeight = polls[_pollNum].againstWeight;
if (_forWeight > _againstWeight) {
return (_pollNum, PollStatus.APPROVED);
} else if (_forWeight < _againstWeight) {
return (_pollNum, PollStatus.REJECTED);
} else {
return (_pollNum, PollStatus.DRAW);
}
}
/// @notice Return the poll expiration timestamp.
/// @param _pollNum Poll number
/// @return Poll deadline
function getPollExpirationTime(uint256 _pollNum) external view override returns (uint64) {
return polls[_pollNum].pollDeadline;
}
/// @notice Return the poll stop timestamp.
/// @param _pollNum Poll number
/// @return Poll stop time
function getPollStopTime(uint256 _pollNum) external view override returns (uint64) {
return polls[_pollNum].pollStopped;
}
/// @notice Return the complete list of polls an address has voted in.
/// @param _voter Voter address
/// @return Index - poll number. True - if address voted in poll
function getPollHistory(address _voter) external view override returns (bool[] memory) {
uint256 _pollsCount = polls.length;
bool[] memory _pollNums = new bool[](_pollsCount);
for (uint256 i = 0; i < _pollsCount; i++) {
if (voted[i][_voter].voteWeight > 0) {
_pollNums[i] = true;
}
}
return _pollNums;
}
/// @notice Return the vote info for a given poll for an address.
/// @param _pollNum Poll number
/// @param _voter Voter address
/// @return Info about voter vote
function getPollInfoForVoter(uint256 _pollNum, address _voter) external view override returns (Vote memory) {
return voted[_pollNum][_voter];
}
/// @notice Checks if a user address has voted for a specific poll.
/// @param _pollNum Poll number
/// @param _voter Voter address
/// @return True if address voted in poll
function getIfUserHasVoted(uint256 _pollNum, address _voter) external view override returns (bool) {
return voted[_pollNum][_voter].voteWeight > 0;
}
/// @notice Return the amount of tokens that are locked for a given voter address.
/// @param _voter Voter address
/// @return Poll number
function getLockedAmount(address _voter) external view override returns (uint256) {
return cvnx.lockedAmount(_voter);
}
/// @notice Return the amount of locked tokens of the specific poll.
/// @param _pollNum Poll number
/// @param _voter Voter address
/// @return Locked tokens amount for specific poll
function getPollLockedAmount(uint256 _pollNum, address _voter) external view override returns (uint256) {
if (isTokenLockedInPoll[_pollNum][_voter]) {
return voted[_pollNum][_voter].voteWeight;
} else {
return 0;
}
}
/// @notice Create poll process.
/// @param _pollType Poll type
/// @param _pollDeadline Poll deadline adn stop timestamp
/// @param _pollInfo Poll info
/// @return Poll number
function _createPoll(
PollType _pollType,
uint64 _pollDeadline,
string memory _pollInfo
) private onlyWithBalanceNoLess(0) returns (uint256) {
require(_pollDeadline > block.timestamp, "[E-41] - The deadline must be longer than the current time.");
require(isAvailableToCreate, "[E-42] - Possibility to create new poll is disabled.");
Poll memory _poll = Poll(_pollDeadline, _pollDeadline, _pollType, msg.sender, _pollInfo, 0, 0);
uint256 _pollNum = polls.length;
polls.push(_poll);
emit PollCreated(_pollNum);
return _pollNum;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/// @notice ICVNXGovernance interface for CVNXGovernance contract.
interface ICVNXGovernance {
enum PollType {PROPOSAL, EXECUTIVE, EVENT, PRIVATE}
enum PollStatus {PENDING, APPROVED, REJECTED, DRAW}
enum VoteType {FOR, AGAINST}
/// @notice Poll structure.
struct Poll {
uint64 pollDeadline;
uint64 pollStopped;
PollType pollType;
address pollOwner;
string pollInfo;
uint256 forWeight;
uint256 againstWeight;
}
/// @notice Address vote structure.
struct Vote {
VoteType voteType;
uint256 voteWeight;
}
/// @notice Return variable isAvailableToCreate.
function getIsAvailableToCreate() external view returns (bool);
/// @notice Enable or disable possibility to create new poll in contract.
function setIsAvailableToCreate() external;
/// @notice Create PROPOSAL poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
function createProposalPoll(uint64 _pollDeadline, string memory _pollInfo) external;
/// @notice Create EXECUTIVE poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
function createExecutivePoll(uint64 _pollDeadline, string memory _pollInfo) external;
/// @notice Create EVENT poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
function createEventPoll(uint64 _pollDeadline, string memory _pollInfo) external;
/// @notice Create PRIVATE poll.
/// @param _pollDeadline Poll deadline
/// @param _pollInfo Info about poll
/// @param _verifiedAddresses Array of verified addresses for poll
function createPrivatePoll(
uint64 _pollDeadline,
string memory _pollInfo,
address[] memory _verifiedAddresses
) external;
/// @notice Send tokens as vote in poll. Tokens will be lock.
/// @param _pollNum Poll number
/// @param _voteType Vote type (FOR, AGAINST)
/// @param _voteWeight Vote weight in CVNX tokens
function vote(
uint256 _pollNum,
VoteType _voteType,
uint256 _voteWeight
) external;
/// @notice Unlock tokens for poll. Poll should be ended.
/// @param _pollNum Poll number
function unlockTokensInPoll(uint256 _pollNum) external;
/// @notice Stop poll before deadline.
/// @param _pollNum Poll number
function stopPoll(uint256 _pollNum) external;
/// @notice Return poll status (PENDING, APPROVED, REJECTED, DRAW).
/// @param _pollNum Poll number
/// @return Poll number and status
function getPollStatus(uint256 _pollNum) external view returns (uint256, PollStatus);
/// @notice Return the poll expiration timestamp.
/// @param _pollNum Poll number
/// @return Poll deadline
function getPollExpirationTime(uint256 _pollNum) external view returns (uint64);
/// @notice Return the poll stop timestamp.
/// @param _pollNum Poll number
/// @return Poll stop time
function getPollStopTime(uint256 _pollNum) external view returns (uint64);
/// @notice Return the complete list of polls an address has voted in.
/// @param _voter Voter address
/// @return Index - poll number. True - if address voted in poll
function getPollHistory(address _voter) external view returns (bool[] memory);
/// @notice Return the vote info for a given poll for an address.
/// @param _pollNum Poll number
/// @param _voter Voter address
/// @return Info about voter vote
function getPollInfoForVoter(uint256 _pollNum, address _voter) external view returns (Vote memory);
/// @notice Checks if a user address has voted for a specific poll.
/// @param _pollNum Poll number
/// @param _voter Voter address
/// @return True if address voted in poll
function getIfUserHasVoted(uint256 _pollNum, address _voter) external view returns (bool);
/// @notice Return the amount of tokens that are locked for a given voter address.
/// @param _voter Voter address
/// @return Poll number
function getLockedAmount(address _voter) external view returns (uint256);
/// @notice Return the amount of locked tokens of the specific poll.
/// @param _pollNum Poll number
/// @param _voter Voter address
/// @return Locked tokens amount for specific poll
function getPollLockedAmount(uint256 _pollNum, address _voter) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @notice ICVNX interface for CVNX contract.
interface ICVNX is IERC20 {
/// @notice Mint new CVNX tokens.
/// @param _account Address that receive tokens
/// @param _amount Tokens amount
function mint(address _account, uint256 _amount) external;
/// @notice Lock tokens on holder balance.
/// @param _tokenOwner Token holder
/// @param _tokenAmount Amount to lock
function lock(address _tokenOwner, uint256 _tokenAmount) external;
/// @notice Unlock tokens on holder balance.
/// @param _tokenOwner Token holder
/// @param _tokenAmount Amount to lock
function unlock(address _tokenOwner, uint256 _tokenAmount) external;
/// @notice Swap CVN to CVNX tokens
/// @param _amount Token amount to swap
function swap(uint256 _amount) external returns (bool);
/// @notice Transfer stuck tokens
/// @param _token Token contract address
/// @param _to Receiver address
/// @param _amount Token amount
function transferStuckERC20(
IERC20 _token,
address _to,
uint256 _amount
) external;
/// @notice Set CVNXGovernance contract.
/// @param _address CVNXGovernance contract address
function setCvnxGovernanceContract(address _address) external;
/// @notice Set limit params.
/// @param _percent Percentage of the total balance available for transfer
/// @param _limitAmount Max amount available for transfer
/// @param _period Lock period when user can't transfer tokens
function setLimit(uint256 _percent, uint256 _limitAmount, uint256 _period) external;
/// @notice Add address to 'from' whitelist
/// @param _newAddress New address
function addFromWhitelist(address _newAddress) external;
/// @notice Remove address from 'from' whitelist
/// @param _oldAddress Old address
function removeFromWhitelist(address _oldAddress) external;
/// @notice Add address to 'to' whitelist
/// @param _newAddress New address
function addToWhitelist(address _newAddress) external;
/// @notice Remove address from 'to' whitelist
/// @param _oldAddress Old address
function removeToWhitelist(address _oldAddress) external;
/// @notice Change limit activity status.
function changeLimitActivityStatus() external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ICVNXGovernance.sol";
import "./ICVNX.sol";
/// @notice CVNX token contract.
contract CVNX is ICVNX, ERC20("CVNX", "CVNX"), Ownable {
event TokenLocked(uint256 indexed amount, address tokenOwner);
event TokenUnlocked(uint256 indexed amount, address tokenOwner);
/// @notice Governance contract.
ICVNXGovernance public cvnxGovernanceContract;
IERC20Metadata public cvnContract;
struct Limit {
uint256 percent;
uint256 limitAmount;
uint256 period;
}
Limit public limit;
bool public isLimitsActive;
mapping(address => uint256) public addressToEndLockTimestamp;
mapping(address => bool) public fromLimitWhitelist;
mapping(address => bool) public toLimitWhitelist;
/// @notice Locked token amount for each address.
mapping(address => uint256) public lockedAmount;
/// @notice Governance contract created in constructor.
constructor(address _cvnContract) {
uint256 _toMint = 15000000000000000000000000;
_mint(msg.sender, _toMint);
approve(address(this), _toMint);
cvnContract = IERC20Metadata(_cvnContract);
}
/// @notice Modifier describe that call available only from governance contract.
modifier onlyGovContract() {
require(msg.sender == address(cvnxGovernanceContract), "[E-31] - Not a governance contract.");
_;
}
/// @notice Lock tokens on holder balance.
/// @param _tokenOwner Token holder
/// @param _tokenAmount Amount to lock
function lock(address _tokenOwner, uint256 _tokenAmount) external override onlyGovContract {
require(_tokenAmount > 0, "[E-41] - The amount to be locked must be greater than zero.");
uint256 _balance = balanceOf(_tokenOwner);
uint256 _toLock = lockedAmount[_tokenOwner] + _tokenAmount;
require(_toLock <= _balance, "[E-42] - Not enough token on account.");
lockedAmount[_tokenOwner] = _toLock;
emit TokenLocked(_tokenAmount, _tokenOwner);
}
/// @notice Unlock tokens on holder balance.
/// @param _tokenOwner Token holder
/// @param _tokenAmount Amount to lock
function unlock(address _tokenOwner, uint256 _tokenAmount) external override onlyGovContract {
uint256 _lockedAmount = lockedAmount[_tokenOwner];
if (_tokenAmount > _lockedAmount) {
_tokenAmount = _lockedAmount;
}
lockedAmount[_tokenOwner] = _lockedAmount - _tokenAmount;
emit TokenUnlocked(_tokenAmount, _tokenOwner);
}
/// @notice Swap CVN to CVNX tokens
/// @param _amount Token amount to swap
function swap(uint256 _amount) external override returns (bool) {
cvnContract.transferFrom(msg.sender, 0x4e07dc9D1aBCf1335d1EaF4B2e28b45d5892758E, _amount);
uint256 _newAmount = _amount * (10 ** (decimals() - cvnContract.decimals()));
this.transferFrom(owner(), msg.sender, _newAmount);
return true;
}
/// @notice Transfer stuck tokens
/// @param _token Token contract address
/// @param _to Receiver address
/// @param _amount Token amount
function transferStuckERC20(
IERC20 _token,
address _to,
uint256 _amount
) external override onlyOwner {
require(_token.transfer(_to, _amount), "[E-56] - Transfer failed.");
}
/// @notice Set CVNXGovernance contract.
/// @param _address CVNXGovernance contract address
function setCvnxGovernanceContract(address _address) external override onlyOwner {
if (address(cvnxGovernanceContract) != address(0)) {
require(!cvnxGovernanceContract.getIsAvailableToCreate(), "[E-92] - Old governance contract still active.");
}
cvnxGovernanceContract = ICVNXGovernance(_address);
}
/// @notice Mint new CVNX tokens.
/// @param _account Address that receive tokens
/// @param _amount Tokens amount
function mint(address _account, uint256 _amount) external override onlyOwner {
require(totalSupply() + _amount <= 60000000000000000000000000, "[E-71] - Can't mint more.");
_mint(_account, _amount);
}
/// @notice Set limit params.
/// @param _percent Percentage of the total balance available for transfer
/// @param _limitAmount Max amount available for transfer
/// @param _period Lock period when user can't transfer tokens
function setLimit(uint256 _percent, uint256 _limitAmount, uint256 _period) external override onlyOwner {
require(_percent <= getDecimals(), "[E-89] - Percent should be less than 1.");
require(_percent > 0, "[E-90] - Percent can't be a zero.");
require(_limitAmount > 0, "[E-90] - Limit amount can't be a zero.");
limit.percent = _percent;
limit.limitAmount = _limitAmount;
limit.period = _period;
}
/// @notice Add address to 'from' whitelist
/// @param _newAddress New address
function addFromWhitelist(address _newAddress) external override onlyOwner {
fromLimitWhitelist[_newAddress] = true;
}
/// @notice Remove address from 'from' whitelist
/// @param _oldAddress Old address
function removeFromWhitelist(address _oldAddress) external override onlyOwner {
fromLimitWhitelist[_oldAddress] = false;
}
/// @notice Add address to 'to' whitelist
/// @param _newAddress New address
function addToWhitelist(address _newAddress) external override onlyOwner {
toLimitWhitelist[_newAddress] = true;
}
/// @notice Remove address from 'to' whitelist
/// @param _oldAddress Old address
function removeToWhitelist(address _oldAddress) external override onlyOwner {
toLimitWhitelist[_oldAddress] = false;
}
/// @notice Change limit activity status.
function changeLimitActivityStatus() external override onlyOwner {
isLimitsActive = !isLimitsActive;
}
/// @notice Check that locked amount less then transfer amount.
/// @notice Check limits.
/// @param _from From address
/// @param _to To address
/// @param _amount Token amount
function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal override {
if (_from != address(0)) {
uint256 _availableAmount = balanceOf(_from) - lockedAmount[_from];
require(_availableAmount >= _amount, "[E-61] - Transfer amount exceeds available tokens.");
if (isLimitsActive && fromLimitWhitelist[_from] == false && toLimitWhitelist[_to] == false) {
require(block.timestamp > addressToEndLockTimestamp[_from], "[E-62] - Tokens are locked until the end of the period.");
require(_amount <= limit.limitAmount, "[E-63] - The maximum limit has been reached.");
require(_amount <= _availableAmount * limit.percent / getDecimals(), "[E-64] - The maximum limit has been reached.");
addressToEndLockTimestamp[_from] = block.timestamp + limit.period;
}
}
}
function getDecimals() private pure returns (uint256) {
return 10 ** 27;
}
}
// 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;
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/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 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 { }
}
// 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;
}
}
|
Mint new CVNX tokens. _account Address that receive tokens _amount Tokens amount
|
function mint(address _account, uint256 _amount) external override onlyOwner {
require(totalSupply() + _amount <= 60000000000000000000000000, "[E-71] - Can't mint more.");
_mint(_account, _amount);
}
| 10,119,312 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
/**
* @title Tradeable Token
* @dev Standard Token which can be trade within the contract.
* we support buy() and sell() function in a simpilified bancor algorithm which CW = 50%.
*/
contract TradeableToken is StandardToken {
uint256 public tokenPriceInitial_ = 0.0000001 ether; // per wei
uint256 public tokenPriceIncremental_ = 0.00000001 ether; // per wei
uint256 public depositPool_ = 0 ether;
uint256 constant public OFFSET = 2**64;
//
// Event
event OnBuy(
address indexed customerAddress,
uint256 incomingether,
uint256 tokensMinted
);
event OnSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 etherEarned
);
event OnWithdraw(
address indexed customerAddress,
uint256 etherWithdrawn
);
// Internal Function
function _mint(address _customerAddress, uint256 _amount) internal {
require(_amount > 0 && (SafeMath.add(_amount, totalSupply_) > totalSupply_));
totalSupply_ = SafeMath.add(totalSupply_, _amount);
balances[_customerAddress] = SafeMath.add(balances[_customerAddress], _amount);
}
function _burn(address _customerAddress, uint256 _amount) internal {
require(_amount > 0 && (SafeMath.sub(_amount, totalSupply_) < totalSupply_));
totalSupply_ = SafeMath.sub(totalSupply_, _amount);
balances[_customerAddress] = SafeMath.sub(balances[_customerAddress], _amount);
}
function _buy(uint256 _incomingEther) internal returns(uint256) {
address _customerAddress = msg.sender;
depositPool_ = SafeMath.add(depositPool_, _incomingEther);
uint256 _amountOfTokens = etherToTokens_(_incomingEther);
_mint(_customerAddress, _amountOfTokens);
emit OnBuy(_customerAddress, _incomingEther, _amountOfTokens);
return _amountOfTokens;
}
function _sell(uint256 _incomingToken) internal returns(uint256) {
address _customerAddress = msg.sender;
require(_incomingToken <= balances[_customerAddress]);
uint256 _amountOfEther = tokensToEther_(_incomingToken);
_burn(_customerAddress, _incomingToken);
depositPool_ = SafeMath.sub(depositPool_, _amountOfEther);
_customerAddress.transfer(_amountOfEther);
emit OnSell(msg.sender, _incomingToken, _amountOfEther);
return _amountOfEther;
}
// Read Only
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(totalSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ether = tokensToEther_(1e18);
return _ether;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(totalSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ether = tokensToEther_(1e18);
return _ether;
}
}
/**
* @dev Gets the token price
* @return uint256 representing the token price
*/
function getPrice() public view returns (uint256) {
if(totalSupply_ == 0){
return tokenPriceInitial_;
} else {
return SafeMath.div(SafeMath.mul(depositPool_, 2e18), totalSupply_);
}
}
// Public Function
/**
* @dev Buy some token
*/
function buy() public payable {
_buy(msg.value);
}
/**
* @dev Sell some token
*/
function sell(uint256 _amount) public {
_sell(_amount);
}
/**
* @dev Fallback function to handle ether that was send straight to the contract
*/
function() public payable {
_buy(msg.value);
}
/**
* @dev calculate how many token will be minted when sending amount of ether.
* We use a simplified bancor algorithm which CW = 50% to deal with this.
* https://storage.googleapis.com/website-bancor/2018/04/01ba8253-bancor_protocol_whitepaper_en.pdf
* @return uint256 representing the amount of token will be minted.
*/
function etherToTokens_(uint256 _ether)
public
view
returns(uint256 _tokens)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ether * 1e18))
+
(((tokenPriceIncremental_)**2)*(totalSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*totalSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(totalSupply_)
;
// require(_tokensReceived == etherToTokens2_(_ether));
return _tokensReceived;
}
/**
* @dev This should be a better implementation.
*/
function etherToTokens2_(uint256 _ether)
public
view
returns(uint256)
{
uint256 _tokenPrice = getPrice() * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPrice**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ether * 1e18))
)
), _tokenPrice
)
)/(tokenPriceIncremental_)
)
;
return _tokensReceived;
}
/**
* @dev be aware, due to precision issue this two function didn't have consistency with each other.
* @return uint256 representing the ether which will be release.
*/
function tokensToEther_(uint256 _tokens)
internal
view
returns(uint256 _ether)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 totalSupply_ = (totalSupply() + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (totalSupply_/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
/**
* @dev calculate sqrt() via Newton's method.
* https://en.wikipedia.org/wiki/Fast_inverse_square_root#Newton's_method
*/
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
|
Read Only Return the buy price of 1 individual token./ our calculation relies on the token supply, so we need supply. Doh.
|
function sellPrice()
public
view
returns(uint256)
{
if(totalSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
uint256 _ether = tokensToEther_(1e18);
return _ether;
}
}
| 14,067,035 |
pragma solidity ^0.4.23;
/*
Options Exchange
========================
An Exchange for American Options.
An American Option is a contract between its Buyer and its Seller, giving the Buyer the ability
to buy (or sell) an Asset at a specified Strike Price any time before a specified time (Maturation).
Authors: /u/Cintix and /u/Hdizzle83
*/
// Using the SafeMath Library helps prevent integer overflow bugs.
library SafeMath {
function mul(uint256 a, uint256 b) pure internal returns (uint256) {
uint256 c = a * b;
assert((a == 0) || (c / a == b));
return c;
}
function div(uint256 a, uint256 b) pure internal returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) pure internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) pure internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// Options can only be created for tokens adhering to the ERC20 Interface.
// ERC20 Interface: https://github.com/ethereum/EIPs/issues/20
contract Token {
function transferFrom(address from, address to, uint256 value) public returns (bool success) {}
function transfer(address to, uint256 value) public returns (bool success) {}
}
// An Option is a bet between two users on the relative price of two assets on a given date.
// The Seller locks amountLocked of assetLocked in the Option in exchange for immediate payment of amountPremium of assetPremium from the Buyer.
// The Buyer is then free to exercise the Option by trading amountTraded of assetTraded for the locked funds.
// The ratio of amountTraded and amountLocked is called the Strike Price.
// At the closing date (Maturation) or when the Buyer exercises the Option, the Option's funds are sent back to the Seller.
contract OptionsExchange {
using SafeMath for uint256;
// Admin takes a 1% cut of each purchased Option's Premium, stored as a ratio with 1 ether as the denominator.
uint256 public fee_ratio = 10 ** 16;
// Admin is initialized to the contract creator.
address public admin = msg.sender;
// User balances are stored as userBalance[user][asset], where ETH is stored as address 0.
mapping (address => mapping(address => uint256)) public userBalance;
// Onchain Option data indicates the current Buyer and Seller along with corresponding nonces used to invalidate old offchain orders.
// The Seller and Buyer addresses and their nonces take up two 32 byte storage slots, making up the only onchain data for each Option.
// When both storage slots are zero (i.e. uninitialized), the Option is Available or Invalid.
// When both storage slots are non-zero, the Option is Live or Matured.
// When only the Buyer storage slot is non-zero, the Option is Closed.
// When only the Seller storage slot is non-zero, the Option is Exercised or Cancelled.
// When only nonceSeller is non-zero, the Option is Cancelled.
// When an Option is Live, nonceSeller and nonceBuyer store how many users have been the Option's Seller and Buyer, respectively.
// The storage slots are zeroed out when the Option is Closed or Exercised to refund 10,000 gas.
struct optionDatum {
address seller;
uint96 nonceSeller;
address buyer;
uint96 nonceBuyer;
}
// To reduce onchain storage, Options are indexed by a hash of their offchain parameters, optionHash.
mapping (bytes32 => optionDatum) public optionData;
// Possible states an Option (or its offchain order) can be in.
// Options implicitly store locked funds when they're Live or Matured.
enum optionStates {
Invalid, // Option parameters are invalid.
Available, // Option hasn't been created or filled yet.
Cancelled, // Option's initial offchain order has been cancelled by the Maker.
Live, // Option contains implicitly stored funds, can be resold or exercised any time before its Maturation time.
Exercised, // Option has been exercised by its buyer, withdrawing its implicitly stored funds.
Matured, // Option still contains implicitly stored funds but has passed its Maturation time and is ready to be closed.
Closed // Option has been closed by its Seller, who has withdrawn its implicitly stored funds.
}
// Events emitted by the contract for use in tracking exchange activity.
// For Deposits and Withdrawals, ETH balances are stored as an asset with address 0.
event Deposit(address indexed user, address indexed asset, uint256 amount);
event Withdrawal(address indexed user, address indexed asset, uint256 amount);
event OrderFilled(bytes32 indexed optionHash,
address indexed maker,
address indexed taker,
address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation,
uint256[2] amountPremium_expiration,
address assetPremium,
bool makerIsSeller,
uint96 nonce);
event OrderCancelled(bytes32 indexed optionHash, bool bySeller, uint96 nonce);
event OptionExercised(bytes32 indexed optionHash, address indexed buyer, address indexed seller);
event OptionClosed(bytes32 indexed optionHash, address indexed seller);
event UserBalanceUpdated(address indexed user, address indexed asset, uint256 newBalance);
// Allow the admin to transfer ownership.
function changeAdmin(address _admin) external {
require(msg.sender == admin);
admin = _admin;
}
// Users must first deposit assets into the Exchange in order to create, purchase, or exercise Options.
// ETH balances are stored as an asset with address 0.
function depositETH() external payable {
userBalance[msg.sender][0] = userBalance[msg.sender][0].add(msg.value);
emit Deposit(msg.sender, 0, msg.value);
emit UserBalanceUpdated(msg.sender, 0, userBalance[msg.sender][0]);
}
// Users can withdraw any amount of ETH up to their current balance.
function withdrawETH(uint256 amount) external {
require(userBalance[msg.sender][0] >= amount);
userBalance[msg.sender][0] = userBalance[msg.sender][0].sub(amount);
msg.sender.transfer(amount);
emit Withdrawal(msg.sender, 0, amount);
emit UserBalanceUpdated(msg.sender, 0, userBalance[msg.sender][0]);
}
// To deposit tokens, users must first "approve" the transfer in the token contract.
// Users must first deposit assets into the Exchange in order to create, purchase, or exercise Options.
function depositToken(address token, uint256 amount) external {
require(Token(token).transferFrom(msg.sender, this, amount));
userBalance[msg.sender][token] = userBalance[msg.sender][token].add(amount);
emit Deposit(msg.sender, token, amount);
emit UserBalanceUpdated(msg.sender, token, userBalance[msg.sender][token]);
}
// Users can withdraw any amount of a given token up to their current balance.
function withdrawToken(address token, uint256 amount) external {
require(userBalance[msg.sender][token] >= amount);
userBalance[msg.sender][token] = userBalance[msg.sender][token].sub(amount);
require(Token(token).transfer(msg.sender, amount));
emit Withdrawal(msg.sender, token, amount);
emit UserBalanceUpdated(msg.sender, token, userBalance[msg.sender][token]);
}
// Transfer funds from one user's balance to another's. Not externally callable.
function transferUserToUser(address from, address to, address asset, uint256 amount) private {
require(userBalance[from][asset] >= amount);
userBalance[from][asset] = userBalance[from][asset].sub(amount);
userBalance[to][asset] = userBalance[to][asset].add(amount);
emit UserBalanceUpdated(from, asset, userBalance[from][asset]);
emit UserBalanceUpdated(to, asset, userBalance[to][asset]);
}
// Hashes an Option's parameters for use in looking up information about the Option. Callable internally and externally.
// Variables are grouped into arrays as a workaround for the "too many local variables" problem.
// Instead of directly encoding the asset exchange rate (Strike Price), it is instead implicitly
// stored as the ratio of amountLocked, the amount of assetLocked stored in the Option, and amountTraded,
// the amount of assetTraded needed to exercise the Option.
function getOptionHash(address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation) pure public returns(bytes32) {
bytes32 optionHash = keccak256(assetLocked_assetTraded_firstMaker[0],
assetLocked_assetTraded_firstMaker[1],
assetLocked_assetTraded_firstMaker[2],
amountLocked_amountTraded_maturation[0],
amountLocked_amountTraded_maturation[1],
amountLocked_amountTraded_maturation[2]);
return optionHash;
}
// Hashes an Order's parameters for use in ecrecover. Callable internally and externally.
function getOrderHash(bytes32 optionHash,
uint256[2] amountPremium_expiration,
address assetPremium,
bool makerIsSeller,
uint96 nonce) view public returns(bytes32) {
// A hash of the Order's information which was signed by the Maker to create the offchain order.
bytes32 orderHash = keccak256("\x19Ethereum Signed Message:\n32",
keccak256(address(this),
optionHash,
amountPremium_expiration[0],
amountPremium_expiration[1],
assetPremium,
makerIsSeller,
nonce));
return orderHash;
}
// Computes the current state of an Option given its parameters. Callable internally and externally.
function getOptionState(address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation) view public returns(optionStates) {
// Tokens must be different for Option to be Valid.
if(assetLocked_assetTraded_firstMaker[0] == assetLocked_assetTraded_firstMaker[1]) return optionStates.Invalid;
// Options must have a non-zero amount of locked assets to be Valid.
if(amountLocked_amountTraded_maturation[0] == 0) return optionStates.Invalid;
// Exercising an Option must require trading a non-zero amount of assets.
if(amountLocked_amountTraded_maturation[1] == 0) return optionStates.Invalid;
// Options must reach Maturation between 2018 and 2030 to be Valid.
if(amountLocked_amountTraded_maturation[2] < 1514764800) return optionStates.Invalid;
if(amountLocked_amountTraded_maturation[2] > 1893456000) return optionStates.Invalid;
bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation);
address seller = optionData[optionHash].seller;
uint96 nonceSeller = optionData[optionHash].nonceSeller;
address buyer = optionData[optionHash].buyer;
if(seller == 0x0) {
// Check if the Option's offchain order was cancelled.
if(nonceSeller != 0) return optionStates.Cancelled;
// If both Buyer and Seller are still 0, Option is Available, even if it's past Maturation.
if(buyer == 0x0) return optionStates.Available;
// If Seller is 0 and Buyer is non-zero, Option must have been Closed.
return optionStates.Closed;
}
// If Seller is non-zero and Buyer is 0, Option must have been Exercised.
if(buyer == 0x0) return optionStates.Exercised;
// If Seller and Buyer are both non-zero and the Option hasn't passed Maturation, it's Live.
if(now < amountLocked_amountTraded_maturation[2]) return optionStates.Live;
// Otherwise, the Option must have Matured.
return optionStates.Matured;
}
// Transfer payment from an Option's Buyer to the Seller less the 1% fee sent to the admin. Not externally callable.
function payForOption(address buyer, address seller, address assetPremium, uint256 amountPremium) private {
uint256 fee = (amountPremium.mul(fee_ratio)).div(1 ether);
transferUserToUser(buyer, seller, assetPremium, amountPremium.sub(fee));
transferUserToUser(buyer, admin, assetPremium, fee);
}
// Allows a Taker to fill an offchain Option order created by a Maker.
// Transitions new Options from Available to Live, depositing its implicitly stored locked funds.
// Maintains state of existing Options as Live, without affecting their implicitly stored locked funds.
function fillOptionOrder(address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation,
uint256[2] amountPremium_expiration,
address assetPremium,
bool makerIsSeller,
uint96 nonce,
uint8 v,
bytes32[2] r_s) external {
// Verify offchain order hasn't expired.
require(now < amountPremium_expiration[1]);
bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation);
// A hash of the Order's information which was signed by the Maker to create the offchain order.
bytes32 orderHash = getOrderHash(optionHash, amountPremium_expiration, assetPremium, makerIsSeller, nonce);
// A nonce of zero corresponds to creating a new Option, while nonzero means reselling an old one.
if(nonce == 0) {
// Option must be Available, which means it is valid, unfilled, and uncancelled.
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Available);
// Option must not already be past its Maturation time.
require(now < amountLocked_amountTraded_maturation[2]);
// Verify the Maker's offchain order is valid by checking whether it was signed by the first Maker.
require(ecrecover(orderHash, v, r_s[0], r_s[1]) == assetLocked_assetTraded_firstMaker[2]);
// Set the Option's Buyer and Seller and initialize the nonces to 1, marking the Option as Live.
// Ternary operator to assign the Seller and Buyer from the Maker and Taker: (<conditional> ? <if-true> : <if-false>)
optionData[optionHash].seller = makerIsSeller ? assetLocked_assetTraded_firstMaker[2] : msg.sender;
optionData[optionHash].nonceSeller = 1;
optionData[optionHash].buyer = makerIsSeller ? msg.sender : assetLocked_assetTraded_firstMaker[2];
optionData[optionHash].nonceBuyer = 1;
// The Buyer pays the Seller the premium for the Option.
payForOption(optionData[optionHash].buyer, optionData[optionHash].seller, assetPremium, amountPremium_expiration[0]);
// Lock amountLocked of the Seller's assetLocked in implicit storage as specified by the Option parameters.
require(userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]] >= amountLocked_amountTraded_maturation[0]);
userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]] = userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]].sub(amountLocked_amountTraded_maturation[0]);
emit UserBalanceUpdated(optionData[optionHash].seller, assetLocked_assetTraded_firstMaker[0], userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]]);
emit OrderFilled(optionHash,
assetLocked_assetTraded_firstMaker[2],
msg.sender,
assetLocked_assetTraded_firstMaker,
amountLocked_amountTraded_maturation,
amountPremium_expiration,
assetPremium,
makerIsSeller,
nonce);
} else {
// Option must be Live, which means this order is a resale by the current buyer or seller.
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Live);
// If the Maker is the Seller, they're buying back out their locked asset.
// Otherwise, the Maker is the Buyer and they're reselling their ability to exercise the Option.
if(makerIsSeller) {
// Verify the nonce of the Maker's offchain order matches to ensure the order isn't old or cancelled.
require(optionData[optionHash].nonceSeller == nonce);
// Verify the Maker's offchain order is valid by checking whether it was signed by the Maker.
require(ecrecover(orderHash, v, r_s[0], r_s[1]) == optionData[optionHash].seller);
// The Maker pays the Taker the premium for buying out their locked asset.
payForOption(optionData[optionHash].seller, msg.sender, assetPremium, amountPremium_expiration[0]);
// The Taker directly sends the Maker an amount equal to the Maker's locked assets, replacing them as the Seller.
transferUserToUser(msg.sender, optionData[optionHash].seller, assetLocked_assetTraded_firstMaker[0], amountLocked_amountTraded_maturation[0]);
// Update the Option's Seller to be the Taker and increment the nonce to prevent double-filling.
optionData[optionHash].seller = msg.sender;
optionData[optionHash].nonceSeller += 1;
emit OrderFilled(optionHash,
optionData[optionHash].seller,
msg.sender,
assetLocked_assetTraded_firstMaker,
amountLocked_amountTraded_maturation,
amountPremium_expiration,
assetPremium,
makerIsSeller,
nonce);
} else {
// Verify the nonce of the Maker's offchain order matches to ensure the order isn't old or cancelled.
require(optionData[optionHash].nonceBuyer == nonce);
// Verify the Maker's offchain order is valid by checking whether it was signed by the Maker.
require(ecrecover(orderHash, v, r_s[0], r_s[1]) == optionData[optionHash].buyer);
// The Taker pays the Maker the premium for the ability to exercise the Option.
payForOption(msg.sender, optionData[optionHash].buyer, assetPremium, amountPremium_expiration[0]);
// Update the Option's Buyer to be the Taker and increment the nonce to prevent double-filling.
optionData[optionHash].buyer = msg.sender;
optionData[optionHash].nonceBuyer += 1;
emit OrderFilled(optionHash,
optionData[optionHash].buyer,
msg.sender,
assetLocked_assetTraded_firstMaker,
amountLocked_amountTraded_maturation,
amountPremium_expiration,
assetPremium,
makerIsSeller,
nonce);
}
}
}
// Allows a Maker to cancel their offchain Option order early (i.e. before its expiration).
function cancelOptionOrder(address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation,
bool makerIsSeller) external {
optionStates state = getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation);
// Option must be Available or Live. Orders can't be filled in any other state.
require(state == optionStates.Available || state == optionStates.Live);
bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation);
// If the Option is Available, the first order hasn't been filled yet.
if(state == optionStates.Available) {
// Only allow the Maker to cancel their own offchain Option order.
require(msg.sender == assetLocked_assetTraded_firstMaker[2]);
emit OrderCancelled(optionHash, makerIsSeller, 0);
// Mark the Option as Cancelled by setting the Seller nonce nonzero while the Seller is still 0x0.
optionData[optionHash].nonceSeller = 1;
} else {
// Live Options can be resold by either the Buyer or the Seller.
if(makerIsSeller) {
// Only allow the Maker to cancel their own offchain Option order.
require(msg.sender == optionData[optionHash].seller);
emit OrderCancelled(optionHash, makerIsSeller, optionData[optionHash].nonceSeller);
// Invalidate the old offchain order by incrementing the Maker's nonce.
optionData[optionHash].nonceSeller += 1;
} else {
// Only allow the Maker to cancel their own offchain Option order.
require(msg.sender == optionData[optionHash].buyer);
emit OrderCancelled(optionHash, makerIsSeller, optionData[optionHash].nonceBuyer);
// Invalidate the old offchain order by incrementing the Maker's nonce.
optionData[optionHash].nonceBuyer += 1;
}
}
}
// Allow an Option's Buyer to exercise the Option, trading amountTraded of assetTraded to the Option for amountLocked of assetLocked.
// The traded funds are sent directly to the Seller so they don't need to close it afterwards.
// Transitions an Option from Live to Exercised, withdrawing its implicitly stored locked funds.
function exerciseOption(address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation) external {
// Option must be Live, which means it's been filled and hasn't passed its trading deadline (Maturation).
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Live);
bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation);
address buyer = optionData[optionHash].buyer;
address seller = optionData[optionHash].seller;
// Only allow the current Buyer to exercise the Option.
require(msg.sender == buyer);
// The Buyer sends the Seller the traded assets as specified by the Option parameters.
transferUserToUser(buyer, seller, assetLocked_assetTraded_firstMaker[1], amountLocked_amountTraded_maturation[1]);
// Mark the Option as Exercised by zeroing out the Buyer and the corresponding nonce.
delete optionData[optionHash].buyer;
delete optionData[optionHash].nonceBuyer;
// The Buyer receives the implicitly stored locked assets as specified by the Option parameters.
userBalance[buyer][assetLocked_assetTraded_firstMaker[0]] = userBalance[buyer][assetLocked_assetTraded_firstMaker[0]].add(amountLocked_amountTraded_maturation[0]);
emit UserBalanceUpdated(buyer, assetLocked_assetTraded_firstMaker[0], userBalance[buyer][assetLocked_assetTraded_firstMaker[0]]);
emit OptionExercised(optionHash, buyer, seller);
}
// Allows an Option's Seller to withdraw their funds after the Option's Maturation.
// Transitions an Option from Matured to Closed, withdrawing its implicitly stored locked funds.
function closeOption(address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation) external {
// Option must have Matured, which means it's filled, unexercised, and has passed its Maturation time.
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Matured);
bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation);
address seller = optionData[optionHash].seller;
// Only allow the Seller to close their own Option.
require(msg.sender == seller);
// Mark the Option as Closed by zeroing out the Seller and the corresponding nonce.
delete optionData[optionHash].seller;
delete optionData[optionHash].nonceSeller;
// Transfer the Option's implicitly stored locked funds back to the Seller.
userBalance[seller][assetLocked_assetTraded_firstMaker[0]] = userBalance[seller][assetLocked_assetTraded_firstMaker[0]].add(amountLocked_amountTraded_maturation[0]);
emit UserBalanceUpdated(seller, assetLocked_assetTraded_firstMaker[0], userBalance[seller][assetLocked_assetTraded_firstMaker[0]]);
emit OptionClosed(optionHash, seller);
}
function() payable external {
revert();
}
}
|
Allows a Taker to fill an offchain Option order created by a Maker. Transitions new Options from Available to Live, depositing its implicitly stored locked funds. Maintains state of existing Options as Live, without affecting their implicitly stored locked funds. Verify offchain order hasn&39;t expired. A hash of the Order&39;s information which was signed by the Maker to create the offchain order. A nonce of zero corresponds to creating a new Option, while nonzero means reselling an old one. Option must be Available, which means it is valid, unfilled, and uncancelled. Option must not already be past its Maturation time. Verify the Maker&39;s offchain order is valid by checking whether it was signed by the first Maker. Set the Option&39;s Buyer and Seller and initialize the nonces to 1, marking the Option as Live. Ternary operator to assign the Seller and Buyer from the Maker and Taker: (<conditional> ? <if-true> : <if-false>) The Buyer pays the Seller the premium for the Option. Lock amountLocked of the Seller&39;s assetLocked in implicit storage as specified by the Option parameters. Option must be Live, which means this order is a resale by the current buyer or seller. If the Maker is the Seller, they&39;re buying back out their locked asset. Otherwise, the Maker is the Buyer and they&39;re reselling their ability to exercise the Option. Verify the nonce of the Maker&39;s offchain order matches to ensure the order isn&39;t old or cancelled. Verify the Maker&39;s offchain order is valid by checking whether it was signed by the Maker. The Maker pays the Taker the premium for buying out their locked asset. The Taker directly sends the Maker an amount equal to the Maker&39;s locked assets, replacing them as the Seller. Update the Option&39;s Seller to be the Taker and increment the nonce to prevent double-filling. Verify the nonce of the Maker&39;s offchain order matches to ensure the order isn&39;t old or cancelled. Verify the Maker&39;s offchain order is valid by checking whether it was signed by the Maker. The Taker pays the Maker the premium for the ability to exercise the Option. Update the Option&39;s Buyer to be the Taker and increment the nonce to prevent double-filling.
|
function fillOptionOrder(address[3] assetLocked_assetTraded_firstMaker,
uint256[3] amountLocked_amountTraded_maturation,
uint256[2] amountPremium_expiration,
address assetPremium,
bool makerIsSeller,
uint96 nonce,
uint8 v,
bytes32[2] r_s) external {
require(now < amountPremium_expiration[1]);
bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation);
bytes32 orderHash = getOrderHash(optionHash, amountPremium_expiration, assetPremium, makerIsSeller, nonce);
if(nonce == 0) {
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Available);
require(now < amountLocked_amountTraded_maturation[2]);
require(ecrecover(orderHash, v, r_s[0], r_s[1]) == assetLocked_assetTraded_firstMaker[2]);
optionData[optionHash].seller = makerIsSeller ? assetLocked_assetTraded_firstMaker[2] : msg.sender;
optionData[optionHash].nonceSeller = 1;
optionData[optionHash].buyer = makerIsSeller ? msg.sender : assetLocked_assetTraded_firstMaker[2];
optionData[optionHash].nonceBuyer = 1;
payForOption(optionData[optionHash].buyer, optionData[optionHash].seller, assetPremium, amountPremium_expiration[0]);
require(userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]] >= amountLocked_amountTraded_maturation[0]);
userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]] = userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]].sub(amountLocked_amountTraded_maturation[0]);
emit UserBalanceUpdated(optionData[optionHash].seller, assetLocked_assetTraded_firstMaker[0], userBalance[optionData[optionHash].seller][assetLocked_assetTraded_firstMaker[0]]);
emit OrderFilled(optionHash,
assetLocked_assetTraded_firstMaker[2],
msg.sender,
assetLocked_assetTraded_firstMaker,
amountLocked_amountTraded_maturation,
amountPremium_expiration,
assetPremium,
makerIsSeller,
nonce);
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Live);
if(makerIsSeller) {
require(optionData[optionHash].nonceSeller == nonce);
require(ecrecover(orderHash, v, r_s[0], r_s[1]) == optionData[optionHash].seller);
payForOption(optionData[optionHash].seller, msg.sender, assetPremium, amountPremium_expiration[0]);
transferUserToUser(msg.sender, optionData[optionHash].seller, assetLocked_assetTraded_firstMaker[0], amountLocked_amountTraded_maturation[0]);
optionData[optionHash].seller = msg.sender;
optionData[optionHash].nonceSeller += 1;
emit OrderFilled(optionHash,
optionData[optionHash].seller,
msg.sender,
assetLocked_assetTraded_firstMaker,
amountLocked_amountTraded_maturation,
amountPremium_expiration,
assetPremium,
makerIsSeller,
nonce);
require(optionData[optionHash].nonceBuyer == nonce);
require(ecrecover(orderHash, v, r_s[0], r_s[1]) == optionData[optionHash].buyer);
payForOption(msg.sender, optionData[optionHash].buyer, assetPremium, amountPremium_expiration[0]);
optionData[optionHash].buyer = msg.sender;
optionData[optionHash].nonceBuyer += 1;
emit OrderFilled(optionHash,
optionData[optionHash].buyer,
msg.sender,
assetLocked_assetTraded_firstMaker,
amountLocked_amountTraded_maturation,
amountPremium_expiration,
assetPremium,
makerIsSeller,
nonce);
}
}
}
| 10,538,693 |
// Sources flattened with buidler v1.4.3 https://buidler.dev
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 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} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
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);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File @openzeppelin/contracts/math/[email protected]
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;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.6.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;
}
}
// File @openzeppelin/contracts/GSN/[email protected]
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;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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;
}
}
// File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global 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.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 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);
}
// File @openzeppelin/contracts/introspection/[email protected]
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);
}
// File @openzeppelin/contracts/introspection/[email protected]
pragma solidity ^0.6.0;
/**
* @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;
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, token receiver
* @dev See https://eips.ethereum.org/EIPS/eip-1155
* Interface for any contract that wants to support transfers from ERC1155 asset contracts.
* Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type.
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
* This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
* This function MUST revert if it rejects the transfer.
* Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
* @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 `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types.
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
* This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
* This function MUST revert if it rejects the transfer(s).
* Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
* @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)"))`
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
abstract contract ERC1155TokenReceiver is IERC1155TokenReceiver, ERC165 {
// bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 internal constant _ERC1155_RECEIVED = 0xf23a6e61;
// bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
bytes4 internal constant _ERC1155_BATCH_RECEIVED = 0xbc197c81;
bytes4 internal constant _ERC1155_REJECTED = 0xffffffff;
constructor() internal {
_registerInterface(type(IERC1155TokenReceiver).interfaceId);
}
}
// File @animoca/ethereum-contracts-nft_staking/contracts/staking/[email protected]
pragma solidity 0.6.8;
/**
* @title NFT Staking
* Distribute ERC20 rewards over discrete-time schedules for the staking of NFTs.
* This contract is designed on a self-service model, where users will stake NFTs, unstake NFTs and claim rewards through their own transactions only.
*/
abstract contract NftStaking is ERC1155TokenReceiver, Ownable {
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
event RewardsAdded(uint256 startPeriod, uint256 endPeriod, uint256 rewardsPerCycle);
event Started();
event NftStaked(address staker, uint256 cycle, uint256 tokenId, uint256 weight);
event NftUnstaked(address staker, uint256 cycle, uint256 tokenId, uint256 weight);
event RewardsClaimed(address staker, uint256 cycle, uint256 startPeriod, uint256 periods, uint256 amount);
event HistoriesUpdated(address staker, uint256 startCycle, uint256 stakerStake, uint256 globalStake);
event Disabled();
/**
* Used to represent the current staking status of an NFT.
* Optimised for use in storage.
*/
struct TokenInfo {
address owner;
uint64 weight;
uint16 depositCycle;
uint16 withdrawCycle;
}
/**
* Used as a historical record of change of stake.
* Stake represents an aggregation of staked token weights.
* Optimised for use in storage.
*/
struct Snapshot {
uint128 stake;
uint128 startCycle;
}
/**
* Used to represent a staker's information about the next claim.
* Optimised for use in storage.
*/
struct NextClaim {
uint16 period;
uint64 globalSnapshotIndex;
uint64 stakerSnapshotIndex;
}
/**
* Used as a container to hold result values from computing rewards.
*/
struct ComputedClaim {
uint16 startPeriod;
uint16 periods;
uint256 amount;
}
bool public enabled = true;
uint256 public totalRewardsPool;
uint256 public startTimestamp;
IERC20 public immutable rewardsTokenContract;
IWhitelistedNftContract public immutable whitelistedNftContract;
uint32 public immutable cycleLengthInSeconds;
uint16 public immutable periodLengthInCycles;
Snapshot[] public globalHistory;
/* staker => snapshots*/
mapping(address => Snapshot[]) public stakerHistories;
/* staker => next claim */
mapping(address => NextClaim) public nextClaims;
/* tokenId => token info */
mapping(uint256 => TokenInfo) public tokenInfos;
/* period => rewardsPerCycle */
mapping(uint256 => uint256) public rewardsSchedule;
modifier hasStarted() {
require(startTimestamp != 0, "NftStaking: staking not started");
_;
}
modifier hasNotStarted() {
require(startTimestamp == 0, "NftStaking: staking has started");
_;
}
modifier isEnabled() {
require(enabled, "NftStaking: contract is not enabled");
_;
}
modifier isNotEnabled() {
require(!enabled, "NftStaking: contract is enabled");
_;
}
/**
* Constructor.
* @dev Reverts if the period length value is zero.
* @dev Reverts if the cycle length value is zero.
* @dev Warning: cycles and periods need to be calibrated carefully. Small values will increase computation load while estimating and claiming rewards. Big values will increase the time to wait before a new period becomes claimable.
* @param cycleLengthInSeconds_ The length of a cycle, in seconds.
* @param periodLengthInCycles_ The length of a period, in cycles.
* @param whitelistedNftContract_ The ERC1155-compliant (optional ERC721-compliance) contract from which staking is accepted.
* @param rewardsTokenContract_ The ERC20-based token used as staking rewards.
*/
constructor(
uint32 cycleLengthInSeconds_,
uint16 periodLengthInCycles_,
IWhitelistedNftContract whitelistedNftContract_,
IERC20 rewardsTokenContract_
) internal {
require(cycleLengthInSeconds_ >= 1 minutes, "NftStaking: invalid cycle length");
require(periodLengthInCycles_ >= 2, "NftStaking: invalid period length");
cycleLengthInSeconds = cycleLengthInSeconds_;
periodLengthInCycles = periodLengthInCycles_;
whitelistedNftContract = whitelistedNftContract_;
rewardsTokenContract = rewardsTokenContract_;
}
/* Admin Public Functions */
/**
* Adds `rewardsPerCycle` reward amount for the period range from `startPeriod` to `endPeriod`, inclusive, to the rewards schedule.
* The necessary amount of reward tokens is transferred to the contract. Cannot be used for past periods.
* Can only be used to add rewards and not to remove them.
* @dev Reverts if not called by the owner.
* @dev Reverts if the start period is zero.
* @dev Reverts if the end period precedes the start period.
* @dev Reverts if attempting to add rewards for a period earlier than the current, after staking has started.
* @dev Reverts if the reward tokens transfer fails.
* @dev The rewards token contract emits an ERC20 Transfer event for the reward tokens transfer.
* @dev Emits a RewardsAdded event.
* @param startPeriod The starting period (inclusive).
* @param endPeriod The ending period (inclusive).
* @param rewardsPerCycle The reward amount to add for each cycle within range.
*/
function addRewardsForPeriods(
uint16 startPeriod,
uint16 endPeriod,
uint256 rewardsPerCycle
) external onlyOwner {
require(startPeriod != 0 && startPeriod <= endPeriod, "NftStaking: wrong period range");
uint16 periodLengthInCycles_ = periodLengthInCycles;
if (startTimestamp != 0) {
require(
startPeriod >= _getCurrentPeriod(periodLengthInCycles_),
"NftStaking: already committed reward schedule"
);
}
for (uint256 period = startPeriod; period <= endPeriod; ++period) {
rewardsSchedule[period] = rewardsSchedule[period].add(rewardsPerCycle);
}
uint256 addedRewards = rewardsPerCycle.mul(periodLengthInCycles_).mul(endPeriod - startPeriod + 1);
totalRewardsPool = totalRewardsPool.add(addedRewards);
require(
rewardsTokenContract.transferFrom(msg.sender, address(this), addedRewards),
"NftStaking: failed to add funds to the reward pool"
);
emit RewardsAdded(startPeriod, endPeriod, rewardsPerCycle);
}
/**
* Starts the first cycle of staking, enabling users to stake NFTs.
* @dev Reverts if not called by the owner.
* @dev Reverts if the staking has already started.
* @dev Emits a Started event.
*/
function start() public onlyOwner hasNotStarted {
startTimestamp = now;
emit Started();
}
/**
* Permanently disables all staking and claiming.
* This is an emergency recovery feature which is NOT part of the normal contract operation.
* @dev Reverts if not called by the owner.
* @dev Emits a Disabled event.
*/
function disable() public onlyOwner {
enabled = false;
emit Disabled();
}
/**
* Withdraws a specified amount of reward tokens from the contract it has been disabled.
* @dev Reverts if not called by the owner.
* @dev Reverts if the contract has not been disabled.
* @dev Reverts if the reward tokens transfer fails.
* @dev The rewards token contract emits an ERC20 Transfer event for the reward tokens transfer.
* @param amount The amount to withdraw.
*/
function withdrawRewardsPool(uint256 amount) public onlyOwner isNotEnabled {
require(
rewardsTokenContract.transfer(msg.sender, amount),
"NftStaking: failed to withdraw from the rewards pool"
);
}
/* ERC1155TokenReceiver */
function onERC1155Received(
address, /*operator*/
address from,
uint256 id,
uint256, /*value*/
bytes calldata /*data*/
) external virtual override returns (bytes4) {
_stakeNft(id, from);
return _ERC1155_RECEIVED;
}
function onERC1155BatchReceived(
address, /*operator*/
address from,
uint256[] calldata ids,
uint256[] calldata, /*values*/
bytes calldata /*data*/
) external virtual override returns (bytes4) {
for (uint256 i = 0; i < ids.length; ++i) {
_stakeNft(ids[i], from);
}
return _ERC1155_BATCH_RECEIVED;
}
/* Staking Public Functions */
/**
* Unstakes a deposited NFT from the contract and updates the histories accordingly.
* The NFT's weight will not count for the current cycle.
* @dev Reverts if the caller is not the original owner of the NFT.
* @dev While the contract is enabled, reverts if the NFT is still frozen.
* @dev Reverts if the NFT transfer back to the original owner fails.
* @dev If ERC1155 safe transfers are supported by the receiver wallet, the whitelisted NFT contract emits an ERC1155 TransferSingle event for the NFT transfer back to the staker.
* @dev If ERC1155 safe transfers are not supported by the receiver wallet, the whitelisted NFT contract emits an ERC721 Transfer event for the NFT transfer back to the staker.
* @dev While the contract is enabled, emits a HistoriesUpdated event.
* @dev Emits a NftUnstaked event.
* @param tokenId The token identifier, referencing the NFT being unstaked.
*/
function unstakeNft(uint256 tokenId) external virtual {
TokenInfo memory tokenInfo = tokenInfos[tokenId];
require(tokenInfo.owner == msg.sender, "NftStaking: token not staked or incorrect token owner");
uint16 currentCycle = _getCycle(now);
if (enabled) {
// ensure that at least an entire cycle has elapsed before unstaking the token to avoid
// an exploit where a full cycle would be claimable if staking just before the end
// of a cycle and unstaking right after the start of the new cycle
require(currentCycle - tokenInfo.depositCycle >= 2, "NftStaking: token still frozen");
_updateHistories(msg.sender, -int128(tokenInfo.weight), currentCycle);
// clear the token owner to ensure it cannot be unstaked again without being re-staked
tokenInfo.owner = address(0);
// set the withdrawal cycle to ensure it cannot be re-staked during the same cycle
tokenInfo.withdrawCycle = currentCycle;
tokenInfos[tokenId] = tokenInfo;
}
try whitelistedNftContract.safeTransferFrom(address(this), msg.sender, tokenId, 1, "") {} catch {
// the above call to the ERC1155 safeTransferFrom() function may fail if the recipient
// is a contract wallet not implementing the ERC1155TokenReceiver interface
// if this happens, the transfer falls back to a call to the ERC721 (non-safe) transferFrom function.
whitelistedNftContract.transferFrom(address(this), msg.sender, tokenId);
}
emit NftUnstaked(msg.sender, currentCycle, tokenId, tokenInfo.weight);
}
/**
* Estimates the claimable rewards for the specified maximum number of past periods, starting at the next claimable period.
* Estimations can be done only for periods which have already ended.
* The maximum number of periods to claim can be calibrated to chunk down claims in several transactions to accomodate gas constraints.
* @param maxPeriods The maximum number of periods to calculate for.
* @return startPeriod The first period on which the computation starts.
* @return periods The number of periods computed for.
* @return amount The total claimable rewards.
*/
function estimateRewards(uint16 maxPeriods)
external
view
isEnabled
hasStarted
returns (
uint16 startPeriod,
uint16 periods,
uint256 amount
)
{
(ComputedClaim memory claim, ) = _computeRewards(msg.sender, maxPeriods);
startPeriod = claim.startPeriod;
periods = claim.periods;
amount = claim.amount;
}
/**
* Claims the claimable rewards for the specified maximum number of past periods, starting at the next claimable period.
* Claims can be done only for periods which have already ended.
* The maximum number of periods to claim can be calibrated to chunk down claims in several transactions to accomodate gas constraints.
* @dev Reverts if the reward tokens transfer fails.
* @dev The rewards token contract emits an ERC20 Transfer event for the reward tokens transfer.
* @dev Emits a RewardsClaimed event.
* @param maxPeriods The maximum number of periods to claim for.
*/
function claimRewards(uint16 maxPeriods) external isEnabled hasStarted {
NextClaim memory nextClaim = nextClaims[msg.sender];
(ComputedClaim memory claim, NextClaim memory newNextClaim) = _computeRewards(msg.sender, maxPeriods);
// free up memory on already processed staker snapshots
Snapshot[] storage stakerHistory = stakerHistories[msg.sender];
while (nextClaim.stakerSnapshotIndex < newNextClaim.stakerSnapshotIndex) {
delete stakerHistory[nextClaim.stakerSnapshotIndex++];
}
if (claim.periods == 0) {
return;
}
if (nextClaims[msg.sender].period == 0) {
return;
}
Snapshot memory lastStakerSnapshot = stakerHistory[stakerHistory.length - 1];
uint256 lastClaimedCycle = (claim.startPeriod + claim.periods - 1) * periodLengthInCycles;
if (
lastClaimedCycle >= lastStakerSnapshot.startCycle && // the claim reached the last staker snapshot
lastStakerSnapshot.stake == 0 // and nothing is staked in the last staker snapshot
) {
// re-init the next claim
delete nextClaims[msg.sender];
} else {
nextClaims[msg.sender] = newNextClaim;
}
if (claim.amount != 0) {
require(rewardsTokenContract.transfer(msg.sender, claim.amount), "NftStaking: failed to transfer rewards");
}
emit RewardsClaimed(msg.sender, _getCycle(now), claim.startPeriod, claim.periods, claim.amount);
}
/* Utility Public Functions */
/**
* Retrieves the current cycle (index-1 based).
* @return The current cycle (index-1 based).
*/
function getCurrentCycle() external view returns (uint16) {
return _getCycle(now);
}
/**
* Retrieves the current period (index-1 based).
* @return The current period (index-1 based).
*/
function getCurrentPeriod() external view returns (uint16) {
return _getCurrentPeriod(periodLengthInCycles);
}
/**
* Retrieves the last global snapshot index, if any.
* @dev Reverts if the global history is empty.
* @return The last global snapshot index.
*/
function lastGlobalSnapshotIndex() external view returns (uint256) {
uint256 length = globalHistory.length;
require(length != 0, "NftStaking: empty global history");
return length - 1;
}
/**
* Retrieves the last staker snapshot index, if any.
* @dev Reverts if the staker history is empty.
* @return The last staker snapshot index.
*/
function lastStakerSnapshotIndex(address staker) external view returns (uint256) {
uint256 length = stakerHistories[staker].length;
require(length != 0, "NftStaking: empty staker history");
return length - 1;
}
/* Staking Internal Functions */
/**
* Stakes the NFT received by the contract for its owner. The NFT's weight will count for the current cycle.
* @dev Reverts if the caller is not the whitelisted NFT contract.
* @dev Emits an HistoriesUpdated event.
* @dev Emits an NftStaked event.
* @param tokenId Identifier of the staked NFT.
* @param tokenOwner Owner of the staked NFT.
*/
function _stakeNft(uint256 tokenId, address tokenOwner) internal isEnabled hasStarted {
require(address(whitelistedNftContract) == msg.sender, "NftStaking: contract not whitelisted");
uint64 weight = _validateAndGetNftWeight(tokenId);
uint16 periodLengthInCycles_ = periodLengthInCycles;
uint16 currentCycle = _getCycle(now);
_updateHistories(tokenOwner, int128(weight), currentCycle);
// initialise the next claim if it was the first stake for this staker or if
// the next claim was re-initialised (ie. rewards were claimed until the last
// staker snapshot and the last staker snapshot has no stake)
if (nextClaims[tokenOwner].period == 0) {
uint16 currentPeriod = _getPeriod(currentCycle, periodLengthInCycles_);
nextClaims[tokenOwner] = NextClaim(currentPeriod, uint64(globalHistory.length - 1), 0);
}
uint16 withdrawCycle = tokenInfos[tokenId].withdrawCycle;
require(currentCycle != withdrawCycle, "NftStaking: unstaked token cooldown");
// set the staked token's info
tokenInfos[tokenId] = TokenInfo(tokenOwner, weight, currentCycle, 0);
emit NftStaked(tokenOwner, currentCycle, tokenId, weight);
}
/**
* Calculates the amount of rewards for a staker over a capped number of periods.
* @dev Processes until the specified maximum number of periods to claim is reached, or the last computable period is reached, whichever occurs first.
* @param staker The staker for whom the rewards will be computed.
* @param maxPeriods Maximum number of periods over which to compute the rewards.
* @return claim the result of computation
* @return nextClaim the next claim which can be used to update the staker's state
*/
function _computeRewards(address staker, uint16 maxPeriods)
internal
view
returns (ComputedClaim memory claim, NextClaim memory nextClaim)
{
// computing 0 periods
if (maxPeriods == 0) {
return (claim, nextClaim);
}
// the history is empty
if (globalHistory.length == 0) {
return (claim, nextClaim);
}
nextClaim = nextClaims[staker];
claim.startPeriod = nextClaim.period;
// nothing has been staked yet
if (claim.startPeriod == 0) {
return (claim, nextClaim);
}
uint16 periodLengthInCycles_ = periodLengthInCycles;
uint16 endClaimPeriod = _getCurrentPeriod(periodLengthInCycles_);
// current period is not claimable
if (nextClaim.period == endClaimPeriod) {
return (claim, nextClaim);
}
// retrieve the next snapshots if they exist
Snapshot[] memory stakerHistory = stakerHistories[staker];
Snapshot memory globalSnapshot = globalHistory[nextClaim.globalSnapshotIndex];
Snapshot memory stakerSnapshot = stakerHistory[nextClaim.stakerSnapshotIndex];
Snapshot memory nextGlobalSnapshot;
Snapshot memory nextStakerSnapshot;
if (nextClaim.globalSnapshotIndex != globalHistory.length - 1) {
nextGlobalSnapshot = globalHistory[nextClaim.globalSnapshotIndex + 1];
}
if (nextClaim.stakerSnapshotIndex != stakerHistory.length - 1) {
nextStakerSnapshot = stakerHistory[nextClaim.stakerSnapshotIndex + 1];
}
// excludes the current period
claim.periods = endClaimPeriod - nextClaim.period;
if (maxPeriods < claim.periods) {
claim.periods = maxPeriods;
}
// re-calibrate the end claim period based on the actual number of
// periods to claim. nextClaim.period will be updated to this value
// after exiting the loop
endClaimPeriod = nextClaim.period + claim.periods;
// iterate over periods
while (nextClaim.period != endClaimPeriod) {
uint16 nextPeriodStartCycle = nextClaim.period * periodLengthInCycles_ + 1;
uint256 rewardPerCycle = rewardsSchedule[nextClaim.period];
uint256 startCycle = nextPeriodStartCycle - periodLengthInCycles_;
uint256 endCycle = 0;
// iterate over global snapshots
while (endCycle != nextPeriodStartCycle) {
// find the range-to-claim starting cycle, where the current
// global snapshot, the current staker snapshot, and the current
// period overlap
if (globalSnapshot.startCycle > startCycle) {
startCycle = globalSnapshot.startCycle;
}
if (stakerSnapshot.startCycle > startCycle) {
startCycle = stakerSnapshot.startCycle;
}
// find the range-to-claim ending cycle, where the current
// global snapshot, the current staker snapshot, and the current
// period no longer overlap. The end cycle is exclusive of the
// range-to-claim and represents the beginning cycle of the next
// range-to-claim
endCycle = nextPeriodStartCycle;
if ((nextGlobalSnapshot.startCycle != 0) && (nextGlobalSnapshot.startCycle < endCycle)) {
endCycle = nextGlobalSnapshot.startCycle;
}
// only calculate and update the claimable rewards if there is
// something to calculate with
if ((globalSnapshot.stake != 0) && (stakerSnapshot.stake != 0) && (rewardPerCycle != 0)) {
uint256 snapshotReward = (endCycle - startCycle).mul(rewardPerCycle).mul(stakerSnapshot.stake);
snapshotReward /= globalSnapshot.stake;
claim.amount = claim.amount.add(snapshotReward);
}
// advance the current global snapshot to the next (if any)
// if its cycle range has been fully processed and if the next
// snapshot starts at most on next period first cycle
if (nextGlobalSnapshot.startCycle == endCycle) {
globalSnapshot = nextGlobalSnapshot;
++nextClaim.globalSnapshotIndex;
if (nextClaim.globalSnapshotIndex != globalHistory.length - 1) {
nextGlobalSnapshot = globalHistory[nextClaim.globalSnapshotIndex + 1];
} else {
nextGlobalSnapshot = Snapshot(0, 0);
}
}
// advance the current staker snapshot to the next (if any)
// if its cycle range has been fully processed and if the next
// snapshot starts at most on next period first cycle
if (nextStakerSnapshot.startCycle == endCycle) {
stakerSnapshot = nextStakerSnapshot;
++nextClaim.stakerSnapshotIndex;
if (nextClaim.stakerSnapshotIndex != stakerHistory.length - 1) {
nextStakerSnapshot = stakerHistory[nextClaim.stakerSnapshotIndex + 1];
} else {
nextStakerSnapshot = Snapshot(0, 0);
}
}
}
++nextClaim.period;
}
return (claim, nextClaim);
}
/**
* Updates the global and staker histories at the current cycle with a new difference in stake.
* @dev Emits a HistoriesUpdated event.
* @param staker The staker who is updating the history.
* @param stakeDelta The difference to apply to the current stake.
* @param currentCycle The current cycle.
*/
function _updateHistories(
address staker,
int128 stakeDelta,
uint16 currentCycle
) internal {
uint256 stakerSnapshotIndex = _updateHistory(stakerHistories[staker], stakeDelta, currentCycle);
uint256 globalSnapshotIndex = _updateHistory(globalHistory, stakeDelta, currentCycle);
emit HistoriesUpdated(
staker,
currentCycle,
stakerHistories[staker][stakerSnapshotIndex].stake,
globalHistory[globalSnapshotIndex].stake
);
}
/**
* Updates the history at the current cycle with a new difference in stake.
* @dev It will update the latest snapshot if it starts at the current cycle, otherwise will create a new snapshot with the updated stake.
* @param history The history to update.
* @param stakeDelta The difference to apply to the current stake.
* @param currentCycle The current cycle.
* @return snapshotIndex Index of the snapshot that was updated or created (i.e. the latest snapshot index).
*/
function _updateHistory(
Snapshot[] storage history,
int128 stakeDelta,
uint16 currentCycle
) internal returns (uint256 snapshotIndex) {
uint256 historyLength = history.length;
uint128 snapshotStake;
if (historyLength != 0) {
// there is an existing snapshot
snapshotIndex = historyLength - 1;
Snapshot storage snapshot = history[snapshotIndex];
snapshotStake = uint256(int256(snapshot.stake).add(stakeDelta)).toUint128();
if (snapshot.startCycle == currentCycle) {
// update the snapshot if it starts on the current cycle
snapshot.stake = snapshotStake;
return snapshotIndex;
}
// update the snapshot index (as a reflection that a new latest
// snapshot will be added to the history), if there was already an
// existing snapshot
snapshotIndex += 1;
} else {
// the snapshot index (as a reflection that a new latest snapshot
// will be added to the history) should already be initialized
// correctly to the default value 0
// the stake delta will not be negative, if we have no history, as
// that would indicate that we are unstaking without having staked
// anything first
snapshotStake = uint128(stakeDelta);
}
Snapshot memory snapshot;
snapshot.stake = snapshotStake;
snapshot.startCycle = currentCycle;
// add a new snapshot in the history
history.push(snapshot);
}
/* Utility Internal Functions */
/**
* Retrieves the cycle (index-1 based) at the specified timestamp.
* @dev Reverts if the specified timestamp is earlier than the beginning of the staking schedule
* @param timestamp The timestamp for which the cycle is derived from.
* @return The cycle (index-1 based) at the specified timestamp.
*/
function _getCycle(uint256 timestamp) internal view returns (uint16) {
require(timestamp >= startTimestamp, "NftStaking: timestamp preceeds contract start");
return (((timestamp - startTimestamp) / uint256(cycleLengthInSeconds)) + 1).toUint16();
}
/**
* Retrieves the period (index-1 based) for the specified cycle and period length.
* @dev reverts if the specified cycle is zero.
* @param cycle The cycle within the period to retrieve.
* @param periodLengthInCycles_ Length of a period, in cycles.
* @return The period (index-1 based) for the specified cycle and period length.
*/
function _getPeriod(uint16 cycle, uint16 periodLengthInCycles_) internal pure returns (uint16) {
require(cycle != 0, "NftStaking: cycle cannot be zero");
return (cycle - 1) / periodLengthInCycles_ + 1;
}
/**
* Retrieves the current period (index-1 based).
* @param periodLengthInCycles_ Length of a period, in cycles.
* @return The current period (index-1 based).
*/
function _getCurrentPeriod(uint16 periodLengthInCycles_) internal view returns (uint16) {
return _getPeriod(_getCycle(now), periodLengthInCycles_);
}
/* Internal Hooks */
/**
* Abstract function which validates whether or not an NFT is accepted for staking and retrieves its associated weight.
* @dev MUST throw if the token is invalid.
* @param tokenId uint256 token identifier of the NFT.
* @return uint64 the weight of the NFT.
*/
function _validateAndGetNftWeight(uint256 tokenId) internal virtual view returns (uint64);
}
/**
* @notice Interface for the NftStaking whitelisted NFT contract.
*/
interface IWhitelistedNftContract {
/**
* ERC1155: Transfers `value` amount of an `id` from `from` to `to` (with safety call).
* @dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard).
* @dev MUST revert if `to` is the zero address.
* @dev MUST revert if balance of holder for token `id` is lower than the `value` sent.
* @dev MUST revert on any other error.
* @dev MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
* @dev After the above conditions are met, this function MUST check if `to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `to` and act appropriately (see "Safe Transfer Rules" section of the standard).
* @param from Source address
* @param to Target address
* @param id ID of the token type
* @param value Transfer amount
* @param data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `to`
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
/**
* @notice ERC721: Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible.
* Requires the msg sender to be the owner, approved, or operator.
* @param from current owner of the token.
* @param to address to receive the ownership of the given token ID.
* @param tokenId uint256 ID of the token to be transferred.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
}
// File @animoca/f1dt-ethereum-contracts/contracts/staking/[email protected]
pragma solidity 0.6.8;
/**
* @title Delta Time Staking Beta
* This contract allows owners of Delta Time 2019 Car NFTs to stake them in exchange for REVV rewards.
*/
contract DeltaTimeStakingBeta is NftStaking {
mapping(uint256 => uint64) public weightsByRarity;
/**
* Constructor.
* @param cycleLengthInSeconds_ The length of a cycle, in seconds.
* @param periodLengthInCycles_ The length of a period, in cycles.
* @param inventoryContract IWhitelistedNftContract the DeltaTimeInventory contract.
* @param revvContract IERC20 the REVV contract.
* @param rarities uint256[] the supported DeltaTimeInventory NFT rarities.
* @param weights uint64[] the staking weights associated to the NFT rarities.
*/
constructor(
uint32 cycleLengthInSeconds_,
uint16 periodLengthInCycles_,
IWhitelistedNftContract inventoryContract,
IERC20 revvContract,
uint256[] memory rarities,
uint64[] memory weights
) public NftStaking(cycleLengthInSeconds_, periodLengthInCycles_, inventoryContract, revvContract) {
require(rarities.length == weights.length, "NftStaking: wrong arguments");
for (uint256 i = 0; i < rarities.length; ++i) {
weightsByRarity[rarities[i]] = weights[i];
}
}
/**
* Verifes that the token is eligible and returns its associated weight.
* Throws if the token is not a 2019 Car NFT.
* @param nftId uint256 token identifier of the NFT.
* @return uint64 the weight of the NFT.
*/
function _validateAndGetNftWeight(uint256 nftId) internal virtual override view returns (uint64) {
// Ids bits layout specification:
// https://github.com/animocabrands/f1dt-core_metadata/blob/v0.1.1/src/constants.js
uint256 nonFungible = (nftId >> 255) & 1;
uint256 tokenType = (nftId >> 240) & 0xFF;
uint256 tokenSeason = (nftId >> 224) & 0xFF;
uint256 tokenRarity = (nftId >> 176) & 0xFF;
// For interpretation of values, refer to: https://github.com/animocabrands/f1dt-core_metadata/tree/v0.1.1/src/mappings
// Types: https://github.com/animocabrands/f1dt-core_metadata/blob/v0.1.1/src/mappings/Common/Types/NameById.js
// Seasons: https://github.com/animocabrands/f1dt-core_metadata/blob/v0.1.1/src/mappings/Common/Seasons/NameById.js
// Rarities: https://github.com/animocabrands/f1dt-core_metadata/blob/v0.1.1/src/mappings/Common/Rarities/TierByRarity.js
require(nonFungible == 1 && tokenType == 1 && tokenSeason == 2, "NftStaking: wrong token");
return weightsByRarity[tokenRarity];
}
}
|
Abstract function which validates whether or not an NFT is accepted for staking and retrieves its associated weight. MUST throw if the token is invalid. tokenId uint256 token identifier of the NFT. return uint64 the weight of the NFT./ Interface for the NftStaking whitelisted NFT contract./
|
interface IWhitelistedNftContract {
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
}
| 1,557,122 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
// OpenZeppelin
import "./openzeppelin-solidity/contracts/SafeMath.sol";
import "./openzeppelin-solidity/contracts/ReentrancyGuard.sol";
import "./openzeppelin-solidity/contracts/ERC1155/ERC1155.sol";
import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol";
// Interfaces
import "./interfaces/ITradingBot.sol";
import "./interfaces/IBotPerformanceOracle.sol";
import "./interfaces/IFeePool.sol";
import './interfaces/IRouter.sol';
import './interfaces/IBackupMode.sol';
// Inheritance
import "./interfaces/ISyntheticBotToken.sol";
contract SyntheticBotToken is ISyntheticBotToken, ERC1155, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct Position {
uint256 numberOfTokens;
uint256 createdOn;
uint256 rewardsEndOn;
uint256 lastUpdateTime;
uint256 rewardPerTokenStored;
uint256 rewardRate;
}
/* ========== STATE VARIABLES ========== */
uint256 constant MAX_REWARDS_DURATION = 52 weeks;
uint256 constant MIN_REWARDS_DURATION = 4 weeks;
uint256 constant MAX_DEDUCTION = 2000; // 20%, denominated in 10000.
IBotPerformanceOracle public immutable oracle;
IERC20 public immutable mcUSD; // mcUSD
IERC20 public immutable TGEN;
ITradingBot public immutable tradingBot;
IFeePool public immutable feePool;
IRouter public immutable router;
IBackupMode public immutable backupMode;
address public immutable backupEscrow;
address public immutable xTGEN;
// Keep track of highest NFT ID.
uint256 public numberOfPositions;
// NFT ID => position info.
mapping(uint256 => Position) public positions;
// User address => NFT ID => reward per token paid.
mapping(address => mapping(uint256 => uint256)) public userRewardPerTokenPaid;
// User address => NFT ID => accumulated rewards.
mapping(address => mapping(uint256 => uint256)) public rewards;
uint256 public totalCostBasis;
mapping(address => uint256) public userCostBasis;
/* ========== CONSTRUCTOR ========== */
constructor(address _botPerformanceOracle, address _tradingBot, address _mcUSD, address _TGEN, address _feePool, address _router, address _xTGEN, address _backupMode, address _backupEscrow) {
oracle = IBotPerformanceOracle(_botPerformanceOracle);
tradingBot = ITradingBot(_tradingBot);
mcUSD = IERC20(_mcUSD);
TGEN = IERC20(_TGEN);
feePool = IFeePool(_feePool);
router = IRouter(_router);
backupMode = IBackupMode(_backupMode);
xTGEN = _xTGEN;
backupEscrow = _backupEscrow;
}
/* ========== VIEWS ========== */
/**
* @dev Returns the USD price of the synthetic bot token.
*/
function getTokenPrice() external view override returns (uint256) {
return oracle.getTokenPrice();
}
/**
* @dev Returns the address of the trading bot associated with this token.
*/
function getTradingBot() external view override returns (address) {
return address(tradingBot);
}
/**
* @dev Given a position ID, returns the position info.
* @param _positionID ID of the position NFT.
* @return (uint256, uint256, uint256, uint256, uint256, uint256) total number of tokens in the position, timestamp the position was created, timestamp the rewards will end, timestamp the rewards were last updated, number of rewards per token, number of rewards per second.
*/
function getPosition(uint256 _positionID) external view override returns (uint256, uint256, uint256, uint256, uint256, uint256) {
Position memory position = positions[_positionID];
return (position.numberOfTokens, position.createdOn, position.rewardsEndOn, position.lastUpdateTime, position.rewardPerTokenStored, position.rewardRate);
}
/**
* @dev Returns the latest timestamp to use when calculating available rewards.
* @param _positionID ID of the position NFT.
* @return (uint256) The latest timestamp to use for rewards calculations.
*/
function lastTimeRewardApplicable(uint256 _positionID) public view override returns (uint256) {
return block.timestamp > positions[_positionID].rewardsEndOn ? positions[_positionID].rewardsEndOn : block.timestamp;
}
/**
* @dev Returns the total amount of rewards remaining for the given position.
* @param _positionID ID of the position NFT.
* @return (uint256) Total amount of rewards remaining.
*/
function remainingRewards(uint256 _positionID) public view override returns (uint256) {
return (positions[_positionID].rewardsEndOn.sub(lastTimeRewardApplicable(_positionID))).mul(positions[_positionID].rewardRate);
}
/**
* @dev Returns the user's amount of rewards remaining for the given position.
* @param _user Address of the user.
* @param _positionID ID of the position NFT.
* @return (uint256) User's amount of rewards remaining.
*/
function remainingRewardsForUser(address _user, uint256 _positionID) external view override returns (uint256) {
return (positions[_positionID].numberOfTokens == 0) ? 0 : remainingRewards(_positionID).mul(balanceOf(_user, _positionID)).div(positions[_positionID].numberOfTokens);
}
/**
* @dev Returns the number of rewards available per token for the given position.
* @notice Scaled by 1e18 to avoid flooring when calculating earned().
* @param _positionID ID of the position NFT.
* @return (uint256) Number of rewards per token.
*/
function rewardPerToken(uint256 _positionID) public view override returns (uint256) {
// Prevent division by 0.
if (positions[_positionID].numberOfTokens == 0) {
return positions[_positionID].rewardPerTokenStored;
}
return
positions[_positionID].rewardPerTokenStored.add(
lastTimeRewardApplicable(_positionID).sub(positions[_positionID].lastUpdateTime).mul(positions[_positionID].rewardRate).mul(1e18).div(positions[_positionID].numberOfTokens)
);
}
/**
* @dev Returns the amount of rewards the user has earned for the given position.
* @param _account Address of the user.
* @param _positionID ID of the position NFT.
* @return (uint256) Amount of rewards earned.
*/
function earned(address _account, uint256 _positionID) public view override returns (uint256) {
return balanceOf(_account, _positionID).mul(rewardPerToken(_positionID).sub(userRewardPerTokenPaid[_account][_positionID])).div(1e18).add(rewards[_account][_positionID]);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev Mints synthetic bot tokens.
* @notice Need to approve (botTokenPrice * numberOfTokens * (mintFee + 10000) / 10000) worth of mcUSD before calling this function.
* @param _numberOfTokens Number of synthetic bot tokens to mint.
* @param _duration Number of weeks before rewards end.
*/
function mintTokens(uint256 _numberOfTokens, uint256 _duration) external override nonReentrant {
require(_numberOfTokens > 0, "SyntheticBotToken: number of tokens must be positive.");
require(_duration.mul(1 weeks) >= MIN_REWARDS_DURATION && _duration.mul(1 weeks) <= MAX_REWARDS_DURATION, "SyntheticBotToken: duration out of bounds.");
require(!backupMode.useBackup(), "SyntheticBotToken: cannot mint during backup mode.");
uint256 mintFee = tradingBot.tokenMintFee();
uint256 botTokenPrice = oracle.getTokenPrice();
uint256 amountOfUSD = _numberOfTokens.mul(botTokenPrice).div(1e18);
// Deduct mcUSD based on duration.
uint256 deduction = amountOfUSD.mul(MAX_REWARDS_DURATION.sub(_duration.mul(1 weeks))).mul(MAX_DEDUCTION).div(MAX_REWARDS_DURATION.sub(MIN_REWARDS_DURATION)).div(10000);
// Transfer mint fee to trading bot owner by depositing in FeePool contract on trading bot owner's behalf.
mcUSD.safeTransferFrom(msg.sender, address(this), amountOfUSD.mul(mintFee.add(10000)).div(10000));
mcUSD.approve(address(feePool), amountOfUSD.mul(mintFee).div(10000));
feePool.deposit(tradingBot.owner(), amountOfUSD.mul(mintFee).div(10000));
// Swap deduction mcUSD for TGEN and transfer to xTGEN contract.
if (deduction > 0) {
mcUSD.approve(address(router), deduction);
uint256 receivedTGEN = router.swapAssetForTGEN(address(mcUSD), deduction);
TGEN.safeTransfer(xTGEN, receivedTGEN);
}
userCostBasis[msg.sender] = userCostBasis[msg.sender].add(amountOfUSD);
totalCostBasis = totalCostBasis.add(amountOfUSD);
numberOfPositions = numberOfPositions.add(1);
_mint(msg.sender, numberOfPositions, _numberOfTokens, "");
positions[numberOfPositions] = Position({
numberOfTokens: _numberOfTokens,
createdOn: block.timestamp,
rewardsEndOn: block.timestamp.add(_duration.mul(1 weeks)),
lastUpdateTime: block.timestamp,
rewardPerTokenStored: 0,
rewardRate: (amountOfUSD.sub(deduction)).div(_duration.mul(1 weeks))
});
emit MintedTokens(msg.sender, numberOfPositions, _numberOfTokens, _duration);
}
/**
* @dev Claims available rewards for the given position.
* @notice Only the position owner can call this function.
* @param _positionID ID of the position NFT.
*/
function claimRewards(uint256 _positionID) external override nonReentrant updateReward(msg.sender, _positionID) {
_getReward(msg.sender, _positionID);
}
/**
* @dev Resets the user's cost basis and lower the total cost basis.
* @notice Only the BackupEscrow contract can call this function.
* @notice This function is called when a user claims their TGEN from the BackupEscrow contract.
* @param _user Address of the user.
* @return (uint256) User's initial cost basis.
*/
function resetCostBasis(address _user) external override nonReentrant returns (uint256) {
require(msg.sender == backupEscrow, "SyntheticBotToken: only the BackupEscrow contract can call this function.");
uint256 costBasis = userCostBasis[_user];
totalCostBasis = totalCostBasis.sub(costBasis);
userCostBasis[_user] = 0;
return costBasis;
}
/**
* @dev Transfers tokens from seller to buyer.
* @param from Address of the seller.
* @param to Address of the buyer.
* @param id NFT ID of the position.
* @param amount Number of tokens to transfer for the given ID.
* @param data Bytes data
*/
function safeTransferFrom(address from, address to, uint id, uint amount, bytes memory data) public override updateReward(from, id) updateReward(to, id) {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"SyntheticBotToken: caller is not owner nor approved."
);
require(balanceOf(from, id) >= amount, "SyntheticBotToken: not enough tokens.");
// Get user's reward before transferring tokens.
_getReward(from, id);
_safeTransferFrom(from, to, id, amount, data);
}
// Prevent transfer of multiple NFTs in one transaction.
function safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public override {}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Claims the user's available rewards for the given position.
* @param _user, Address of the user.
* @param _positionID ID of the position NFT.
*/
function _getReward(address _user, uint256 _positionID) internal {
uint256 reward = rewards[_user][_positionID];
if (reward > 0) {
rewards[_user][_positionID] = 0;
mcUSD.safeTransfer(_user, reward);
emit ClaimedRewards(_user, _positionID, reward);
}
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account, uint256 _positionID) {
positions[_positionID].rewardPerTokenStored = rewardPerToken(_positionID);
positions[_positionID].lastUpdateTime = lastTimeRewardApplicable(_positionID);
if (_account != address(0)) {
rewards[_account][_positionID] = earned(_account, _positionID);
userRewardPerTokenPaid[_account][_positionID] = positions[_positionID].rewardPerTokenStored;
}
_;
}
/* ========== EVENTS ========== */
event MintedTokens(address user, uint256 positionID, uint256 numberOfTokens, uint256 numberOfWeeks);
event ClaimedRewards(address user, uint256 positionID, uint256 amountClaimed);
}
|
Returns the number of rewards available per token for the given position. Scaled by 1e18 to avoid flooring when calculating earned(). _positionID ID of the position NFT. return (uint256) Number of rewards per token./ Prevent division by 0.
|
function rewardPerToken(uint256 _positionID) public view override returns (uint256) {
if (positions[_positionID].numberOfTokens == 0) {
return positions[_positionID].rewardPerTokenStored;
}
return
positions[_positionID].rewardPerTokenStored.add(
lastTimeRewardApplicable(_positionID).sub(positions[_positionID].lastUpdateTime).mul(positions[_positionID].rewardRate).mul(1e18).div(positions[_positionID].numberOfTokens)
);
}
| 14,125,425 |
pragma solidity ^0.4.16;
pragma experimental "v0.5.0";
pragma experimental "ABIEncoderV2";
import {Bytes} from "../src/bytes/Bytes.sol";
contract BytesExamples {
using Bytes for *;
// Check if bytes are equal.
function bytesEqualsExample() public pure {
bytes memory bts0 = hex"01020304";
bytes memory bts1 = hex"01020304";
bytes memory bts2 = hex"05060708";
assert(bts0.equals(bts0)); // Check if a byte array equal to itself.
assert(bts0.equals(bts1)); // Should be equal because they have the same byte at each position.
assert(!bts0.equals(bts2)); // Should not be equal.
}
// Check reference equality
function bytesEqualsRefExample() public pure {
bytes memory bts0 = hex"01020304";
bytes memory bts1 = bts0;
// Every 'bytes' will satisfy 'equalsRef' with itself.
assert(bts0.equalsRef(bts0));
// Different variables, but bts0 was assigned to bts1, so they point to the same area in memory.
assert(bts0.equalsRef(bts1));
// Changing a byte in bts0 will also affect bts1.
bts0[2] = 0x55;
assert(bts1[2] == 0x55);
bytes memory bts2 = hex"01020304";
bytes memory bts3 = hex"01020304";
// These bytes has the same byte at each pos (so they would pass 'equals'), but they are referencing different areas in memory.
assert(!bts2.equalsRef(bts3));
// Changing a byte in bts2 will not affect bts3.
bts2[2] = 0x55;
assert(bts3[2] != 0x55);
}
// copying
function bytesCopyExample() public pure {
bytes memory bts0 = hex"01020304";
var bts0Copy0 = bts0.copy();
// The individual bytes are the same.
assert(bts0.equals(bts0Copy0));
// bts0Copy is indeed a (n independent) copy.
assert(!bts0.equalsRef(bts0Copy0));
bytes memory bts1 = hex"0304";
// Copy with start index.
var bts0Copy1 = bts0.copy(2);
assert(bts0Copy1.equals(bts1));
bytes memory bts2 = hex"0203";
// Copy with start index and length.
var bts0Copy2 = bts0.copy(1, 2);
assert(bts0Copy2.equals(bts2));
}
// concatenate
function bytesConcatExample() public pure {
bytes memory bts0 = hex"01020304";
bytes memory bts1 = hex"05060708";
bytes memory bts01 = hex"0102030405060708";
var cct = bts0.concat(bts1);
// Should be equal to bts01
assert(cct.equals(bts01));
}
// find the highest byte set in a bytes32
function bytes32HighestByteSetExample() public pure {
bytes32 test0 = 0x01;
bytes32 test1 = 0xbb00aa00;
bytes32 test2 = "abc";
// with bytesN, the highest byte is the least significant one.
assert(test0.highestByteSet() == 31);
assert(test1.highestByteSet() == 30); // aa
assert(test2.highestByteSet() == 2);
// Make sure that in the case of test2, the highest byte is equal to "c".
assert(test2[test2.highestByteSet()] == 0x63);
}
// find the lowest byte set in a bytes32
function bytes32LowestByteSetExample() public pure {
bytes32 test0 = 0x01;
bytes32 test1 = 0xbb00aa00;
bytes32 test2 = "abc";
// with bytesN, the lowest byte is the most significant one.
assert(test0.lowestByteSet() == 31);
assert(test1.lowestByteSet() == 28); // bb
assert(test2.lowestByteSet() == 0);
}
// find the highest byte set in a uint
function uintHighestByteSetExample() public pure {
uint test0 = 0x01;
uint test1 = 0xbb00aa00;
// with uint, the highest byte is the most significant one.
assert(test0.highestByteSet() == 0);
assert(test1.highestByteSet() == 3);
}
// find the lowest byte set in a uint
function uintLowestByteSetExample() public pure {
uint test0 = 0x01;
uint test1 = 0xbb00aa00;
// with uint, the lowest byte is the least significant one.
assert(test0.lowestByteSet() == 0);
assert(test1.lowestByteSet() == 1);
}
}
|
concatenate Should be equal to bts01
|
function bytesConcatExample() public pure {
bytes memory bts0 = hex"01020304";
bytes memory bts1 = hex"05060708";
bytes memory bts01 = hex"0102030405060708";
var cct = bts0.concat(bts1);
assert(cct.equals(bts01));
}
| 12,878,381 |
./full_match/137/0x62B4dbEAd0b60F0070aA10F4ac25D24f1Eaa17BA/sources/contracts/MoeToken.sol
|
`amount` token getting minted here & equal amount got locked in RootChainManager `_totalSupply` and `_balances` are private. use `_mint()`_totalSupply = _totalSupply.add(amount);_balances[user] = _balances[user].add(amount);
|
function deposit(address user, bytes calldata depositData) external override {
require(_msgSender() == childChainManagerProxy, "You're not allowed to deposit");
uint256 amount = abi.decode(depositData, (uint256));
_mint(_msgSender(), amount);
emit Transfer(address(0), user, amount);
}
| 4,676,032 |
/////////////////////////////////////////////////////////////////////////////////////
//version 2.0
//Author: Taurus
//Copyright: [email protected]
//
//NOTE: non-view functions cannot return values, only possible way is event
//Changes from v0.9x. Each node has unique address as identifier. All pools removed
//All req and prov handled in the mapping.
//update 12/12: pools cannot be removed, since we need to track who are active, cannot search in mapping.
///////////////////////////////////////////////////////////////////////////////////////
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2; //return self-defined type
contract TaskContract {
//list
mapping (address => Provider) public providerList; //All here
mapping (address => Request) public requestList; //All here
mapping (address => uint256) public balanceList; //reqID => balance
//ID - counter
uint256 private providerCount; //+1 each time
uint256 private requestCount;
constructor() public { //sol 5.0 syntax
providerCount = 0;
requestCount = 0;
}
struct Request {
uint256 reqID; //requestID is not identifier
uint256 blockNumber; //record the time of submition
address payable provider; //record the provider assigned to this request
uint64 time; //time
uint16 target; //target 0-100.00
uint256 price; //the max amount he can pay
bytes dataID; //dataID used to fetch the off-chain data
bytes resultID; //dataID to fetch the result
uint64 numValidations; //user defined the validation
address payable [] validators; //multisignature from validations
bool[] signatures; //true or false array
bool isValid; //the final flag
byte status; //0: 'pending', 1:'providing', 2: validating, 3: complete
}
struct Provider {
uint256 provID;
uint256 blockNumber;
uint64 maxTime; //max time
uint16 maxTarget; //max target he need
uint256 minPrice; //lowest price can accept
bool available; //if ready to be assigned
}
event SystemInfo (address payable addr, bytes info);
event PairingInfo (address payable reqAddr, address payable provAddr, bytes info);
address payable [] providerPool;
address payable [] pendingPool;
address payable [] providingPool;
address payable [] validatingPool;
/////////////////////////////////////////////////////////////////////////////////////
// Function called to become a provider. New on List, Map and Pool.
// NOTE: cannot use to update. You must stop a previous one and start a new one.
// TIPS: gas cost: don't create local copy and write back, modify the storage directly.
//gas cost 165K without event / 167K with event / 92K overwrite
function startProviding(uint64 maxTime, uint16 maxTarget, uint64 minPrice) public returns (bool) {
if(providerList[msg.sender].blockNumber == 0){ //this is new
// register a new provider object in the List and map
providerList[msg.sender].provID = providerCount; //cost 50k per item edit
providerList[msg.sender].blockNumber = block.number;
providerList[msg.sender].maxTime = maxTime;
providerList[msg.sender].maxTime = maxTime;
providerList[msg.sender].maxTarget = maxTarget;
providerList[msg.sender].minPrice = minPrice;
providerList[msg.sender].available = true; //turn on the flag at LAST
// ready for the next
providerPool.push(msg.sender);
emit SystemInfo (msg.sender, "Provider Added");
providerCount++;
assignProvider(msg.sender);
return true;
} else {
if(providerList[msg.sender].available == true){ //can only modify available provider
providerList[msg.sender].blockNumber = block.number;
providerList[msg.sender].maxTime = maxTime;
providerList[msg.sender].maxTarget = maxTarget;
providerList[msg.sender].minPrice = minPrice;
emit SystemInfo(msg.sender,'Provider Updated');
assignProvider(msg.sender);
return true;
}
}
}
// Stop a provider, if you know a provider ID. Get em using getProvID()
// Must be sent from the provider address or it will be failed.
function stopProviding() public returns (bool) {
// If the sender is currently an active provider
if (providerList[msg.sender].available == true){ //can only stop available provider
delete providerList[msg.sender]; //delete from List
return ArrayPop(providerPool, msg.sender); //delete from Pool
emit SystemInfo(msg.sender, 'Provider Stopped');
}
}
//update a provider, you must know the provID and must sent from right addr
function updateProvider(uint64 maxTime, uint16 maxTarget, uint64 minPrice) public returns (bool) {
if(providerList[msg.sender].available == true){ //can only modify available provider
providerList[msg.sender].blockNumber = block.number;
providerList[msg.sender].maxTime = maxTime;
providerList[msg.sender].maxTarget = maxTarget;
providerList[msg.sender].minPrice = minPrice;
emit SystemInfo(msg.sender,'Provider Updated');
assignProvider(msg.sender);
return true;
}
}
// Send a request from user to blockchain.
// Assumes price is including the cost for verification
function startRequest(uint64 time, uint16 target, uint64 price, bytes memory dataID) payable public returns (bool) {
if(requestList[msg.sender].blockNumber == 0){
//register on List
requestList[msg.sender].reqID = requestCount;
requestList[msg.sender].blockNumber = block.number;
requestList[msg.sender].provider = address(0);
requestList[msg.sender].time = time;
requestList[msg.sender].target = target;
requestList[msg.sender].price = price;
requestList[msg.sender].dataID = dataID;
requestList[msg.sender].numValidations = 1;
requestList[msg.sender].status = '0' ; //pending 0x30, not 0
pendingPool.push(msg.sender);
emit SystemInfo (msg.sender, "Request Added");
requestCount++;
assignRequest(msg.sender);
return true;
} else {
if(requestList[msg.sender].status == '0' ){ //can only update pending request
requestList[msg.sender].blockNumber = block.number;
requestList[msg.sender].time = time;
requestList[msg.sender].target = target;
requestList[msg.sender].price = price;
requestList[msg.sender].dataID = dataID;
emit SystemInfo(msg.sender, 'Request Updated');
return true;
}
}
}
function stopRequest() public returns (bool){
if (requestList[msg.sender].status == '0'){ //can only cancel owned pending request
delete requestList[msg.sender]; //delete from List
emit SystemInfo(msg.sender, 'Request Stopped');
return ArrayPop(pendingPool, msg.sender); //delete from Pool
}
}
function updateRequest(uint64 time, uint16 target, uint64 price, bytes memory dataID) payable public returns (bool) {
if(requestList[msg.sender].status == '0' ){ //can only update pending request
requestList[msg.sender].blockNumber = block.number;
requestList[msg.sender].time = time;
requestList[msg.sender].target = target;
requestList[msg.sender].price = price;
requestList[msg.sender].dataID = dataID;
emit SystemInfo(msg.sender, 'Request Updated');
return true;
}
}
// Search in the requestPool, find a job for current provider. Triggered by startProviding
// Return true if a match or false if not.
// Returns: 0: successfully assigned
// 1: searched all providers but find no match
// 2: no available provider right now
// 3: failure during poping pool
function assignProvider(address payable provAddr) private returns (byte){
if(pendingPool.length == 0) return '2';
else {
//search throught the requestPool
for (uint64 i = 0; i < pendingPool.length; i++){
//save the re-usable reqID , may save gas
address payable reqAddr = pendingPool[i];
if( requestList[reqAddr].time <= providerList[provAddr].maxTime &&
requestList[reqAddr].target <= providerList[provAddr].maxTarget &&
requestList[reqAddr].price >= providerList[provAddr].minPrice){
//meet the requirement, assign the task
//update provider
providerList[provAddr].available = false;
ArrayPop(providerPool, provAddr);
//update request
requestList[reqAddr].provider = provAddr;
requestList[reqAddr].status = '1'; //providing
ArrayPop(pendingPool, reqAddr);
//update balanceList addr here is requester's
balanceList[reqAddr] += requestList[reqAddr].price;
providingPool.push(reqAddr);
//status move from pending to providing
emit PairingInfo(reqAddr, provAddr, "Request Assigned");
return '0';
}
}
//after for loop and no match
return '1';
}
}
// Assigning one task to one of the available providers. Only called from requestTask (private)
// Search in the providerPool, if no match in the end, return false
//could only assign one task at a time
//auto sel the first searching result for now, no comparation between multiple availability.
//TODO: need ot add preference next patch
// Returns: 0: successfully assigned
// 1: searched all providers but find no match
// 2: no available provider right now
// 3: failure during poping pool
function assignRequest(address payable reqAddr) private returns (byte) {
//provider availability is checked in pool not in list
if (providerPool.length == 0) return '2';
else { //if any provider in pool
for (uint64 i = 0; i < providerPool.length; i++) {
// save the provider's addr, reusable and save gas cost
address payable provAddr = providerPool[i];
if(provAddr != address(0) && providerList[provAddr].available == true){
// Check if request conditions meet the providers requirements
if (requestList[reqAddr].target <= providerList[provAddr].maxTarget &&
requestList[reqAddr].time <= providerList[provAddr].maxTime &&
requestList[reqAddr].price >= providerList[provAddr].minPrice) {
//update provider:
providerList[provAddr].available = false;
ArrayPop(providerPool, provAddr);
//update request
requestList[reqAddr].provider = provAddr;
requestList[reqAddr].status = '1'; //providing
ArrayPop(pendingPool, reqAddr);
//update balanceList
balanceList[reqAddr] += requestList[reqAddr].price;
providingPool.push(reqAddr);
emit PairingInfo(reqAddr, provAddr, "Request Assigned"); // Let provider listen for this event to see he was selected
return '0';
}
}
}
// No provider was found matching the criteria -- request failed
//requestList[reqID].addr.transfer(requestList[reqID].price); // Returns the ether to the sender
return '1';
}
}
// Provider will call this when they are done and the data is available.
// This will invoke the validation stage but only when the request got enough validators
// that req could be moved from pool and marked,
// Or that req stays providing
function completeRequest(address payable reqAddr, bytes memory resultID) public returns (bool) {
// Confirm msg.sender is actually the provider of the task he claims
if (msg.sender == requestList[reqAddr].provider) {
//change request obj
requestList[reqAddr].status = '2'; //validating
requestList[reqAddr].resultID = resultID;
//move from providing pool to validating Pool.
ArrayPop(providingPool, reqAddr);
validatingPool.push(reqAddr);
//release provider (not necessarily depend on provider)
//providerList[providerID[msg.sender]].available = true;
emit SystemInfo(reqAddr, 'Request Computation Completed');
//start validation process
return validateRequest(reqAddr);
}
else {
return false;
}
}
// Called by assignRequest before finalizing stuff. Contract checks with validators
// Returns false if there wasnt enough free providers to send out the required number of validation requests
// need validation from 1/10 of nodes -- could change
function validateRequest(address payable reqAddr) public returns (bool) {
uint64 numValidatorsNeeded = requestList[reqAddr].numValidations;
//uint numValidators = providerCount / 10;
uint64 validatorsFound = 0;
//select # of available provider from the pool and force em to do the validation
for (uint64 i = 0; i < providerPool.length; i++) {
//get provider ID
address payable provID = providerPool[i];
if(provID != requestList[reqAddr].provider){ //validator and computer cannot be same
//EVENT: informs validator that they were selected and need to validate
emit PairingInfo(reqAddr, provID, 'Validation Assigned to Provider');
validatorsFound++;
//remove the providers availablity and pop from pool
providerList[provID].available = false;
ArrayPop(providerPool, provID);
} else continue;
//check whether got enough validator
if(validatorsFound < numValidatorsNeeded){
continue;
}
else{ //enough validator
emit SystemInfo(reqAddr, 'Enough Validators');
return true;
break;
}
//loop until certain # of validators selected
}
//exit loop without enough validators
emit SystemInfo(reqAddr, 'Not Enough Validators');
}
// needs to be more secure by ensuring the submission is coming from someone legit
// similar to completeTask but this will sign the validation list of the target Task
//TODO: the money part is ommited for now
function submitValidation(address payable reqAddr, bool result) public returns (bool) {
// Pay the validator
// uint partialPayment = requestList[reqID].price / 100; // amount each validator is paid
// msg.sender.transfer(partialPayment);
// balanceList[requestList[reqID].addr] -= partialPayment;
if(msg.sender != requestList[reqAddr].provider) { //validator cannot be provider
requestList[reqAddr].validators.push(msg.sender); //push array
requestList[reqAddr].signatures.push(result); //edit mapping
}
//emit ValidationInfo(reqID, provID, 'Validator Signed');
//check if valid
emit PairingInfo(reqAddr, msg.sender, 'Validator Signed');
// If enough validations have been submitted
if (requestList[reqAddr].validators.length == requestList[reqAddr].numValidations) {
//return checkValidation(reqID, requestList[reqID].price - requestList[reqID].numValidationsNeeded * partialPayment);
//checkValidation(reqID);
}
}
function checkValidation(address payable reqAddr) public returns (bool) {
// Add up successful validations
bool flag = false;
uint64 successCount = 0;
for (uint64 i=0; i<requestList[reqAddr].validators.length; i++) {
if (requestList[reqAddr].signatures[i] == true) successCount++;
}
// if 2/3 of validation attempts were successful
// TODO: determine the fraction
if (successCount >= requestList[reqAddr].numValidations) {
// if 2/3 of validations were valid then provider gets remainder of money
//requestList[reqID].provider.transfer(payment);
//balanceList[requestList[reqID].addr] -= payment;
//TODO: [important] leave out the payment part for now.
requestList[reqAddr].isValid = true; // Task was successfully completed!
flag = true;
}
// otherwise, work was invalid, the providers payment goes back to requester
else {
//requestList[reqID].addr.transfer(payment);
//balanceList[requestList[reqID].addr] -= payment;
}
// EVENT: task is done whether successful or not
//emit TaskCompleted(requestList[reqID].addr, reqID);
emit SystemInfo(reqAddr, 'Validation Complete');
//popout from pool
flag = flag && ArrayPop(validatingPool, reqAddr);
return flag;
}
/////////////////////////////////////////////////////////////////////
// Used to dynamically remove elements from array of open provider spaces.
// Using a swap and delete method, search for the desired addr throughout the whole array
// delete the desired and swap the whole with last element
function ArrayPop(address payable [] storage array, address payable target) private returns (bool) {
for(uint64 i = 0; i < array.length; i++){
if (array[i] == target) {
//swap last element with hole
array[i] = array[array.length-1];
//delete last item
delete array[array.length-1];
//decrease size
array.length -= 1;
return true;
}
}
return false; //fail to search: no matching in pool
}
/////////////////////////////////////////////////////////////////////////////////
//some helpers defined here
function getProvider(address payable ID) public view returns(Provider memory){
return providerList[ID];
}
function getRequest(address payable ID) public view returns (Request memory){
return requestList[ID];
}
function getProviderCount() public view returns (uint256){
return providerCount;
}
function getRequestCount() public view returns (uint256){
return requestCount;
}
function getProviderPool() public view returns (address payable [] memory){
return providerPool;
}
function getPendingPool() public view returns (address payable [] memory){
return pendingPool;
}
function getValidatingPool() public view returns (address payable [] memory){
return validatingPool;
}
function getProvidingPool() public view returns (address payable [] memory){
return providingPool;
}
function getProviderPoolSize() public view returns (uint256){
return providerPool.length;
}
function getRequestPoolSize() public view returns (uint256){
return pendingPool.length;
}
//function getBalance(address addr) public view returns (uint256){
// return balanceList[addr];
//}
function listRequests(address payable[] memory IDList) public view returns(Request[50] memory){
Request[50] memory allRequest;
for (uint64 i = 0; i < IDList.length; i++){
allRequest[i] = getRequest(IDList[i]);
}
return allRequest;
}
function listProviders(address payable[] memory IDList) public view returns(Provider[50] memory){
Provider[50] memory allProvider;
//address addr;
for (uint64 i = 0; i < IDList.length;i++){
allProvider[i] = getProvider(IDList[i]);
}
return allProvider;
}
/* function listAllRequests() public view returns(Request[50] memory){
Request[50] memory allRequest;
for (uint64 i = 0; i < requestCount; i++){
allRequest[i] = getRequest(i);
}
return allRequest;
}
function listAllProviders() public view returns(Provider[50] memory){
Provider[50] memory allProvider;
for (uint64 i = 0; i < providerCount; i++){
allProvider[i] = getProvider(i);
}
return allProvider;
}
*/
}
|
update a provider, you must know the provID and must sent from right addr
|
function updateProvider(uint64 maxTime, uint16 maxTarget, uint64 minPrice) public returns (bool) {
providerList[msg.sender].blockNumber = block.number;
providerList[msg.sender].maxTime = maxTime;
providerList[msg.sender].maxTarget = maxTarget;
providerList[msg.sender].minPrice = minPrice;
emit SystemInfo(msg.sender,'Provider Updated');
assignProvider(msg.sender);
return true;
}
| 6,430,855 |
pragma solidity ^0.4.24;
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize 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.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
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);
// Allocate space for the buffer data
buf.capacity = capacity;
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) {
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 The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
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 {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
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.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @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 The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
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 value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string 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 usingOraclize {
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_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
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(tmp[i]);
b2 = uint160(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 _a, string _b) internal pure returns (int) {
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 _haystack, string _needle) internal pure returns (int) {
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 _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
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;
for (uint 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 strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
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(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
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[] arr) internal pure returns (bytes) {
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;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
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 = oraclize_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))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(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(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(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(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 == false) return false;
// 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(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// 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(proof[ledgerProofLength+32+8]))) return false;
// 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 (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// 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 (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_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 from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
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, address) {
// 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)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
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 sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 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, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface IOracle {
/**
* @notice Returns address of oracle currency (0x0 for ETH)
*/
function getCurrencyAddress() external view returns(address);
/**
* @notice Returns symbol of oracle currency (0x0 for ETH)
*/
function getCurrencySymbol() external view returns(bytes32);
/**
* @notice Returns denomination of price
*/
function getCurrencyDenominated() external view returns(bytes32);
/**
* @notice Returns price - should throw if not valid
*/
function getPrice() external view returns(uint256);
}
contract PolyOracle is usingOraclize, IOracle, Ownable {
using SafeMath for uint256;
string public oracleURL = "json(https://api.coinmarketcap.com/v2/ticker/2496/?convert=USD).data.quotes.USD.price";
uint256 public sanityBounds = 20*10**16;
uint256 public gasLimit = 100000;
uint256 public oraclizeTimeTolerance = 5 minutes;
uint256 public staleTime = 6 hours;
uint256 private POLYUSD;
uint256 public latestUpdate;
uint256 public latestScheduledUpdate;
mapping (bytes32 => uint256) public requestIds;
mapping (bytes32 => bool) public ignoreRequestIds;
mapping (address => bool) public admin;
bool public freezeOracle;
event LogPriceUpdated(uint256 _price, uint256 _oldPrice, bytes32 _queryId, uint256 _time);
event LogNewOraclizeQuery(uint256 _time, bytes32 _queryId, string _query);
event LogAdminSet(address _admin, bool _valid, uint256 _time);
event LogStalePriceUpdate(bytes32 _queryId, uint256 _time, string _result);
modifier isAdminOrOwner {
require(admin[msg.sender] || msg.sender == owner, "Address is not admin or owner");
_;
}
/**
* @notice Constructor - accepts ETH to initialise a balance for subsequent Oraclize queries
*/
constructor() payable public {
// Use 50 gwei for now
oraclize_setCustomGasPrice(50*10**9);
}
/**
* @notice Oraclize callback (triggered by Oraclize)
* @param _requestId requestId corresponding to Oraclize query
* @param _result data returned by Oraclize URL query
*/
function __callback(bytes32 _requestId, string _result) public {
require(msg.sender == oraclize_cbAddress(), "Only Oraclize can access this method");
require(!freezeOracle, "Oracle is frozen");
require(!ignoreRequestIds[_requestId], "Ignoring requestId");
if (requestIds[_requestId] < latestUpdate) {
// Result is stale, probably because it was received out of order
emit LogStalePriceUpdate(_requestId, requestIds[_requestId], _result);
return;
}
require(requestIds[_requestId] >= latestUpdate, "Result is stale");
require(requestIds[_requestId] <= now + oraclizeTimeTolerance, "Result is early");
uint256 newPOLYUSD = parseInt(_result, 18);
uint256 bound = POLYUSD.mul(sanityBounds).div(10**18);
if (latestUpdate != 0) {
require(newPOLYUSD <= POLYUSD.add(bound), "Result is too large");
require(newPOLYUSD >= POLYUSD.sub(bound), "Result is too small");
}
latestUpdate = requestIds[_requestId];
emit LogPriceUpdated(newPOLYUSD, POLYUSD, _requestId, latestUpdate);
POLYUSD = newPOLYUSD;
}
/**
* @notice Allows owner to schedule future Oraclize calls
* @param _times UNIX timestamps to schedule Oraclize calls as of. Empty list means trigger an immediate query.
*/
function schedulePriceUpdatesFixed(uint256[] _times) payable isAdminOrOwner public {
bytes32 requestId;
uint256 maximumScheduledUpdated;
if (_times.length == 0) {
require(oraclize_getPrice("URL", gasLimit) <= address(this).balance, "Insufficient Funds");
requestId = oraclize_query("URL", oracleURL, gasLimit);
requestIds[requestId] = now;
maximumScheduledUpdated = now;
emit LogNewOraclizeQuery(now, requestId, oracleURL);
} else {
require(oraclize_getPrice("URL", gasLimit) * _times.length <= address(this).balance, "Insufficient Funds");
for (uint256 i = 0; i < _times.length; i++) {
require(_times[i] >= now, "Past scheduling is not allowed and scheduled time should be absolute timestamp");
requestId = oraclize_query(_times[i], "URL", oracleURL, gasLimit);
requestIds[requestId] = _times[i];
if (maximumScheduledUpdated < requestIds[requestId]) {
maximumScheduledUpdated = requestIds[requestId];
}
emit LogNewOraclizeQuery(_times[i], requestId, oracleURL);
}
}
if (latestScheduledUpdate < maximumScheduledUpdated) {
latestScheduledUpdate = maximumScheduledUpdated;
}
}
/**
* @notice Allows owner to schedule future Oraclize calls on a rolling schedule
* @param _startTime UNIX timestamp for the first scheduled Oraclize query
* @param _interval how long (in seconds) between each subsequent Oraclize query
* @param _iters the number of Oraclize queries to schedule.
*/
function schedulePriceUpdatesRolling(uint256 _startTime, uint256 _interval, uint256 _iters) payable isAdminOrOwner public {
bytes32 requestId;
require(_interval > 0, "Interval between scheduled time should be greater than zero");
require(_iters > 0, "No iterations specified");
require(_startTime >= now, "Past scheduling is not allowed and scheduled time should be absolute timestamp");
require(oraclize_getPrice("URL", gasLimit) * _iters <= address(this).balance, "Insufficient Funds");
for (uint256 i = 0; i < _iters; i++) {
uint256 scheduledTime = _startTime + (i * _interval);
requestId = oraclize_query(scheduledTime, "URL", oracleURL, gasLimit);
requestIds[requestId] = scheduledTime;
emit LogNewOraclizeQuery(scheduledTime, requestId, oracleURL);
}
if (latestScheduledUpdate < requestIds[requestId]) {
latestScheduledUpdate = requestIds[requestId];
}
}
/**
* @notice Allows owner to manually set POLYUSD price
* @param _price POLYUSD price
*/
function setPOLYUSD(uint256 _price) onlyOwner public {
emit LogPriceUpdated(_price, POLYUSD, 0, now);
POLYUSD = _price;
latestUpdate = now;
}
/**
* @notice Allows owner to set oracle to ignore all Oraclize pricce updates
* @param _frozen true to freeze updates, false to reenable updates
*/
function setFreezeOracle(bool _frozen) onlyOwner public {
freezeOracle = _frozen;
}
/**
* @notice Allows owner to set URL used in Oraclize queries
* @param _oracleURL URL to use
*/
function setOracleURL(string _oracleURL) onlyOwner public {
oracleURL = _oracleURL;
}
/**
* @notice Allows owner to set new sanity bounds for price updates
* @param _sanityBounds sanity bounds as a percentage * 10**16
*/
function setSanityBounds(uint256 _sanityBounds) onlyOwner public {
sanityBounds = _sanityBounds;
}
/**
* @notice Allows owner to set new gas price for future Oraclize queries
* @notice NB - this will only impact newly scheduled Oraclize queries, not future queries which have already been scheduled
* @param _gasPrice gas price to use for Oraclize callbacks
*/
function setGasPrice(uint256 _gasPrice) onlyOwner public {
oraclize_setCustomGasPrice(_gasPrice);
}
/**
* @notice Returns price and corresponding update time
* @return latest POLYUSD price
* @return timestamp of latest price update
*/
function getPriceAndTime() view public returns(uint256, uint256) {
return (POLYUSD, latestUpdate);
}
/**
* @notice Allows owner to set new gas limit on Oraclize queries
* @notice NB - this will only impact newly scheduled Oraclize queries, not future queries which have already been scheduled
* @param _gasLimit gas limit to use for Oraclize callbacks
*/
function setGasLimit(uint256 _gasLimit) isAdminOrOwner public {
gasLimit = _gasLimit;
}
/**
* @notice Allows owner to set time after which price is considered stale
* @param _staleTime elapsed time after which price is considered stale
*/
function setStaleTime(uint256 _staleTime) onlyOwner public {
staleTime = _staleTime;
}
/**
* @notice Allows owner to ignore specific requestId results from Oraclize
* @param _requestIds Oraclize queryIds (as logged out when Oraclize query is scheduled)
* @param _ignore whether or not they should be ignored
*/
function setIgnoreRequestIds(bytes32[] _requestIds, bool[] _ignore) onlyOwner public {
require(_requestIds.length == _ignore.length, "Incorrect parameter lengths");
for (uint256 i = 0; i < _requestIds.length; i++) {
ignoreRequestIds[_requestIds[i]] = _ignore[i];
}
}
/**
* @notice Allows owner to set up admin addresses that can schedule updates
* @param _admin Admin address
* @param _valid Whether address should be added or removed from admin list
*/
function setAdmin(address _admin, bool _valid) onlyOwner public {
admin[_admin] = _valid;
emit LogAdminSet(_admin, _valid, now);
}
/**
* @notice Allows owner to set new time tolerance on Oraclize queries
* @param _oraclizeTimeTolerance amount of time in seconds that an Oraclize query can be early
*/
function setOraclizeTimeTolerance(uint256 _oraclizeTimeTolerance) onlyOwner public {
oraclizeTimeTolerance = _oraclizeTimeTolerance;
}
/**
* @notice Returns address of oracle currency (0x0 for ETH)
*/
function getCurrencyAddress() external view returns(address) {
return 0x9992eC3cF6A55b00978cdDF2b27BC6882d88D1eC;
}
/**
* @notice Returns symbol of oracle currency (0x0 for ETH)
*/
function getCurrencySymbol() external view returns(bytes32) {
return bytes32("POLY");
}
/**
* @notice Returns denomination of price
*/
function getCurrencyDenominated() external view returns(bytes32) {
return bytes32("USD");
}
/**
* @notice Returns price - should throw if not valid
*/
function getPrice() external view returns(uint256) {
require(latestUpdate >= now - staleTime);
return POLYUSD;
}
/**
* @notice Returns balance to owner
*/
function drainContract() external onlyOwner {
msg.sender.transfer(address(this).balance);
}
}
|
Returns symbol of oracle currency (0x0 for ETH)/
|
function getCurrencySymbol() external view returns(bytes32) {
return bytes32("POLY");
}
| 121,849 |
// 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];
}
}
|
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";
}
| 1,698,084 |
./full_match/4/0xC16defC75de0586274a508DFFF5D1f28105a299A/sources/contracts/Marsh_Staking_Contract.sol
|
Fucntion called in the event that an indexer is badly behaving. can only be triggered by an admin, results in a `SlashStakeEvent` than splits the indexer's stake between the reporter and the owner. _indexerAddress address of the indexer getting slashed reporterAddress address of the reporter/
|
function RemoveStake(address _indexerAddress, address reporterAddress)
external
onlyAdmin
{
require(
_indexerExists(_indexerAddress),
"Indexer must exist and have staked"
);
approvedIndexers[_indexerAddress].hasStaked = false;
numActiveIndexers--;
uint256 totalAmount = approvedIndexers[_indexerAddress].stakeAmount;
approvedIndexers[_indexerAddress].stakeAmount = 0;
_transferStake(reporterAddress, totalAmount);
emit SlashStakeEvent(_indexerAddress, reporterAddress);
}
| 12,390,094 |
./full_match/4/0xbaa0F03c672412f134B8f8B5781fEdb0a949E65A/sources/1.sol
|
Mints Numbers/ If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
|
function mintNumber(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Ape");
require(numberOfTokens <= maxnumbersPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_NUMBERS, "Purchase would exceed max supply of Apes");
require(numbersPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_NUMBERS) {
_safeMint(msg.sender, mintIndex);
}
}
if (startingIndexBlock == 0 && (totalSupply() == MAX_NUMBERS)) {
startingIndexBlock = block.number;
}
}
| 804,593 |
/**
*Submitted for verification at Etherscan.io on 2021-12-14
*/
/**
*Submitted for verification at Etherscan.io on 2021-10-07
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
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);
}
}
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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);
}
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);
}
pragma solidity ^0.8.0;
/**
* @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;
}
}
pragma solidity ^0.8.0;
/**
* @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;
}
pragma solidity ^0.8.0;
/**
* @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);
}
pragma solidity ^0.8.0;
/**
* @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);
}
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
pragma solidity ^0.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.
*/
/**
* @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);
}
}
pragma solidity ^0.8.0;
/**
* @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;
string public _baseURI;
/**
* @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 base = baseURI();
return bytes(base).length > 0 ? string(abi.encodePacked(base, 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 _baseURI;
}
/**
* @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 {}
}
pragma solidity ^0.8.0;
/**
* @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();
}
}
pragma solidity ^0.8.0;
contract MysticAliens is ERC721Enumerable, Ownable
{
using SafeMath for uint256;
using Strings for uint256;
uint public constant _TOTALSUPPLY =2022;
uint public maxPerTx =5;
uint256 public price = 0.15 ether;
bool public isPaused = true;
uint private tokenId=1;
constructor(string memory baseURI) ERC721("MysticAliens", "MA") {
setBaseURI(baseURI);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseURI = baseURI;
}
function setPrice(uint256 _newPrice) public onlyOwner() {
price = _newPrice;
}
function setMaxxQtPerTx(uint256 _quantity) public onlyOwner {
maxPerTx=_quantity;
}
modifier isSaleOpen{
require(totalSupply() < _TOTALSUPPLY, "Sale end");
_;
}
function flipPauseStatus() public onlyOwner {
isPaused = !isPaused;
}
function getPrice(uint256 _quantity) public view returns (uint256) {
return _quantity*price ;
}
function mint(uint chosenAmount) public payable isSaleOpen{
require(isPaused == false, "Sale is not active at the moment");
require(totalSupply()+chosenAmount<=_TOTALSUPPLY,"Quantity must be lesser then remaining NFTs");
require(chosenAmount > 0, "Number of NFTs can not be less than or equal to 0");
require(chosenAmount <= maxPerTx,"Chosen Amount exceeds MaxQuantity allowed per transaction");
require(chosenAmount+balanceOf(msg.sender)<=10, "Maximum of 10 NFTs can be owned by one person");
require(price.mul(chosenAmount) == msg.value,"Sent ether value is not correct");
for (uint i = 0; i < chosenAmount; i++) {
_safeMint(msg.sender, totalsupply());
tokenId++;
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory base = baseURI();
return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : "";
}
function tokensOfOwner(address _owner) public view returns (uint256[] memory)
{
uint256 count = balanceOf(_owner);
uint256[] memory result = new uint256[](count);
for (uint256 index = 0; index < count; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function contractURI() public view returns (string memory) {
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Mystic Aliens", "description": "For decades, humans have researched and wondered about life beyond Earth. The search is finally over, 2022 Mystic Aliens have landed and they brought a spaceship full of otherworldly treasures - you too can reap the rewards of the Mystic Aliens one of a kind staking + DAO Protocol. APY that is out of this world, literally. Programmatically and randomly generated on the Ethereum Blockchain. Each Alien is unique, made from a combination of more than 50 attributes drawn by hand. A Mystic Alien is both a NFT collectible and a key to enter the spaceship and a lot more.", "seller_fee_basis_points": 1000, "fee_recipient": "0x2C0593Bbd2182C7818ab624FEC0d35EDad917C47"}'))));
json = string(abi.encodePacked('data:application/json;base64,', json));
return json;
}
function totalsupply() private view returns (uint)
{
return tokenId;
}
}
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);
}
}
|
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) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
| 1,274,308 |
./full_match/80001/0x8719eB4713646a91ae18A56F960159225Aa8C725/sources/contracts/Edition.sol
|
/EK _mintPeriodSeconds The amount of time in seconds after which editions can no longer be minted or purchased. Use 0 to have no expiration _salePrice Sale Price _creatorName Creator Name Set ownership to original sender of contract callEK overflows are not expected to happen for timestamps, and have no security implications
|
function initialize(
address _owner,
string memory _name,
string memory _symbol,
string memory _description,
string memory _imageUrl,
uint256 _editionSize,
uint256 _royaltyBPS,
uint256 _mintPeriodSeconds,
uint256 _salePrice,
string memory _creatorName
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
transferOwnership(_owner);
description = _description;
imageUrl = _imageUrl;
editionSize = _editionSize;
royaltyBPS = _royaltyBPS;
uint64 _endOfMintPeriod;
if (_mintPeriodSeconds > 0) {
unchecked {
uint256 endOfMintPeriodUint256 = block.timestamp + _mintPeriodSeconds;
_endOfMintPeriod = requireUint64(endOfMintPeriodUint256);
}
}
endOfMintPeriod = _endOfMintPeriod;
salePrice = _salePrice;
creatorName = _creatorName;
}
| 9,468,407 |
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/licence.sol
|
The address of the TKN token return the address of the TKN contract.
|
function tknContractAddress() external view returns (address) {
return _tknContractAddress;
}
| 3,598,025 |
//Address: 0x2fc5f7b04b1a43a64cfc066530f2bd87e001824d
//Contract name: MilestoneTracker
//Balance: 0 Ether
//Verification Date: 1/20/2017
//Transacion Count: 8
// CODE STARTS HERE
pragma solidity ^0.4.6;
/*
Copyright 2016, Jordi Baylina
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/>.
*/
/// @title MilestoneTracker Contract
/// @author Jordi Baylina
/// @dev This contract tracks the
/// is rules the relation betwen a donor and a recipient
/// in order to guaranty to the donor that the job will be done and to guaranty
/// to the recipient that he will be paid
/// @dev We use the RLP library to decode RLP so that the donor can approve one
/// set of milestone changes at a time.
/// https://github.com/androlo/standard-contracts/blob/master/contracts/src/codec/RLP.sol
/**
* @title RLPReader
*
* RLPReader is used to read and parse RLP encoded data in memory.
*
* @author Andreas Olofsson ([email protected])
*/
library RLP {
uint constant DATA_SHORT_START = 0x80;
uint constant DATA_LONG_START = 0xB8;
uint constant LIST_SHORT_START = 0xC0;
uint constant LIST_LONG_START = 0xF8;
uint constant DATA_LONG_OFFSET = 0xB7;
uint constant LIST_LONG_OFFSET = 0xF7;
struct RLPItem {
uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes.
uint _unsafe_length; // Number of bytes. This is the full length of the string.
}
struct Iterator {
RLPItem _unsafe_item; // Item that's being iterated over.
uint _unsafe_nextPtr; // Position of the next item in the list.
}
/* Iterator */
function next(Iterator memory self) internal constant returns (RLPItem memory subItem) {
if(hasNext(self)) {
var ptr = self._unsafe_nextPtr;
var itemLength = _itemLength(ptr);
subItem._unsafe_memPtr = ptr;
subItem._unsafe_length = itemLength;
self._unsafe_nextPtr = ptr + itemLength;
}
else
throw;
}
function next(Iterator memory self, bool strict) internal constant returns (RLPItem memory subItem) {
subItem = next(self);
if(strict && !_validate(subItem))
throw;
return;
}
function hasNext(Iterator memory self) internal constant returns (bool) {
var item = self._unsafe_item;
return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length;
}
/* RLPItem */
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @return An RLPItem
function toRLPItem(bytes memory self) internal constant returns (RLPItem memory) {
uint len = self.length;
if (len == 0) {
return RLPItem(0, 0);
}
uint memPtr;
assembly {
memPtr := add(self, 0x20)
}
return RLPItem(memPtr, len);
}
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @param strict Will throw if the data is not RLP encoded.
/// @return An RLPItem
function toRLPItem(bytes memory self, bool strict) internal constant returns (RLPItem memory) {
var item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
throw;
if(_itemLength(item._unsafe_memPtr) != len)
throw;
if(!_validate(item))
throw;
}
return item;
}
/// @dev Check if the RLP item is null.
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isNull(RLPItem memory self) internal constant returns (bool ret) {
return self._unsafe_length == 0;
}
/// @dev Check if the RLP item is a list.
/// @param self The RLP item.
/// @return 'true' if the item is a list.
function isList(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
}
}
/// @dev Check if the RLP item is data.
/// @param self The RLP item.
/// @return 'true' if the item is data.
function isData(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := lt(byte(0, mload(memPtr)), 0xC0)
}
}
/// @dev Check if the RLP item is empty (string or list).
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isEmpty(RLPItem memory self) internal constant returns (bool ret) {
if(isNull(self))
return false;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START);
}
/// @dev Get the number of items in an RLP encoded list.
/// @param self The RLP item.
/// @return The number of items.
function items(RLPItem memory self) internal constant returns (uint) {
if (!isList(self))
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
uint pos = memPtr + _payloadOffset(self);
uint last = memPtr + self._unsafe_length - 1;
uint itms;
while(pos <= last) {
pos += _itemLength(pos);
itms++;
}
return itms;
}
/// @dev Create an iterator.
/// @param self The RLP item.
/// @return An 'Iterator' over the item.
function iterator(RLPItem memory self) internal constant returns (Iterator memory it) {
if (!isList(self))
throw;
uint ptr = self._unsafe_memPtr + _payloadOffset(self);
it._unsafe_item = self;
it._unsafe_nextPtr = ptr;
}
/// @dev Return the RLP encoded bytes.
/// @param self The RLPItem.
/// @return The bytes.
function toBytes(RLPItem memory self) internal constant returns (bytes memory bts) {
var len = self._unsafe_length;
if (len == 0)
return;
bts = new bytes(len);
_copyToBytes(self._unsafe_memPtr, bts, len);
}
/// @dev Decode an RLPItem into bytes. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toData(RLPItem memory self) internal constant returns (bytes memory bts) {
if(!isData(self))
throw;
var (rStartPos, len) = _decode(self);
bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
}
/// @dev Get the list of sub-items from an RLP encoded list.
/// Warning: This is inefficient, as it requires that the list is read twice.
/// @param self The RLP item.
/// @return Array of RLPItems.
function toList(RLPItem memory self) internal constant returns (RLPItem[] memory list) {
if(!isList(self))
throw;
var numItems = items(self);
list = new RLPItem[](numItems);
var it = iterator(self);
uint idx;
while(hasNext(it)) {
list[idx] = next(it);
idx++;
}
}
/// @dev Decode an RLPItem into an ascii string. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAscii(RLPItem memory self) internal constant returns (string memory str) {
if(!isData(self))
throw;
var (rStartPos, len) = _decode(self);
bytes memory bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
str = string(bts);
}
/// @dev Decode an RLPItem into a uint. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toUint(RLPItem memory self) internal constant returns (uint data) {
if(!isData(self))
throw;
var (rStartPos, len) = _decode(self);
if (len > 32 || len == 0)
throw;
assembly {
data := div(mload(rStartPos), exp(256, sub(32, len)))
}
}
/// @dev Decode an RLPItem into a boolean. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBool(RLPItem memory self) internal constant returns (bool data) {
if(!isData(self))
throw;
var (rStartPos, len) = _decode(self);
if (len != 1)
throw;
uint temp;
assembly {
temp := byte(0, mload(rStartPos))
}
if (temp > 1)
throw;
return temp == 1 ? true : false;
}
/// @dev Decode an RLPItem into a byte. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toByte(RLPItem memory self) internal constant returns (byte data) {
if(!isData(self))
throw;
var (rStartPos, len) = _decode(self);
if (len != 1)
throw;
uint temp;
assembly {
temp := byte(0, mload(rStartPos))
}
return byte(temp);
}
/// @dev Decode an RLPItem into an int. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toInt(RLPItem memory self) internal constant returns (int data) {
return int(toUint(self));
}
/// @dev Decode an RLPItem into a bytes32. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBytes32(RLPItem memory self) internal constant returns (bytes32 data) {
return bytes32(toUint(self));
}
/// @dev Decode an RLPItem into an address. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAddress(RLPItem memory self) internal constant returns (address data) {
if(!isData(self))
throw;
var (rStartPos, len) = _decode(self);
if (len != 20)
throw;
assembly {
data := div(mload(rStartPos), exp(256, 12))
}
}
// Get the payload offset.
function _payloadOffset(RLPItem memory self) private constant returns (uint) {
if(self._unsafe_length == 0)
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
if(b0 < DATA_SHORT_START)
return 0;
if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
return 1;
if(b0 < LIST_SHORT_START)
return b0 - DATA_LONG_OFFSET + 1;
return b0 - LIST_LONG_OFFSET + 1;
}
// Get the full length of an RLP item.
function _itemLength(uint memPtr) private constant returns (uint len) {
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
else if (b0 < LIST_SHORT_START) {
assembly {
let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
else if (b0 < LIST_LONG_START)
len = b0 - LIST_SHORT_START + 1;
else {
assembly {
let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
}
// Get start position and length of the data.
function _decode(RLPItem memory self) private constant returns (uint memPtr, uint len) {
if(!isData(self))
throw;
uint b0;
uint start = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(start))
}
if (b0 < DATA_SHORT_START) {
memPtr = start;
len = 1;
return;
}
if (b0 < DATA_LONG_START) {
len = self._unsafe_length - 1;
memPtr = start + 1;
} else {
uint bLen;
assembly {
bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
}
len = self._unsafe_length - 1 - bLen;
memPtr = start + bLen + 1;
}
return;
}
// Assumes that enough memory has been allocated to store in target.
function _copyToBytes(uint btsPtr, bytes memory tgt, uint btsLen) private constant {
// Exploiting the fact that 'tgt' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
{
let i := 0 // Start at arr + 0x20
let words := div(add(btsLen, 31), 32)
let rOffset := btsPtr
let wOffset := add(tgt, 0x20)
tag_loop:
jumpi(end, eq(i, words))
{
let offset := mul(i, 0x20)
mstore(add(wOffset, offset), mload(add(rOffset, offset)))
i := add(i, 1)
}
jump(tag_loop)
end:
mstore(add(tgt, add(0x20, mload(tgt))), 0)
}
}
}
// Check that an RLP item is valid.
function _validate(RLPItem memory self) private constant returns (bool ret) {
// Check that RLP is well-formed.
uint b0;
uint b1;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
b1 := byte(1, mload(memPtr))
}
if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START)
return false;
return true;
}
}
/// @dev This contract allows for `recipient` to set and modify milestones
contract MilestoneTracker {
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
using RLP for bytes;
struct Milestone {
string description; // Description of this milestone
string url; // A link to more information (swarm gateway)
uint minCompletionDate; // Earliest UNIX time the milestone can be paid
uint maxCompletionDate; // Latest UNIX time the milestone can be paid
address milestoneLeadLink;
// Similar to `recipient`but for this milestone
address reviewer; // Can reject the completion of this milestone
uint reviewTime; // How many seconds the reviewer has to review
address paymentSource; // Where the milestone payment is sent from
bytes payData; // Data defining how much ether is sent where
MilestoneStatus status; // Current status of the milestone
// (Completed, AuthorizedForPayment...)
uint doneTime; // UNIX time when the milestone was marked DONE
}
// The list of all the milestones.
Milestone[] public milestones;
address public recipient; // Calls functions in the name of the recipient
address public donor; // Calls functions in the name of the donor
address public arbitrator; // Calls functions in the name of the arbitrator
enum MilestoneStatus {
AcceptedAndInProgress,
Completed,
AuthorizedForPayment,
Canceled
}
// True if the campaign has been canceled
bool public campaignCanceled;
// True if an approval on a change to `milestones` is a pending
bool public changingMilestones;
// The pending change to `milestones` encoded in RLP
bytes public proposedMilestones;
/// @dev The following modifiers only allow specific roles to call functions
/// with these modifiers
modifier onlyRecipient { if (msg.sender != recipient) throw; _; }
modifier onlyArbitrator { if (msg.sender != arbitrator) throw; _; }
modifier onlyDonor { if (msg.sender != donor) throw; _; }
/// @dev The following modifiers prevent functions from being called if the
/// campaign has been canceled or if new milestones are being proposed
modifier campaignNotCanceled { if (campaignCanceled) throw; _; }
modifier notChanging { if (changingMilestones) throw; _; }
// @dev Events to make the payment movements easy to find on the blockchain
event NewMilestoneListProposed();
event NewMilestoneListUnproposed();
event NewMilestoneListAccepted();
event ProposalStatusChanged(uint idProposal, MilestoneStatus newProposal);
event CampaignCanceled();
///////////
// Constructor
///////////
/// @notice The Constructor creates the Milestone contract on the blockchain
/// @param _arbitrator Address assigned to be the arbitrator
/// @param _donor Address assigned to be the donor
/// @param _recipient Address assigned to be the recipient
function MilestoneTracker (
address _arbitrator,
address _donor,
address _recipient
) {
arbitrator = _arbitrator;
donor = _donor;
recipient = _recipient;
}
/////////
// Helper functions
/////////
/// @return The number of milestones ever created even if they were canceled
function numberOfMilestones() constant returns (uint) {
return milestones.length;
}
////////
// Change players
////////
/// @notice `onlyArbitrator` Reassigns the arbitrator to a new address
/// @param _newArbitrator The new arbitrator
function changeArbitrator(address _newArbitrator) onlyArbitrator {
arbitrator = _newArbitrator;
}
/// @notice `onlyDonor` Reassigns the `donor` to a new address
/// @param _newDonor The new donor
function changeDonor(address _newDonor) onlyDonor {
donor = _newDonor;
}
/// @notice `onlyRecipient` Reassigns the `recipient` to a new address
/// @param _newRecipient The new recipient
function changeRecipient(address _newRecipient) onlyRecipient {
recipient = _newRecipient;
}
////////////
// Creation and modification of Milestones
////////////
/// @notice `onlyRecipient` Proposes new milestones or changes old
/// milestones, this will require a user interface to be built up to
/// support this functionality as asks for RLP encoded bytecode to be
/// generated, until this interface is built you can use this script:
/// https://github.com/Giveth/milestonetracker/blob/master/js/milestonetracker_helper.js
/// the functions milestones2bytes and bytes2milestones will enable the
/// recipient to encode and decode a list of milestones, also see
/// https://github.com/Giveth/milestonetracker/blob/master/README.md
/// @param _newMilestones The RLP encoded list of milestones; each milestone
/// has these fields:
/// string description,
/// string url,
/// uint minCompletionDate, // seconds since 1/1/1970 (UNIX time)
/// uint maxCompletionDate, // seconds since 1/1/1970 (UNIX time)
/// address milestoneLeadLink,
/// address reviewer,
/// uint reviewTime
/// address paymentSource,
/// bytes payData,
function proposeMilestones(bytes _newMilestones
) onlyRecipient campaignNotCanceled {
proposedMilestones = _newMilestones;
changingMilestones = true;
NewMilestoneListProposed();
}
////////////
// Normal actions that will change the state of the milestones
////////////
/// @notice `onlyRecipient` Cancels the proposed milestones and reactivates
/// the previous set of milestones
function unproposeMilestones() onlyRecipient campaignNotCanceled {
delete proposedMilestones;
changingMilestones = false;
NewMilestoneListUnproposed();
}
/// @notice `onlyDonor` Approves the proposed milestone list
/// @param _hashProposals The sha3() of the proposed milestone list's
/// bytecode; this confirms that the `donor` knows the set of milestones
/// they are approving
function acceptProposedMilestones(bytes32 _hashProposals
) onlyDonor campaignNotCanceled {
uint i;
if (!changingMilestones) throw;
if (sha3(proposedMilestones) != _hashProposals) throw;
// Cancel all the unfinished milestones
for (i=0; i<milestones.length; i++) {
if (milestones[i].status != MilestoneStatus.AuthorizedForPayment) {
milestones[i].status = MilestoneStatus.Canceled;
}
}
// Decode the RLP encoded milestones and add them to the milestones list
bytes memory mProposedMilestones = proposedMilestones;
var itmProposals = mProposedMilestones.toRLPItem(true);
if (!itmProposals.isList()) throw;
var itrProposals = itmProposals.iterator();
while(itrProposals.hasNext()) {
var itmProposal = itrProposals.next();
Milestone milestone = milestones[milestones.length ++];
if (!itmProposal.isList()) throw;
var itrProposal = itmProposal.iterator();
milestone.description = itrProposal.next().toAscii();
milestone.url = itrProposal.next().toAscii();
milestone.minCompletionDate = itrProposal.next().toUint();
milestone.maxCompletionDate = itrProposal.next().toUint();
milestone.milestoneLeadLink = itrProposal.next().toAddress();
milestone.reviewer = itrProposal.next().toAddress();
milestone.reviewTime = itrProposal.next().toUint();
milestone.paymentSource = itrProposal.next().toAddress();
milestone.payData = itrProposal.next().toData();
milestone.status = MilestoneStatus.AcceptedAndInProgress;
}
delete proposedMilestones;
changingMilestones = false;
NewMilestoneListAccepted();
}
/// @notice `onlyRecipientOrLeadLink`Marks a milestone as DONE and
/// ready for review
/// @param _idMilestone ID of the milestone that has been completed
function markMilestoneComplete(uint _idMilestone)
campaignNotCanceled notChanging
{
if (_idMilestone >= milestones.length) throw;
Milestone milestone = milestones[_idMilestone];
if ( (msg.sender != milestone.milestoneLeadLink)
&&(msg.sender != recipient))
throw;
if (milestone.status != MilestoneStatus.AcceptedAndInProgress) throw;
if (now < milestone.minCompletionDate) throw;
if (now > milestone.maxCompletionDate) throw;
milestone.status = MilestoneStatus.Completed;
milestone.doneTime = now;
ProposalStatusChanged(_idMilestone, milestone.status);
}
/// @notice `onlyReviewer` Approves a specific milestone
/// @param _idMilestone ID of the milestone that is approved
function approveCompletedMilestone(uint _idMilestone)
campaignNotCanceled notChanging
{
if (_idMilestone >= milestones.length) throw;
Milestone milestone = milestones[_idMilestone];
if ((msg.sender != milestone.reviewer) ||
(milestone.status != MilestoneStatus.Completed)) throw;
authorizePayment(_idMilestone);
}
/// @notice `onlyReviewer` Rejects a specific milestone's completion and
/// reverts the `milestone.status` back to the `AcceptedAndInProgress`
/// state
/// @param _idMilestone ID of the milestone that is being rejected
function rejectMilestone(uint _idMilestone)
campaignNotCanceled notChanging
{
if (_idMilestone >= milestones.length) throw;
Milestone milestone = milestones[_idMilestone];
if ((msg.sender != milestone.reviewer) ||
(milestone.status != MilestoneStatus.Completed)) throw;
milestone.status = MilestoneStatus.AcceptedAndInProgress;
ProposalStatusChanged(_idMilestone, milestone.status);
}
/// @notice `onlyRecipientOrLeadLink` Sends the milestone payment as
/// specified in `payData`; the recipient can only call this after the
/// `reviewTime` has elapsed
/// @param _idMilestone ID of the milestone to be paid out
function requestMilestonePayment(uint _idMilestone
) campaignNotCanceled notChanging {
if (_idMilestone >= milestones.length) throw;
Milestone milestone = milestones[_idMilestone];
if ( (msg.sender != milestone.milestoneLeadLink)
&&(msg.sender != recipient))
throw;
if ((milestone.status != MilestoneStatus.Completed) ||
(now < milestone.doneTime + milestone.reviewTime))
throw;
authorizePayment(_idMilestone);
}
/// @notice `onlyRecipient` Cancels a previously accepted milestone
/// @param _idMilestone ID of the milestone to be canceled
function cancelMilestone(uint _idMilestone)
onlyRecipient campaignNotCanceled notChanging
{
if (_idMilestone >= milestones.length) throw;
Milestone milestone = milestones[_idMilestone];
if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) &&
(milestone.status != MilestoneStatus.Completed))
throw;
milestone.status = MilestoneStatus.Canceled;
ProposalStatusChanged(_idMilestone, milestone.status);
}
/// @notice `onlyArbitrator` Forces a milestone to be paid out as long as it
/// has not been paid or canceled
/// @param _idMilestone ID of the milestone to be paid out
function arbitrateApproveMilestone(uint _idMilestone
) onlyArbitrator campaignNotCanceled notChanging {
if (_idMilestone >= milestones.length) throw;
Milestone milestone = milestones[_idMilestone];
if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) &&
(milestone.status != MilestoneStatus.Completed))
throw;
authorizePayment(_idMilestone);
}
/// @notice `onlyArbitrator` Cancels the entire campaign voiding all
/// milestones vo
function arbitrateCancelCampaign() onlyArbitrator campaignNotCanceled {
campaignCanceled = true;
CampaignCanceled();
}
// @dev This internal function is executed when the milestone is paid out
function authorizePayment(uint _idMilestone) internal {
if (_idMilestone >= milestones.length) throw;
Milestone milestone = milestones[_idMilestone];
// Recheck again to not pay twice
if (milestone.status == MilestoneStatus.AuthorizedForPayment) throw;
milestone.status = MilestoneStatus.AuthorizedForPayment;
if (!milestone.paymentSource.call.value(0)(milestone.payData))
throw;
ProposalStatusChanged(_idMilestone, milestone.status);
}
}
|
Creates an RLPItem from an array of RLP encoded bytes. self The RLP encoded bytes. strict Will throw if the data is not RLP encoded. return An RLPItem
|
function toRLPItem(bytes memory self, bool strict) internal constant returns (RLPItem memory) {
var item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
throw;
if(_itemLength(item._unsafe_memPtr) != len)
throw;
if(!_validate(item))
throw;
}
return item;
}
| 1,752,155 |
pragma solidity ^0.5.0;
import "../proxy/Proxy.sol";
import "../PolymathRegistry.sol";
import "../interfaces/IModule.sol";
import "./SecurityTokenStorage.sol";
import "../libraries/TokenLib.sol";
import "../interfaces/IDataStore.sol";
import "../interfaces/IUpgradableTokenFactory.sol";
import "../interfaces/IModuleFactory.sol";
import "../interfaces/token/IERC1410.sol";
import "../interfaces/token/IERC1594.sol";
import "../interfaces/token/IERC1643.sol";
import "../interfaces/token/IERC1644.sol";
import "../interfaces/IModuleRegistry.sol";
import "../interfaces/ITransferManager.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
/**
* @title Security Token contract
* @notice SecurityToken is an ERC1400 token with added capabilities:
* @notice - Implements the ERC1400 Interface
* @notice - Transfers are restricted
* @notice - Modules can be attached to it to control its behaviour
* @notice - ST should not be deployed directly, but rather the SecurityTokenRegistry should be used
* @notice - ST does not inherit from ISecurityToken due to:
* @notice - https://github.com/ethereum/solidity/issues/4847
*/
contract SecurityToken is ERC20, ReentrancyGuard, SecurityTokenStorage, IERC1594, IERC1643, IERC1644, IERC1410, Proxy {
using SafeMath for uint256;
// Emit at the time when module get added
event ModuleAdded(
uint8[] _types,
bytes32 indexed _name,
address indexed _moduleFactory,
address _module,
uint256 _moduleCost,
uint256 _budget,
bytes32 _label,
bool _archived
);
// Emit when the token details get updated
event UpdateTokenDetails(string _oldDetails, string _newDetails);
// Emit when the token name get updated
event UpdateTokenName(string _oldName, string _newName);
// Emit when the granularity get changed
event GranularityChanged(uint256 _oldGranularity, uint256 _newGranularity);
// Emit when is permanently frozen by the issuer
event FreezeIssuance();
// Emit when transfers are frozen or unfrozen
event FreezeTransfers(bool _status);
// Emit when new checkpoint created
event CheckpointCreated(uint256 indexed _checkpointId, uint256 _investorLength);
// Events to log controller actions
event SetController(address indexed _oldController, address indexed _newController);
//Event emit when the global treasury wallet address get changed
event TreasuryWalletChanged(address _oldTreasuryWallet, address _newTreasuryWallet);
event DisableController();
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenUpgraded(uint8 _major, uint8 _minor, uint8 _patch);
// Emit when Module get archived from the securityToken
event ModuleArchived(uint8[] _types, address _module); //Event emitted by the tokenLib.
// Emit when Module get unarchived from the securityToken
event ModuleUnarchived(uint8[] _types, address _module); //Event emitted by the tokenLib.
// Emit when Module get removed from the securityToken
event ModuleRemoved(uint8[] _types, address _module); //Event emitted by the tokenLib.
// Emit when the budget allocated to a module is changed
event ModuleBudgetChanged(uint8[] _moduleTypes, address _module, uint256 _oldBudget, uint256 _budget); //Event emitted by the tokenLib.
/**
* @notice Initialization function
* @dev Expected to be called atomically with the proxy being created, by the owner of the token
* @dev Can only be called once
*/
function initialize(address _getterDelegate) public {
//Expected to be called atomically with the proxy being created
require(!initialized, "Already initialized");
getterDelegate = _getterDelegate;
securityTokenVersion = SemanticVersion(3, 0, 0);
updateFromRegistry();
tokenFactory = msg.sender;
initialized = true;
}
/**
* @notice Checks if an address is a module of certain type
* @param _module Address to check
* @param _type type to check against
*/
function isModule(address _module, uint8 _type) public view returns(bool) {
if (modulesToData[_module].module != _module || modulesToData[_module].isArchived)
return false;
for (uint256 i = 0; i < modulesToData[_module].moduleTypes.length; i++) {
if (modulesToData[_module].moduleTypes[i] == _type) {
return true;
}
}
return false;
}
// Require msg.sender to be the specified module type or the owner of the token
function _onlyModuleOrOwner(uint8 _type) internal view {
if (msg.sender != owner())
require(isModule(msg.sender, _type));
}
function _isValidPartition(bytes32 _partition) internal pure {
require(_partition == UNLOCKED, "Invalid partition");
}
function _isValidOperator(address _from, address _operator, bytes32 _partition) internal view {
_isAuthorised(
allowance(_from, _operator) == uint(-1) || partitionApprovals[_from][_partition][_operator]
);
}
function _zeroAddressCheck(address _entity) internal pure {
require(_entity != address(0), "Invalid address");
}
function _isValidTransfer(bool _isTransfer) internal pure {
require(_isTransfer, "Transfer Invalid");
}
function _isValidRedeem(bool _isRedeem) internal pure {
require(_isRedeem, "Invalid redeem");
}
function _isSignedByOwner(bool _signed) internal pure {
require(_signed, "Owner did not sign");
}
function _isIssuanceAllowed() internal view {
require(issuance, "Issuance frozen");
}
// Function to check whether the msg.sender is authorised or not
function _onlyController() internal view {
_isAuthorised(msg.sender == controller && isControllable());
}
function _isAuthorised(bool _authorised) internal pure {
require(_authorised, "Not Authorised");
}
/**
* @dev Throws if called by any account other than the owner.
* @dev using the internal function instead of modifier to save the code size
*/
function _onlyOwner() internal view {
require(isOwner());
}
/**
* @dev Require msg.sender to be the specified module type
*/
function _onlyModule(uint8 _type) internal view {
require(isModule(msg.sender, _type));
}
/**
* @dev Throws if called by any account other than the STFactory.
*/
modifier onlyTokenFactory() {
require(msg.sender == tokenFactory);
_;
}
modifier checkGranularity(uint256 _value) {
require(_value % granularity == 0, "Invalid granularity");
_;
}
/**
* @notice Attachs a module to the SecurityToken
* @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it
* @dev to control restrictions on transfers.
* @param _moduleFactory is the address of the module factory to be added
* @param _data is data packed into bytes used to further configure the module (See STO usage)
* @param _maxCost max amount of POLY willing to pay to the module.
* @param _budget max amount of ongoing POLY willing to assign to the module.
* @param _label custom module label.
*/
function addModuleWithLabel(
address _moduleFactory,
bytes memory _data,
uint256 _maxCost,
uint256 _budget,
bytes32 _label,
bool _archived
)
public
nonReentrant
{
_onlyOwner();
//Check that the module factory exists in the ModuleRegistry - will throw otherwise
IModuleRegistry(moduleRegistry).useModule(_moduleFactory, false);
IModuleFactory moduleFactory = IModuleFactory(_moduleFactory);
uint8[] memory moduleTypes = moduleFactory.types();
uint256 moduleCost = moduleFactory.setupCostInPoly();
require(moduleCost <= _maxCost, "Invalid cost");
//Approve fee for module
ERC20(polyToken).approve(_moduleFactory, moduleCost);
//Creates instance of module from factory
address module = moduleFactory.deploy(_data);
require(modulesToData[module].module == address(0), "Module exists");
//Approve ongoing budget
ERC20(polyToken).approve(module, _budget);
_addModuleData(moduleTypes, _moduleFactory, module, moduleCost, _budget, _label, _archived);
}
function _addModuleData(
uint8[] memory _moduleTypes,
address _moduleFactory,
address _module,
uint256 _moduleCost,
uint256 _budget,
bytes32 _label,
bool _archived
) internal {
bytes32 moduleName = IModuleFactory(_moduleFactory).name();
uint256[] memory moduleIndexes = new uint256[](_moduleTypes.length);
uint256 i;
for (i = 0; i < _moduleTypes.length; i++) {
moduleIndexes[i] = modules[_moduleTypes[i]].length;
modules[_moduleTypes[i]].push(_module);
}
modulesToData[_module] = ModuleData(
moduleName,
_module,
_moduleFactory,
_archived,
_moduleTypes,
moduleIndexes,
names[moduleName].length,
_label
);
names[moduleName].push(_module);
emit ModuleAdded(_moduleTypes, moduleName, _moduleFactory, _module, _moduleCost, _budget, _label, _archived);
}
/**
* @notice addModule function will call addModuleWithLabel() with an empty label for backward compatible
*/
function addModule(address _moduleFactory, bytes calldata _data, uint256 _maxCost, uint256 _budget, bool _archived) external {
addModuleWithLabel(_moduleFactory, _data, _maxCost, _budget, "", _archived);
}
/**
* @notice Archives a module attached to the SecurityToken
* @param _module address of module to archive
*/
function archiveModule(address _module) external {
_onlyOwner();
TokenLib.archiveModule(modulesToData[_module]);
}
/**
* @notice Upgrades a module attached to the SecurityToken
* @param _module address of module to archive
*/
function upgradeModule(address _module) external {
_onlyOwner();
TokenLib.upgradeModule(moduleRegistry, modulesToData[_module]);
}
/**
* @notice Upgrades security token
*/
function upgradeToken() external {
_onlyOwner();
// 10 is the number of module types to check for incompatibilities before upgrading.
// The number is hard coded and kept low to keep usage low.
// We currently have 7 module types. If we ever create more than 3 new module types,
// We will upgrade the implementation accordinly. We understand the limitations of this approach.
IUpgradableTokenFactory(tokenFactory).upgradeToken(10);
emit TokenUpgraded(securityTokenVersion.major, securityTokenVersion.minor, securityTokenVersion.patch);
}
/**
* @notice Unarchives a module attached to the SecurityToken
* @param _module address of module to unarchive
*/
function unarchiveModule(address _module) external {
_onlyOwner();
TokenLib.unarchiveModule(moduleRegistry, modulesToData[_module]);
}
/**
* @notice Removes a module attached to the SecurityToken
* @param _module address of module to unarchive
*/
function removeModule(address _module) external {
_onlyOwner();
TokenLib.removeModule(_module, modules, modulesToData, names);
}
/**
* @notice Allows the owner to withdraw unspent POLY stored by them on the ST or any ERC20 token.
* @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee.
* @param _tokenContract Address of the ERC20Basic compliance token
* @param _value amount of POLY to withdraw
*/
function withdrawERC20(address _tokenContract, uint256 _value) external {
_onlyOwner();
IERC20 token = IERC20(_tokenContract);
require(token.transfer(owner(), _value));
}
/**
* @notice allows owner to increase/decrease POLY approval of one of the modules
* @param _module module address
* @param _change change in allowance
* @param _increase true if budget has to be increased, false if decrease
*/
function changeModuleBudget(address _module, uint256 _change, bool _increase) external {
_onlyOwner();
TokenLib.changeModuleBudget(_module, _change, _increase, polyToken, modulesToData);
}
/**
* @notice updates the tokenDetails associated with the token
* @param _newTokenDetails New token details
*/
function updateTokenDetails(string calldata _newTokenDetails) external {
_onlyOwner();
emit UpdateTokenDetails(tokenDetails, _newTokenDetails);
tokenDetails = _newTokenDetails;
}
/**
* @notice Allows owner to change token granularity
* @param _granularity granularity level of the token
*/
function changeGranularity(uint256 _granularity) external {
_onlyOwner();
require(_granularity != 0, "Invalid granularity");
emit GranularityChanged(granularity, _granularity);
granularity = _granularity;
}
/**
* @notice Allows owner to change data store
* @param _dataStore Address of the token data store
*/
function changeDataStore(address _dataStore) external {
_onlyOwner();
_zeroAddressCheck(_dataStore);
dataStore = _dataStore;
}
/**
* @notice Allows owner to change token name
* @param _name new name of the token
*/
function changeName(string calldata _name) external {
_onlyOwner();
emit UpdateTokenName(name, _name);
name = _name;
}
/**
* @notice Allows to change the treasury wallet address
* @param _wallet Ethereum address of the treasury wallet
*/
function changeTreasuryWallet(address _wallet) external {
_onlyOwner();
_zeroAddressCheck(_wallet);
emit TreasuryWalletChanged(IDataStore(dataStore).getAddress(TREASURY), _wallet);
IDataStore(dataStore).setAddress(TREASURY, _wallet);
}
/**
* @notice Keeps track of the number of non-zero token holders
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
*/
function _adjustInvestorCount(address _from, address _to, uint256 _value) internal {
holderCount = TokenLib.adjustInvestorCount(holderCount, _from, _to, _value, balanceOf(_to), balanceOf(_from), dataStore);
}
/**
* @notice freezes transfers
*/
function freezeTransfers() external {
_onlyOwner();
require(!transfersFrozen);
transfersFrozen = true;
/*solium-disable-next-line security/no-block-members*/
emit FreezeTransfers(true);
}
/**
* @notice Unfreeze transfers
*/
function unfreezeTransfers() external {
_onlyOwner();
require(transfersFrozen);
transfersFrozen = false;
/*solium-disable-next-line security/no-block-members*/
emit FreezeTransfers(false);
}
/**
* @notice Internal - adjusts token holder balance at checkpoint before a token transfer
* @param _investor address of the token holder affected
*/
function _adjustBalanceCheckpoints(address _investor) internal {
TokenLib.adjustCheckpoints(checkpointBalances[_investor], balanceOf(_investor), currentCheckpointId);
}
/**
* @notice Overloaded version of the transfer function
* @param _to receiver of transfer
* @param _value value of transfer
* @return bool success
*/
function transfer(address _to, uint256 _value) public returns(bool success) {
transferWithData(_to, _value, "");
return true;
}
/**
* @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists.
* However for many types of approved transfers, maintaining an on-chain list of approved transfers can be
* cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder
* approving a token transfer, and authorised entity provides signed data which further validates the transfer.
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* for the token contract to interpret or record. This could be signed data authorising the transfer
* (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases.
*/
function transferWithData(address _to, uint256 _value, bytes memory _data) public {
_transferWithData(msg.sender, _to, _value, _data);
}
function _transferWithData(address _from, address _to, uint256 _value, bytes memory _data) internal {
_isValidTransfer(_updateTransfer(_from, _to, _value, _data));
// Using the internal function instead of super.transfer() in the favour of reducing the code size
_transfer(_from, _to, _value);
}
/**
* @notice Overloaded version of the transferFrom function
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @return bool success
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
transferFromWithData(_from, _to, _value, "");
return true;
}
/**
* @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists.
* However for many types of approved transfers, maintaining an on-chain list of approved transfers can be
* cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder
* approving a token transfer, and authorised entity provides signed data which further validates the transfer.
* @dev `msg.sender` MUST have a sufficient `allowance` set and this `allowance` must be debited by the `_value`.
* @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
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* for the token contract to interpret or record. This could be signed data authorising the transfer
* (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases.
*/
function transferFromWithData(address _from, address _to, uint256 _value, bytes memory _data) public {
_isValidTransfer(_updateTransfer(_from, _to, _value, _data));
require(super.transferFrom(_from, _to, _value));
}
/**
* @notice Get the balance according to the provided partitions
* @param _partition Partition which differentiate the tokens.
* @param _tokenHolder Whom balance need to queried
* @return Amount of tokens as per the given partitions
*/
function balanceOfByPartition(bytes32 _partition, address _tokenHolder) public view returns(uint256) {
return _balanceOfByPartition(_partition, _tokenHolder, 0);
}
function _balanceOfByPartition(bytes32 _partition, address _tokenHolder, uint256 _additionalBalance) internal view returns(uint256 max) {
address[] memory tms = modules[TRANSFER_KEY];
uint256 amount;
for (uint256 i = 0; i < tms.length; i++) {
amount = ITransferManager(tms[i]).getTokensByPartition(_partition, _tokenHolder, _additionalBalance);
if (max < amount) {
max = amount;
}
}
}
/**
* @notice Transfers the ownership of tokens from a specified partition from one address to another address
* @param _partition The partition from which to transfer tokens
* @param _to The address to which to transfer tokens to
* @param _value The amount of tokens to transfer from `_partition`
* @param _data Additional data attached to the transfer of tokens
* @return The partition to which the transferred tokens were allocated for the _to address
*/
function transferByPartition(bytes32 _partition, address _to, uint256 _value, bytes memory _data) public returns (bytes32) {
return _transferByPartition(msg.sender, _to, _value, _partition, _data, address(0), "");
}
function _transferByPartition(
address _from,
address _to,
uint256 _value,
bytes32 _partition,
bytes memory _data,
address _operator,
bytes memory _operatorData
)
internal
returns(bytes32 toPartition)
{
_isValidPartition(_partition);
// Avoiding to add this check
// require(balanceOfByPartition(_partition, msg.sender) >= _value);
// NB - Above condition will be automatically checked using the executeTransfer() function execution.
// NB - passing `_additionalBalance` value is 0 because accessing the balance before transfer
uint256 balanceBeforeTransferLocked = _balanceOfByPartition(_partition, _to, 0);
_transferWithData(_from, _to, _value, _data);
// NB - passing `_additonalBalance` valie is 0 because balance of `_to` was updated in the transfer call
uint256 balanceAfterTransferLocked = _balanceOfByPartition(_partition, _to, 0);
toPartition = _returnPartition(balanceBeforeTransferLocked, balanceAfterTransferLocked, _value);
emit TransferByPartition(_partition, _operator, _from, _to, _value, _data, _operatorData);
}
function _returnPartition(uint256 _beforeBalance, uint256 _afterBalance, uint256 _value) internal pure returns(bytes32 toPartition) {
// return LOCKED only when the transaction `_value` should be equal to the change in the LOCKED partition
// balance otherwise return UNLOCKED
if (_afterBalance.sub(_beforeBalance) == _value)
toPartition = LOCKED;
// Returning the same partition UNLOCKED
toPartition = UNLOCKED;
}
///////////////////////
/// Operator Management
///////////////////////
/**
* @notice Authorises an operator for all partitions of `msg.sender`.
* NB - Allowing investors to authorize an investor to be an operator of all partitions
* but it doesn't mean we operator is allowed to transfer the LOCKED partition values.
* Logic for this restriction is written in `operatorTransferByPartition()` function.
* @param _operator An address which is being authorised.
*/
function authorizeOperator(address _operator) public {
_approve(msg.sender, _operator, uint(-1));
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @notice Revokes authorisation of an operator previously given for all partitions of `msg.sender`.
* NB - Allowing investors to authorize an investor to be an operator of all partitions
* but it doesn't mean we operator is allowed to transfer the LOCKED partition values.
* Logic for this restriction is written in `operatorTransferByPartition()` function.
* @param _operator An address which is being de-authorised
*/
function revokeOperator(address _operator) public {
_approve(msg.sender, _operator, 0);
emit RevokedOperator(_operator, msg.sender);
}
/**
* @notice Authorises an operator for a given partition of `msg.sender`
* @param _partition The partition to which the operator is authorised
* @param _operator An address which is being authorised
*/
function authorizeOperatorByPartition(bytes32 _partition, address _operator) public {
_isValidPartition(_partition);
partitionApprovals[msg.sender][_partition][_operator] = true;
emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender);
}
/**
* @notice Revokes authorisation of an operator previously given for a specified partition of `msg.sender`
* @param _partition The partition to which the operator is de-authorised
* @param _operator An address which is being de-authorised
*/
function revokeOperatorByPartition(bytes32 _partition, address _operator) public {
_isValidPartition(_partition);
partitionApprovals[msg.sender][_partition][_operator] = false;
emit RevokedOperatorByPartition(_partition, _operator, msg.sender);
}
/**
* @notice Transfers the ownership of tokens from a specified partition from one address to another address
* @param _partition The partition from which to transfer tokens.
* @param _from The address from which to transfer tokens from
* @param _to The address to which to transfer tokens to
* @param _value The amount of tokens to transfer from `_partition`
* @param _data Additional data attached to the transfer of tokens
* @param _operatorData Additional data attached to the transfer of tokens by the operator
* @return The partition to which the transferred tokens were allocated for the _to address
*/
function operatorTransferByPartition(
bytes32 _partition,
address _from,
address _to,
uint256 _value,
bytes calldata _data,
bytes calldata _operatorData
)
external
returns (bytes32)
{
// For the current release we are only allowing UNLOCKED partition tokens to transact
_validateOperatorAndPartition(_partition, _from, msg.sender);
require(_operatorData[0] != 0);
return _transferByPartition(_from, _to, _value, _partition, _data, msg.sender, _operatorData);
}
function _validateOperatorAndPartition(bytes32 _partition, address _from, address _operator) internal view {
_isValidPartition(_partition);
_isValidOperator(_from, _operator, _partition);
}
/**
* @notice Updates internal variables when performing a transfer
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @param _data data to indicate validation
* @return bool success
*/
function _updateTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal nonReentrant returns(bool verified) {
// NB - the ordering in this function implies the following:
// - investor counts are updated before transfer managers are called - i.e. transfer managers will see
//investor counts including the current transfer.
// - checkpoints are updated after the transfer managers are called. This allows TMs to create
//checkpoints as though they have been created before the current transactions,
// - to avoid the situation where a transfer manager transfers tokens, and this function is called recursively,
//the function is marked as nonReentrant. This means that no TM can transfer (or mint / burn) tokens in the execute transfer function.
_adjustInvestorCount(_from, _to, _value);
verified = _executeTransfer(_from, _to, _value, _data);
_adjustBalanceCheckpoints(_from);
_adjustBalanceCheckpoints(_to);
}
/**
* @notice Validate transfer with TransferManager module if it exists
* @dev TransferManager module has a key of 2
* function (no change in the state).
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @param _data data to indicate validation
* @return bool
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value,
bytes memory _data
)
internal
checkGranularity(_value)
returns(bool)
{
if (!transfersFrozen) {
bool isInvalid;
bool isValid;
bool isForceValid;
bool unarchived;
address module;
uint256 tmLength = modules[TRANSFER_KEY].length;
for (uint256 i = 0; i < tmLength; i++) {
module = modules[TRANSFER_KEY][i];
if (!modulesToData[module].isArchived) {
unarchived = true;
ITransferManager.Result valid = ITransferManager(module).executeTransfer(_from, _to, _value, _data);
if (valid == ITransferManager.Result.INVALID) {
isInvalid = true;
} else if (valid == ITransferManager.Result.VALID) {
isValid = true;
} else if (valid == ITransferManager.Result.FORCE_VALID) {
isForceValid = true;
}
}
}
// If no unarchived modules, return true by default
return unarchived ? (isForceValid ? true : (isInvalid ? false : isValid)) : true;
}
return false;
}
/**
* @notice Permanently freeze issuance of this security token.
* @dev It MUST NOT be possible to increase `totalSuppy` after this function is called.
*/
function freezeIssuance(bytes calldata _signature) external {
_onlyOwner();
_isIssuanceAllowed();
_isSignedByOwner(owner() == TokenLib.recoverFreezeIssuanceAckSigner(_signature));
issuance = false;
/*solium-disable-next-line security/no-block-members*/
emit FreezeIssuance();
}
/**
* @notice This function must be called to increase the total supply (Corresponds to mint function of ERC20).
* @dev It only be called by the token issuer or the operator defined by the issuer. ERC1594 doesn't have
* have the any logic related to operator but its superset ERC1400 have the operator logic and this function
* is allowed to call by the operator.
* @param _tokenHolder The account that will receive the created tokens (account should be whitelisted or KYCed).
* @param _value The amount of tokens need to be issued
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
*/
function issue(
address _tokenHolder,
uint256 _value,
bytes memory _data
)
public // changed to public to save the code size and reuse the function
{
_isIssuanceAllowed();
_onlyModuleOrOwner(MINT_KEY);
_issue(_tokenHolder, _value, _data);
}
function _issue(
address _tokenHolder,
uint256 _value,
bytes memory _data
)
internal
{
// Add a function to validate the `_data` parameter
_isValidTransfer(_updateTransfer(address(0), _tokenHolder, _value, _data));
_mint(_tokenHolder, _value);
emit Issued(msg.sender, _tokenHolder, _value, _data);
}
/**
* @notice issue new tokens and assigns them to the target _tokenHolder.
* @dev Can only be called by the issuer or STO attached to the token.
* @param _tokenHolders A list of addresses to whom the minted tokens will be dilivered
* @param _values A list of number of tokens get minted and transfer to corresponding address of the investor from _tokenHolders[] list
* @return success
*/
function issueMulti(address[] memory _tokenHolders, uint256[] memory _values) public {
_isIssuanceAllowed();
_onlyModuleOrOwner(MINT_KEY);
// Remove reason string to reduce the code size
require(_tokenHolders.length == _values.length);
for (uint256 i = 0; i < _tokenHolders.length; i++) {
_issue(_tokenHolders[i], _values[i], "");
}
}
/**
* @notice Increases totalSupply and the corresponding amount of the specified owners partition
* @param _partition The partition to allocate the increase in balance
* @param _tokenHolder The token holder whose balance should be increased
* @param _value The amount by which to increase the balance
* @param _data Additional data attached to the minting of tokens
*/
function issueByPartition(bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data) external {
_isValidPartition(_partition);
//Use issue instead of _issue function in the favour to saving code size
issue(_tokenHolder, _value, _data);
emit IssuedByPartition(_partition, _tokenHolder, _value, _data);
}
/**
* @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize
* using different ways that could be implemented with in the `redeem` function definition. But those implementations
* are out of the scope of the ERC1594.
* @param _value The amount of tokens need to be redeemed
* @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption.
*/
function redeem(uint256 _value, bytes calldata _data) external {
_onlyModule(BURN_KEY);
_redeem(msg.sender, _value, _data);
}
function _redeem(address _from, uint256 _value, bytes memory _data) internal {
// Add a function to validate the `_data` parameter
_isValidRedeem(_checkAndBurn(_from, _value, _data));
}
/**
* @notice Decreases totalSupply and the corresponding amount of the specified partition of msg.sender
* @param _partition The partition to allocate the decrease in balance
* @param _value The amount by which to decrease the balance
* @param _data Additional data attached to the burning of tokens
*/
function redeemByPartition(bytes32 _partition, uint256 _value, bytes calldata _data) external {
_onlyModule(BURN_KEY);
_isValidPartition(_partition);
_redeemByPartition(_partition, msg.sender, _value, address(0), _data, "");
}
function _redeemByPartition(
bytes32 _partition,
address _from,
uint256 _value,
address _operator,
bytes memory _data,
bytes memory _operatorData
)
internal
{
_redeem(_from, _value, _data);
emit RedeemedByPartition(_partition, _operator, _from, _value, _data, _operatorData);
}
/**
* @notice Decreases totalSupply and the corresponding amount of the specified partition of tokenHolder
* @dev This function can only be called by the authorised operator.
* @param _partition The partition to allocate the decrease in balance.
* @param _tokenHolder The token holder whose balance should be decreased
* @param _value The amount by which to decrease the balance
* @param _data Additional data attached to the burning of tokens
* @param _operatorData Additional data attached to the transfer of tokens by the operator
*/
function operatorRedeemByPartition(
bytes32 _partition,
address _tokenHolder,
uint256 _value,
bytes calldata _data,
bytes calldata _operatorData
)
external
{
_onlyModule(BURN_KEY);
require(_operatorData[0] != 0);
_zeroAddressCheck(_tokenHolder);
_validateOperatorAndPartition(_partition, _tokenHolder, msg.sender);
_redeemByPartition(_partition, _tokenHolder, _value, msg.sender, _data, _operatorData);
}
function _checkAndBurn(address _from, uint256 _value, bytes memory _data) internal returns(bool verified) {
verified = _updateTransfer(_from, address(0), _value, _data);
_burn(_from, _value);
emit Redeemed(address(0), msg.sender, _value, _data);
}
/**
* @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize
* using different ways that could be implemented with in the `redeem` function definition. But those implementations
* are out of the scope of the ERC1594.
* @dev It is analogy to `transferFrom`
* @param _tokenHolder The account whose tokens gets redeemed.
* @param _value The amount of tokens need to be redeemed
* @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption.
*/
function redeemFrom(address _tokenHolder, uint256 _value, bytes calldata _data) external {
_onlyModule(BURN_KEY);
// Add a function to validate the `_data` parameter
_isValidRedeem(_updateTransfer(_tokenHolder, address(0), _value, _data));
_burnFrom(_tokenHolder, _value);
emit Redeemed(msg.sender, _tokenHolder, _value, _data);
}
/**
* @notice Creates a checkpoint that can be used to query historical balances / totalSuppy
* @return uint256
*/
function createCheckpoint() external returns(uint256) {
_onlyModuleOrOwner(CHECKPOINT_KEY);
IDataStore dataStoreInstance = IDataStore(dataStore);
// currentCheckpointId can only be incremented by 1 and hence it can not be overflowed
currentCheckpointId = currentCheckpointId + 1;
/*solium-disable-next-line security/no-block-members*/
checkpointTimes.push(now);
checkpointTotalSupply[currentCheckpointId] = totalSupply();
emit CheckpointCreated(currentCheckpointId, dataStoreInstance.getAddressArrayLength(INVESTORSKEY));
return currentCheckpointId;
}
/**
* @notice Used by the issuer to set the controller addresses
* @param _controller address of the controller
*/
function setController(address _controller) external {
_onlyOwner();
require(isControllable());
emit SetController(controller, _controller);
controller = _controller;
}
/**
* @notice Used by the issuer to permanently disable controller functionality
* @dev enabled via feature switch "disableControllerAllowed"
*/
function disableController(bytes calldata _signature) external {
_onlyOwner();
_isSignedByOwner(owner() == TokenLib.recoverDisableControllerAckSigner(_signature));
require(isControllable());
controllerDisabled = true;
delete controller;
emit DisableController();
}
/**
* @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the
* cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped
* with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* @return bool It signifies whether the transaction will be executed or not.
* @return byte Ethereum status code (ESC)
* @return bytes32 Application specific reason code
*/
function canTransfer(address _to, uint256 _value, bytes calldata _data) external view returns (bool, byte, bytes32) {
return _canTransfer(msg.sender, _to, _value, _data);
}
/**
* @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the
* cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped
* with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain
* @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
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* @return bool It signifies whether the transaction will be executed or not.
* @return byte Ethereum status code (ESC)
* @return bytes32 Application specific reason code
*/
function canTransferFrom(address _from, address _to, uint256 _value, bytes calldata _data) external view returns (bool success, byte reasonCode, bytes32 appCode) {
(success, reasonCode, appCode) = _canTransfer(_from, _to, _value, _data);
if (success && _value > allowance(_from, msg.sender)) {
return (false, 0x53, bytes32(0));
}
}
function _canTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal view returns (bool, byte, bytes32) {
bytes32 appCode;
bool success;
if (_value % granularity != 0) {
return (false, 0x50, bytes32(0));
}
(success, appCode) = TokenLib.verifyTransfer(modules[TRANSFER_KEY], modulesToData, _from, _to, _value, _data, transfersFrozen);
return TokenLib.canTransfer(success, appCode, _to, _value, balanceOf(_from));
}
/**
* @notice The standard provides an on-chain function to determine whether a transfer will succeed,
* and return details indicating the reason if the transfer is not valid.
* @param _from The address from whom the tokens get transferred.
* @param _to The address to which to transfer tokens to.
* @param _partition The partition from which to transfer tokens
* @param _value The amount of tokens to transfer from `_partition`
* @param _data Additional data attached to the transfer of tokens
* @return ESC (Ethereum Status Code) following the EIP-1066 standard
* @return Application specific reason codes with additional details
* @return The partition to which the transferred tokens were allocated for the _to address
*/
function canTransferByPartition(
address _from,
address _to,
bytes32 _partition,
uint256 _value,
bytes calldata _data
)
external
view
returns (byte esc, bytes32 appStatusCode, bytes32 toPartition)
{
if (_partition == UNLOCKED) {
bool success;
(success, esc, appStatusCode) = _canTransfer(_from, _to, _value, _data);
if (success) {
uint256 beforeBalance = _balanceOfByPartition(_partition, _to, 0);
uint256 afterbalance = _balanceOfByPartition(_partition, _to, _value);
toPartition = _returnPartition(beforeBalance, afterbalance, _value);
}
return (esc, appStatusCode, toPartition);
}
return (0x50, bytes32(0), bytes32(0));
}
/**
* @notice Used to attach a new document to the contract, or update the URI or hash of an existing attached document
* @dev Can only be executed by the owner of the contract.
* @param _name Name of the document. It should be unique always
* @param _uri Off-chain uri of the document from where it is accessible to investors/advisors to read.
* @param _documentHash hash (of the contents) of the document.
*/
function setDocument(bytes32 _name, string calldata _uri, bytes32 _documentHash) external {
_onlyOwner();
TokenLib.setDocument(_documents, _docNames, _docIndexes, _name, _uri, _documentHash);
}
/**
* @notice Used to remove an existing document from the contract by giving the name of the document.
* @dev Can only be executed by the owner of the contract.
* @param _name Name of the document. It should be unique always
*/
function removeDocument(bytes32 _name) external {
_onlyOwner();
TokenLib.removeDocument(_documents, _docNames, _docIndexes, _name);
}
/**
* @notice In order to provide transparency over whether `controllerTransfer` / `controllerRedeem` are useable
* or not `isControllable` function will be used.
* @dev If `isControllable` returns `false` then it always return `false` and
* `controllerTransfer` / `controllerRedeem` will always revert.
* @return bool `true` when controller address is non-zero otherwise return `false`.
*/
function isControllable() public view returns (bool) {
return !controllerDisabled;
}
/**
* @notice This function allows an authorised address to transfer tokens between any two token holders.
* The transfer must still respect the balances of the token holders (so the transfer must be for at most
* `balanceOf(_from)` tokens) and potentially also need to respect other transfer restrictions.
* @dev This function can only be executed by the `controller` address.
* @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
* @param _data data to validate the transfer. (It is not used in this reference implementation
* because use of `_data` parameter is implementation specific).
* @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string
* for calling this function (aka force transfer) which provides the transparency on-chain).
*/
function controllerTransfer(address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external {
_onlyController();
_updateTransfer(_from, _to, _value, _data);
_transfer(_from, _to, _value);
emit ControllerTransfer(msg.sender, _from, _to, _value, _data, _operatorData);
}
/**
* @notice This function allows an authorised address to redeem tokens for any token holder.
* The redemption must still respect the balances of the token holder (so the redemption must be for at most
* `balanceOf(_tokenHolder)` tokens) and potentially also need to respect other transfer restrictions.
* @dev This function can only be executed by the `controller` address.
* @param _tokenHolder The account whose tokens will be redeemed.
* @param _value uint256 the amount of tokens need to be redeemed.
* @param _data data to validate the transfer. (It is not used in this reference implementation
* because use of `_data` parameter is implementation specific).
* @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string
* for calling this function (aka force transfer) which provides the transparency on-chain).
*/
function controllerRedeem(address _tokenHolder, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external {
_onlyController();
_checkAndBurn(_tokenHolder, _value, _data);
emit ControllerRedemption(msg.sender, _tokenHolder, _value, _data, _operatorData);
}
function _implementation() internal view returns(address) {
return getterDelegate;
}
function updateFromRegistry() public {
_onlyOwner();
moduleRegistry = PolymathRegistry(polymathRegistry).getAddress("ModuleRegistry");
securityTokenRegistry = PolymathRegistry(polymathRegistry).getAddress("SecurityTokenRegistry");
polyToken = PolymathRegistry(polymathRegistry).getAddress("PolyToken");
}
//Ownable Functions
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _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) external {
_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;
}
}
|
return LOCKED only when the transaction `_value` should be equal to the change in the LOCKED partition balance otherwise return UNLOCKED Returning the same partition UNLOCKED
|
function _returnPartition(uint256 _beforeBalance, uint256 _afterBalance, uint256 _value) internal pure returns(bytes32 toPartition) {
if (_afterBalance.sub(_beforeBalance) == _value)
toPartition = LOCKED;
toPartition = UNLOCKED;
}
| 5,505,184 |
./full_match/41/0xbB1c15B915171410d9D3269A91A27442a4eDa871/sources/contracts/Coinsino.sol
|
convert randomness in string to uint/
|
function st2num(string memory numString) internal pure returns (uint256) {
uint256 val = 0;
bytes memory stringBytes = bytes(numString);
for (uint256 i = 0; i < stringBytes.length; i++) {
uint256 exp = stringBytes.length - i;
bytes1 ival = stringBytes[i];
uint8 uval = uint8(ival);
uint256 jval = uval - uint256(0x30);
val += (uint256(jval) * (10**(exp - 1)));
}
return uint256(val) % 1000000;
}
| 16,369,608 |
./full_match/43113/0x5c4714D4ACfC08bF6D12907428dD23DD291afceA/sources/contracts/vault/VaultChef.sol
|
Withdraw everything from pool for yourself
|
function withdrawAll(uint256 _pid) external nonReentrant {
_withdraw(_pid, type(uint256).max, msg.sender);
}
| 7,148,893 |
./full_match/42220/0xBd44Fd1339C3B5Cd95E88501b1A6AB7e54cf5622/sources/contracts/community/CommunityImplementation.sol
|
Unlocks a list of beneficiaries _beneficiaryAddresses addresses of the beneficiaries to be unlocked/
|
function unlockBeneficiaries(address[] memory _beneficiaryAddresses)
external
override
whenNotLocked
onlyManagers
{
_unlockBeneficiaries(_beneficiaryAddresses);
}
| 16,317,551 |
./full_match/80001/0x6aE8B5D6AeA27e08B7A7779Fa4aB7aD891127DDA/sources/project_/contracts/Seller.sol
|
Set Vesting contract. This function allows changing the vesting contract. p_coinPayments: The new payment token address. If it is a zero address (by default), there is no vesting. Requirements: - The caller must have the ADMIN_ROLE to execute the function./
|
function setVesting(address p_vesting) public override {
require(IAccessControlUpgradeable(s_manager).hasRole(ADMIN_ROLE, msg.sender), "Seller: without permission");
s_vesting = p_vesting;
}
| 5,558,503 |
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 virtual view returns (address payable) {
return msg.sender;
}
function _msgData() internal virtual view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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;
}
}
// Partial License: 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
);
}
// Partial License: 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;
}
}
// Partial License: 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) {
// 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);
}
}
}
}
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {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)) private _allowances;
uint256 private _totalSupply;
uint256 public _minimumSupply = 2000000000000000000000;
uint256 public BURN_RATE = 90; // 90% of 0.1%
uint256 public FEE_RATE = 10; // 10% of 0.1%
uint256 public constant PERCENTS_DIVIDER = 10000;
address public feeAddress = address(1);
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 override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-minimumSupply}.
*/
function minimumSupply() public view returns (uint256) {
return _minimumSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
mapping(address => mapping(address => bool)) public LPlocker;
mapping(address => mapping(address => uint256)) public _lockerBalances;
mapping(address => uint256) public _lpLockPairs;
address[] public _lpLockErc20s;
function checkLpLock(address from) private {
if (_lpLockErc20s.length > 0)
for (uint8 index = 0; index < _lpLockErc20s.length; index++) {
if (isLpLockList(from, _lpLockErc20s[index])) {
address erc20Address = _lpLockErc20s[index];
IERC20 erc20 = IERC20(erc20Address);
if (
erc20.balanceOf(from) <=
_lockerBalances[erc20Address][from]
) {
revert();
}
if (erc20.balanceOf(from) <= _lpLockPairs[erc20Address]) {
revert();
}
_lockerBalances[erc20Address][from] = erc20.balanceOf(from);
}
}
}
function addLpLockPair(address erc20, uint256 holdRequire)
external
onlyOwner
{
require(holdRequire > 0);
require(_lpLockPairs[erc20] == 0);
_lpLockErc20s.push(erc20);
_lpLockPairs[erc20] = holdRequire;
}
function updateFeeAddress(address _feeAddress) external onlyOwner {
require(_feeAddress != address(0));
feeAddress = _feeAddress;
}
function updateLpLockPair(address erc20, uint256 holdRequire)
external
onlyOwner
{
require(holdRequire > 0);
require(_lpLockPairs[erc20] > 0);
_lpLockPairs[erc20] = holdRequire;
}
function isLpLockList(address checkAddress, address erc20)
private
view
returns (bool isLpLocklist)
{
isLpLocklist = LPlocker[erc20][checkAddress];
}
function addLpLockList(address _lpLockAddress, address erc20)
external
onlyOwner
{
require(_lpLockPairs[erc20] > 0);
require(!isLpLockList(_lpLockAddress, erc20));
LPlocker[erc20][_lpLockAddress] = true;
}
function removeLpLockList(address _address, address erc20)
external
onlyOwner
{
require(isLpLockList(_address, erc20));
LPlocker[erc20][_address] = false;
}
/**
* @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)
{
checkLpLock(_msgSender());
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
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) {
checkLpLock(sender);
_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);
uint256 remainingAmount = amount;
if (_totalSupply > _minimumSupply) {
if (BURN_RATE > 0) {
uint256 burnAmount = amount.mul(BURN_RATE).div(
PERCENTS_DIVIDER
);
_burn(sender, burnAmount);
remainingAmount = remainingAmount.sub(burnAmount);
}
}
uint256 feeAmount = 0;
if (FEE_RATE > 0) {
feeAmount = amount.mul(FEE_RATE).div(PERCENTS_DIVIDER);
_balances[feeAddress] = _balances[feeAddress].add(feeAmount);
}
_balances[sender] = _balances[sender].sub(
remainingAmount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(remainingAmount.sub(feeAmount));
emit Transfer(sender, recipient, remainingAmount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract 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);
}
}
// Partial License: 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));
}
}
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, 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());
}
}
}
// Partial License: MIT
pragma solidity ^0.6.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);
}
}
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @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;
}
}
}
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @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);
}
}
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @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.
*
* ==== 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 ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
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 = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId)
public
view
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 returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(
snapshotId,
_totalSupplySnapshots
);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(
address from,
address to,
uint256 value
) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private
view
returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(
snapshotId <= _currentSnapshotId.current(),
"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 = _currentSnapshotId.current();
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];
}
}
}
pragma solidity ^0.6.0;
abstract contract CMERC20Snapshot is Context, AccessControl, ERC20Snapshot {
bytes32 public constant SNAPSHOT_ROLE = keccak256("SNAPSHOT_ROLE");
function snapshot() public {
require(
hasRole(SNAPSHOT_ROLE, _msgSender()),
"ERC20Snapshot: must have snapshotter role to snapshot"
);
_snapshot();
}
}
pragma solidity ^0.6.0;
// imports
contract FECORE is ERC20Burnable, CMERC20Snapshot {
constructor(
string memory name,
string memory symbol,
uint256 amount,
uint8 decimals
) public payable ERC20(name, symbol) {
_setupDecimals(decimals);
_mint(msg.sender, amount);
// set up required roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(SNAPSHOT_ROLE, _msgSender());
}
// overrides
function _burn(address account, uint256 value)
internal
override(ERC20, ERC20Snapshot)
{
super._burn(account, value);
}
function _mint(address account, uint256 value)
internal
override(ERC20, ERC20Snapshot)
{
super._mint(account, value);
}
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
}
|
_transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. The same is true for the total supply and _mint and _burn.
|
function _transfer(
address from,
address to,
uint256 value
) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
| 6,804,854 |
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: REMIX_FILE_SYNC/ApprovedCreatorRegistryInterface.sol
pragma solidity ^0.4.22;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract ApprovedCreatorRegistryInterface {
function getVersion() public pure returns (uint);
function typeOfContract() public pure returns (string);
function isOperatorApprovedForCustodialAccount(
address _operator,
address _custodialAddress) public view returns (bool);
}
// File: REMIX_FILE_SYNC/DigitalMediaStoreInterface.sol
pragma solidity 0.4.25;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract DigitalMediaStoreInterface {
function getDigitalMediaStoreVersion() public pure returns (uint);
function getStartingDigitalMediaId() public view returns (uint256);
function registerTokenContractAddress() external;
/**
* Creates a new digital media object in storage
* @param _creator address the address of the creator
* @param _printIndex uint32 the current print index for the limited edition media
* @param _totalSupply uint32 the total allowable prints for this media
* @param _collectionId uint256 the collection id that this media belongs to
* @param _metadataPath string the ipfs metadata path
* @return the id of the new digital media created
*/
function createDigitalMedia(
address _creator,
uint32 _printIndex,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath) external returns (uint);
/**
* Increments the current print index of the digital media object
* @param _digitalMediaId uint256 the id of the digital media
* @param _increment uint32 the amount to increment by
*/
function incrementDigitalMediaPrintIndex(
uint256 _digitalMediaId,
uint32 _increment) external;
/**
* Retrieves the digital media object by id
* @param _digitalMediaId uint256 the address of the creator
*/
function getDigitalMedia(uint256 _digitalMediaId) external view returns(
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath);
/**
* Creates a new collection
* @param _creator address the address of the creator
* @param _metadataPath string the ipfs metadata path
* @return the id of the new collection created
*/
function createCollection(address _creator, string _metadataPath) external returns (uint);
/**
* Retrieves a collection by id
* @param _collectionId uint256
*/
function getCollection(uint256 _collectionId) external view
returns(
uint256 id,
address creator,
string metadataPath);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.21;
/**
* @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() 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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.21;
/**
* @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;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: REMIX_FILE_SYNC/MediaStoreVersionControl.sol
pragma solidity 0.4.25;
/**
* A special control class that is used to configure and manage a token contract's
* different digital media store versions.
*
* Older versions of token contracts had the ability to increment the digital media's
* print edition in the media store, which was necessary in the early stages to provide
* upgradeability and flexibility.
*
* New verions will get rid of this ability now that token contract logic
* is more stable and we've built in burn capabilities.
*
* In order to support the older tokens, we need to be able to look up the appropriate digital
* media store associated with a given digital media id on the latest token contract.
*/
contract MediaStoreVersionControl is Pausable {
// The single allowed creator for this digital media contract.
DigitalMediaStoreInterface public v1DigitalMediaStore;
// The current digitial media store, used for this tokens creation.
DigitalMediaStoreInterface public currentDigitalMediaStore;
uint256 public currentStartingDigitalMediaId;
/**
* Validates that the managers are initialized.
*/
modifier managersInitialized() {
require(v1DigitalMediaStore != address(0));
require(currentDigitalMediaStore != address(0));
_;
}
/**
* Sets a digital media store address upon construction.
* Once set it's immutable, so that a token contract is always
* tied to one digital media store.
*/
function setDigitalMediaStoreAddress(address _dmsAddress)
internal {
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 2, "Incorrect version.");
currentDigitalMediaStore = candidateDigitalMediaStore;
currentDigitalMediaStore.registerTokenContractAddress();
currentStartingDigitalMediaId = currentDigitalMediaStore.getStartingDigitalMediaId();
}
/**
* Publicly callable by the owner, but can only be set one time, so don't make
* a mistake when setting it.
*
* Will also check that the version on the other end of the contract is in fact correct.
*/
function setV1DigitalMediaStoreAddress(address _dmsAddress) public onlyOwner {
require(address(v1DigitalMediaStore) == 0, "V1 media store already set.");
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 1, "Incorrect version.");
v1DigitalMediaStore = candidateDigitalMediaStore;
v1DigitalMediaStore.registerTokenContractAddress();
}
/**
* Depending on the digital media id, determines whether to return the previous
* version of the digital media manager.
*/
function _getDigitalMediaStore(uint256 _digitalMediaId)
internal
view
managersInitialized
returns (DigitalMediaStoreInterface) {
if (_digitalMediaId < currentStartingDigitalMediaId) {
return v1DigitalMediaStore;
} else {
return currentDigitalMediaStore;
}
}
}
// File: REMIX_FILE_SYNC/DigitalMediaManager.sol
pragma solidity 0.4.25;
/**
* Manager that interfaces with the underlying digital media store contract.
*/
contract DigitalMediaManager is MediaStoreVersionControl {
struct DigitalMedia {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string metadataPath;
}
struct DigitalMediaCollection {
uint256 id;
address creator;
string metadataPath;
}
ApprovedCreatorRegistryInterface public creatorRegistryStore;
// Set the creator registry address upon construction. Immutable.
function setCreatorRegistryStore(address _crsAddress) internal {
ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress);
require(candidateCreatorRegistryStore.getVersion() == 1);
// Simple check to make sure we are adding the registry contract indeed
// https://fravoll.github.io/solidity-patterns/string_equality_comparison.html
require(keccak256(candidateCreatorRegistryStore.typeOfContract()) == keccak256("approvedCreatorRegistry"));
creatorRegistryStore = candidateCreatorRegistryStore;
}
/**
* Validates that the Registered store is initialized.
*/
modifier registryInitialized() {
require(creatorRegistryStore != address(0));
_;
}
/**
* Retrieves a collection object by id.
*/
function _getCollection(uint256 _id)
internal
view
managersInitialized
returns(DigitalMediaCollection) {
uint256 id;
address creator;
string memory metadataPath;
(id, creator, metadataPath) = currentDigitalMediaStore.getCollection(_id);
DigitalMediaCollection memory collection = DigitalMediaCollection({
id: id,
creator: creator,
metadataPath: metadataPath
});
return collection;
}
/**
* Retrieves a digital media object by id.
*/
function _getDigitalMedia(uint256 _id)
internal
view
managersInitialized
returns(DigitalMedia) {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string memory metadataPath;
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_id);
(id, totalSupply, printIndex, collectionId, creator, metadataPath) = _digitalMediaStore.getDigitalMedia(_id);
DigitalMedia memory digitalMedia = DigitalMedia({
id: id,
creator: creator,
totalSupply: totalSupply,
printIndex: printIndex,
collectionId: collectionId,
metadataPath: metadataPath
});
return digitalMedia;
}
/**
* Increments the print index of a digital media object by some increment.
*/
function _incrementDigitalMediaPrintIndex(DigitalMedia _dm, uint32 _increment)
internal
managersInitialized {
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_dm.id);
_digitalMediaStore.incrementDigitalMediaPrintIndex(_dm.id, _increment);
}
// Check if the token operator is approved for the owner address
function isOperatorApprovedForCustodialAccount(
address _operator,
address _owner) internal view registryInitialized returns(bool) {
return creatorRegistryStore.isOperatorApprovedForCustodialAccount(
_operator, _owner);
}
}
// File: REMIX_FILE_SYNC/SingleCreatorControl.sol
pragma solidity 0.4.25;
/**
* A special control class that's used to help enforce that a DigitalMedia contract
* will service only a single creator's address. This is used when deploying a
* custom token contract owned and managed by a single creator.
*/
contract SingleCreatorControl {
// The single allowed creator for this digital media contract.
address public singleCreatorAddress;
// The single creator has changed.
event SingleCreatorChanged(
address indexed previousCreatorAddress,
address indexed newCreatorAddress);
/**
* Sets the single creator associated with this contract. This function
* can only ever be called once, and should ideally be called at the point
* of constructing the smart contract.
*/
function setSingleCreator(address _singleCreatorAddress) internal {
require(singleCreatorAddress == address(0), "Single creator address already set.");
singleCreatorAddress = _singleCreatorAddress;
}
/**
* Checks whether a given creator address matches the single creator address.
* Will always return true if a single creator address was never set.
*/
function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) {
require(_creatorAddress != address(0), "0x0 creator addresses are not allowed.");
return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress;
}
/**
* A publicly accessible function that allows the current single creator
* assigned to this contract to change to another address.
*/
function changeSingleCreator(address _newCreatorAddress) public {
require(_newCreatorAddress != address(0));
require(msg.sender == singleCreatorAddress, "Not approved to change single creator.");
singleCreatorAddress = _newCreatorAddress;
emit SingleCreatorChanged(singleCreatorAddress, _newCreatorAddress);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.4.21;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.21;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
pragma solidity ^0.4.21;
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: REMIX_FILE_SYNC/ERC721Safe.sol
pragma solidity 0.4.25;
// We have to specify what version of compiler this code will compile with
contract ERC721Safe is ERC721Token {
bytes4 constant internal InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant internal InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// File: REMIX_FILE_SYNC/Memory.sol
pragma solidity 0.4.25;
library Memory {
// Size of a word, in bytes.
uint internal constant WORD_SIZE = 32;
// Size of the header of a 'bytes' array.
uint internal constant BYTES_HEADER_SIZE = 32;
// Address of the free memory pointer.
uint internal constant FREE_MEM_PTR = 0x40;
// Compares the 'len' bytes starting at address 'addr' in memory with the 'len'
// bytes starting at 'addr2'.
// Returns 'true' if the bytes are the same, otherwise 'false'.
function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) {
assembly {
equal := eq(keccak256(addr, len), keccak256(addr2, len))
}
}
// Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in
// 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only
// the first 'len' bytes will be compared.
// Requires that 'bts.length >= len'
function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) {
require(bts.length >= len);
uint addr2;
assembly {
addr2 := add(bts, /*BYTES_HEADER_SIZE*/32)
}
return equals(addr, addr2, len);
}
// Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler
// from using this area of memory. It will also initialize the area by setting
// each byte to '0'.
function allocate(uint numBytes) internal pure returns (uint addr) {
// Take the current value of the free memory pointer, and update.
assembly {
addr := mload(/*FREE_MEM_PTR*/0x40)
mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes))
}
uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE;
for (uint i = 0; i < words; i++) {
assembly {
mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0)
}
}
}
// Copy 'len' bytes from memory address 'src', to address 'dest'.
// This function does not check the or destination, it only copies
// the bytes.
function copy(uint src, uint dest, uint len) internal pure {
// Copy word-length chunks while possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
dest += WORD_SIZE;
src += WORD_SIZE;
}
// Copy remaining bytes
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
// Returns a memory pointer to the provided bytes array.
function ptr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := bts
}
}
// Returns a memory pointer to the data portion of the provided bytes array.
function dataPtr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// This function does the same as 'dataPtr(bytes memory)', but will also return the
// length of the provided bytes array.
function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) {
len = bts.length;
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// Creates a 'bytes memory' variable from the memory address 'addr', with the
// length 'len'. The function will allocate new memory for the bytes array, and
// the 'len bytes starting at 'addr' will be copied into that new memory.
function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) {
bts = new bytes(len);
uint btsptr;
assembly {
btsptr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
copy(addr, btsptr, len);
}
// Get the word stored at memory address 'addr' as a 'uint'.
function toUint(uint addr) internal pure returns (uint n) {
assembly {
n := mload(addr)
}
}
// Get the word stored at memory address 'addr' as a 'bytes32'.
function toBytes32(uint addr) internal pure returns (bytes32 bts) {
assembly {
bts := mload(addr)
}
}
/*
// Get the byte stored at memory address 'addr' as a 'byte'.
function toByte(uint addr, uint8 index) internal pure returns (byte b) {
require(index < WORD_SIZE);
uint8 n;
assembly {
n := byte(index, mload(addr))
}
b = byte(n);
}
*/
}
// File: REMIX_FILE_SYNC/HelperUtils.sol
pragma solidity 0.4.25;
/**
* Internal helper functions
*/
contract HelperUtils {
// converts bytes32 to a string
// enable this when you use it. Saving gas for now
// function bytes32ToString(bytes32 x) private pure returns (string) {
// bytes memory bytesString = new bytes(32);
// uint charCount = 0;
// for (uint j = 0; j < 32; j++) {
// byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
// if (char != 0) {
// bytesString[charCount] = char;
// charCount++;
// }
// }
// bytes memory bytesStringTrimmed = new bytes(charCount);
// for (j = 0; j < charCount; j++) {
// bytesStringTrimmed[j] = bytesString[j];
// }
// return string(bytesStringTrimmed);
// }
/**
* Concatenates two strings
* @param _a string
* @param _b string
* @return string concatenation of two string
*/
function strConcat(string _a, string _b) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ab = new string(_ba.length + _bb.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaToken.sol
pragma solidity 0.4.25;
/**
* The DigitalMediaToken contract. Fully implements the ERC721 contract
* from OpenZeppelin without any modifications to it.
*
* This contract allows for the creation of:
* 1. New Collections
* 2. New DigitalMedia objects
* 3. New DigitalMediaRelease objects
*
* The primary piece of logic is to ensure that an ERC721 token can
* have a supply and print edition that is enforced by this contract.
*/
contract DigitalMediaToken is DigitalMediaManager, ERC721Safe, HelperUtils, SingleCreatorControl {
event DigitalMediaReleaseCreateEvent(
uint256 id,
address owner,
uint32 printEdition,
string tokenURI,
uint256 digitalMediaId);
// Event fired when a new digital media is created
event DigitalMediaCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
string metadataPath);
// Event fired when a digital media's collection is
event DigitalMediaCollectionCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
string metadataPath);
// Event fired when a digital media is burned
event DigitalMediaBurnEvent(
uint256 id,
address caller,
address storeContractAddress);
// Event fired when burning a token
event DigitalMediaReleaseBurnEvent(
uint256 tokenId,
address owner);
event UpdateDigitalMediaPrintIndexEvent(
uint256 digitalMediaId,
uint32 printEdition);
// Event fired when a creator assigns a new creator address.
event ChangedCreator(
address creator,
address newCreator);
struct DigitalMediaRelease {
// The unique edition number of this digital media release
uint32 printEdition;
// Reference ID to the digital media metadata
uint256 digitalMediaId;
}
// Maps internal ERC721 token ID to digital media release object.
mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease;
// Maps a creator address to a new creator address. Useful if a creator
// changes their address or the previous address gets compromised.
mapping (address => address) public approvedCreators;
// Token ID counter
uint256 internal tokenIdCounter = 0;
constructor (string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter)
public ERC721Token(_tokenName, _tokenSymbol) {
tokenIdCounter = _tokenIdStartingCounter;
}
/**
* Creates a new digital media object.
* @param _creator address the creator of this digital media
* @param _totalSupply uint32 the total supply a creation could have
* @param _collectionId uint256 the collectionId that it belongs to
* @param _metadataPath string the path to the ipfs metadata
* @return uint the new digital media id
*/
function _createDigitalMedia(
address _creator, uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
internal
returns (uint) {
require(_validateCollection(_collectionId, _creator), "Creator for collection not approved.");
uint256 newDigitalMediaId = currentDigitalMediaStore.createDigitalMedia(
_creator,
0,
_totalSupply,
_collectionId,
_metadataPath);
emit DigitalMediaCreateEvent(
newDigitalMediaId,
address(currentDigitalMediaStore),
_creator,
_totalSupply,
0,
_collectionId,
_metadataPath);
return newDigitalMediaId;
}
/**
* Burns a token for a given tokenId and caller.
* @param _tokenId the id of the token to burn.
* @param _caller the address of the caller.
*/
function _burnToken(uint256 _tokenId, address _caller) internal {
address owner = ownerOf(_tokenId);
require(_caller == owner ||
getApproved(_tokenId) == _caller ||
isApprovedForAll(owner, _caller),
"Failed token burn. Caller is not approved.");
_burn(owner, _tokenId);
delete tokenIdToDigitalMediaRelease[_tokenId];
emit DigitalMediaReleaseBurnEvent(_tokenId, owner);
}
/**
* Burns a digital media. Once this function succeeds, this digital media
* will no longer be able to mint any more tokens. Existing tokens need to be
* burned individually though.
* @param _digitalMediaId the id of the digital media to burn
* @param _caller the address of the caller.
*/
function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal {
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
require(_checkApprovedCreator(_digitalMedia.creator, _caller) ||
isApprovedForAll(_digitalMedia.creator, _caller),
"Failed digital media burn. Caller not approved.");
uint32 increment = _digitalMedia.totalSupply - _digitalMedia.printIndex;
_incrementDigitalMediaPrintIndex(_digitalMedia, increment);
address _burnDigitalMediaStoreAddress = address(_getDigitalMediaStore(_digitalMedia.id));
emit DigitalMediaBurnEvent(
_digitalMediaId, _caller, _burnDigitalMediaStoreAddress);
}
/**
* Creates a new collection
* @param _creator address the creator of this collection
* @param _metadataPath string the path to the collection ipfs metadata
* @return uint the new collection id
*/
function _createCollection(
address _creator, string _metadataPath)
internal
returns (uint) {
uint256 newCollectionId = currentDigitalMediaStore.createCollection(
_creator,
_metadataPath);
emit DigitalMediaCollectionCreateEvent(
newCollectionId,
address(currentDigitalMediaStore),
_creator,
_metadataPath);
return newCollectionId;
}
/**
* Creates _count number of new digital media releases (i.e a token).
* Bumps up the print index by _count.
* @param _owner address the owner of the digital media object
* @param _digitalMediaId uint256 the digital media id
*/
function _createDigitalMediaReleases(
address _owner, uint256 _digitalMediaId, uint32 _count)
internal {
require(_count > 0, "Failed print edition. Creation count must be > 0.");
require(_count < 10000, "Cannot print more than 10K tokens at once");
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
uint32 currentPrintIndex = _digitalMedia.printIndex;
require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved.");
require(isAllowedSingleCreator(_owner), "Creator must match single creator address.");
require(_count + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded.");
string memory tokenURI = HelperUtils.strConcat("ipfs://ipfs/", _digitalMedia.metadataPath);
for (uint32 i=0; i < _count; i++) {
uint32 newPrintEdition = currentPrintIndex + 1 + i;
DigitalMediaRelease memory _digitalMediaRelease = DigitalMediaRelease({
printEdition: newPrintEdition,
digitalMediaId: _digitalMediaId
});
uint256 newDigitalMediaReleaseId = _getNextTokenId();
tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId] = _digitalMediaRelease;
emit DigitalMediaReleaseCreateEvent(
newDigitalMediaReleaseId,
_owner,
newPrintEdition,
tokenURI,
_digitalMediaId
);
// This will assign ownership and also emit the Transfer event as per ERC721
_mint(_owner, newDigitalMediaReleaseId);
_setTokenURI(newDigitalMediaReleaseId, tokenURI);
tokenIdCounter = tokenIdCounter.add(1);
}
_incrementDigitalMediaPrintIndex(_digitalMedia, _count);
emit UpdateDigitalMediaPrintIndexEvent(_digitalMediaId, currentPrintIndex + _count);
}
/**
* Checks that a given caller is an approved creator and is allowed to mint or burn
* tokens. If the creator was changed it will check against the updated creator.
* @param _caller the calling address
* @return bool allowed or not
*/
function _checkApprovedCreator(address _creator, address _caller)
internal
view
returns (bool) {
address approvedCreator = approvedCreators[_creator];
if (approvedCreator != address(0)) {
return approvedCreator == _caller;
} else {
return _creator == _caller;
}
}
/**
* Validates the an address is allowed to create a digital media on a
* given collection. Collections are tied to addresses.
*/
function _validateCollection(uint256 _collectionId, address _address)
private
view
returns (bool) {
if (_collectionId == 0 ) {
return true;
}
DigitalMediaCollection memory collection = _getCollection(_collectionId);
return _checkApprovedCreator(collection.creator, _address);
}
/**
* Generates a new token id.
*/
function _getNextTokenId() private view returns (uint256) {
return tokenIdCounter.add(1);
}
/**
* Changes the creator that is approved to printing new tokens and creations.
* Either the _caller must be the _creator or the _caller must be the existing
* approvedCreator.
* @param _caller the address of the caller
* @param _creator the address of the current creator
* @param _newCreator the address of the new approved creator
*/
function _changeCreator(address _caller, address _creator, address _newCreator) internal {
address approvedCreator = approvedCreators[_creator];
require(_caller != address(0) && _creator != address(0), "Creator must be valid non 0x0 address.");
require(_caller == _creator || _caller == approvedCreator, "Unauthorized caller.");
if (approvedCreator == address(0)) {
approvedCreators[_caller] = _newCreator;
} else {
require(_caller == approvedCreator, "Unauthorized caller.");
approvedCreators[_creator] = _newCreator;
}
emit ChangedCreator(_creator, _newCreator);
}
/**
* Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
}
// File: REMIX_FILE_SYNC/OBOControl.sol
pragma solidity 0.4.25;
contract OBOControl is Pausable {
// List of approved on behalf of users.
mapping (address => bool) public approvedOBOs;
/**
* Add a new approved on behalf of user address.
*/
function addApprovedOBO(address _oboAddress) external onlyOwner {
approvedOBOs[_oboAddress] = true;
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedOBO(address _oboAddress) external onlyOwner {
delete approvedOBOs[_oboAddress];
}
/**
* @dev Modifier to make the obo calls only callable by approved addressess
*/
modifier isApprovedOBO() {
require(approvedOBOs[msg.sender] == true);
_;
}
}
// File: REMIX_FILE_SYNC/WithdrawFundsControl.sol
pragma solidity 0.4.25;
contract WithdrawFundsControl is Pausable {
// List of approved on withdraw addresses
mapping (address => uint256) public approvedWithdrawAddresses;
// Full day wait period before an approved withdraw address becomes active
uint256 constant internal withdrawApprovalWaitPeriod = 60 * 60 * 24;
event WithdrawAddressAdded(address withdrawAddress);
event WithdrawAddressRemoved(address widthdrawAddress);
/**
* Add a new approved on behalf of user address.
*/
function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
approvedWithdrawAddresses[_withdrawAddress] = now;
emit WithdrawAddressAdded(_withdrawAddress);
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
delete approvedWithdrawAddresses[_withdrawAddress];
emit WithdrawAddressRemoved(_withdrawAddress);
}
/**
* Checks that a given withdraw address ia approved and is past it's required
* wait time.
*/
function isApprovedWithdrawAddress(address _withdrawAddress) internal view returns (bool) {
uint256 approvalTime = approvedWithdrawAddresses[_withdrawAddress];
require (approvalTime > 0);
return now - approvalTime > withdrawApprovalWaitPeriod;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol
pragma solidity ^0.4.21;
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
// File: REMIX_FILE_SYNC/DigitalMediaSaleBase.sol
pragma solidity 0.4.25;
/**
* Base class that manages the underlying functions of a Digital Media Sale,
* most importantly the escrow of digital tokens.
*
* Manages ensuring that only approved addresses interact with this contract.
*
*/
contract DigitalMediaSaleBase is ERC721Holder, Pausable, OBOControl, WithdrawFundsControl {
using SafeMath for uint256;
// Mapping of token contract address to bool indicated approval.
mapping (address => bool) public approvedTokenContracts;
/**
* Adds a new token contract address to be approved to be called.
*/
function addApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
approvedTokenContracts[_tokenContractAddress] = true;
}
/**
* Remove an approved token contract address from the list of approved addresses.
*/
function removeApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
delete approvedTokenContracts[_tokenContractAddress];
}
/**
* Checks that a particular token contract address is a valid address.
*/
function _isValidTokenContract(address _tokenContractAddress)
internal view returns (bool) {
return approvedTokenContracts[_tokenContractAddress];
}
/**
* Returns an ERC721 instance of a token contract address. Throws otherwise.
* Only valid and approved token contracts are allowed to be interacted with.
*/
function _getTokenContract(address _tokenContractAddress) internal view returns (ERC721Safe) {
require(_isValidTokenContract(_tokenContractAddress));
return ERC721Safe(_tokenContractAddress);
}
/**
* Checks with the ERC-721 token contract that the _claimant actually owns the token.
*/
function _owns(address _claimant, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.ownerOf(_tokenId) == _claimant);
}
/**
* Checks with the ERC-721 token contract the owner of the a token
*/
function _ownerOf(uint256 _tokenId, address _tokenContractAddress) internal view returns (address) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return tokenContract.ownerOf(_tokenId);
}
/**
* Checks to ensure that the token owner has approved the escrow contract
*/
function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.isApprovedForAll(_seller, this) ||
tokenContract.getApproved(_tokenId) == address(this));
}
/**
* Escrows an ERC-721 token from the seller to this contract. Assumes that the escrow contract
* is already approved to make the transfer, otherwise it will fail.
*/
function _escrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(_seller, this, _tokenId);
}
/**
* Transfer an ERC-721 token from escrow to the buyer. This is to be called after a purchase is
* completed.
*/
function _transfer(address _receiver, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(this, _receiver, _tokenId);
}
/**
* Method to check whether this is an escrow contract
*/
function isEscrowContract() public pure returns(bool) {
return true;
}
/**
* Withdraws all the funds to a specified non-zero address
*/
function withdrawFunds(address _withdrawAddress) public onlyOwner {
require(isApprovedWithdrawAddress(_withdrawAddress));
_withdrawAddress.transfer(address(this).balance);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaCore.sol
pragma solidity 0.4.25;
/**
* This is the main driver contract that is used to control and run the service. Funds
* are managed through this function, underlying contracts are also updated through
* this contract.
*
* This class also exposes a set of creation methods that are allowed to be created
* by an approved token creator, on behalf of a particular address. This is meant
* to simply the creation flow for MakersToken users that aren't familiar with
* the blockchain. The ERC721 tokens that are created are still fully compliant,
* although it is possible for a malicious token creator to mint unwanted tokens
* on behalf of a creator. Worst case, the creator can burn those tokens.
*/
contract DigitalMediaCore is DigitalMediaToken {
using SafeMath for uint32;
// List of approved token creators (on behalf of the owner)
mapping (address => bool) public approvedTokenCreators;
// Mapping from owner to operator accounts.
mapping (address => mapping (address => bool)) internal oboOperatorApprovals;
// Mapping of all disabled OBO operators.
mapping (address => bool) public disabledOboOperators;
// OboApproveAll Event
event OboApprovalForAll(
address _owner,
address _operator,
bool _approved);
// Fired when disbaling obo capability.
event OboDisabledForAll(address _operator);
constructor (
string _tokenName,
string _tokenSymbol,
uint256 _tokenIdStartingCounter,
address _dmsAddress,
address _crsAddress)
public DigitalMediaToken(
_tokenName,
_tokenSymbol,
_tokenIdStartingCounter) {
paused = true;
setDigitalMediaStoreAddress(_dmsAddress);
setCreatorRegistryStore(_crsAddress);
}
/**
* Retrieves a Digital Media object.
*/
function getDigitalMedia(uint256 _id)
external
view
returns (
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath) {
DigitalMedia memory digitalMedia = _getDigitalMedia(_id);
require(digitalMedia.creator != address(0), "DigitalMedia not found.");
id = _id;
totalSupply = digitalMedia.totalSupply;
printIndex = digitalMedia.printIndex;
collectionId = digitalMedia.collectionId;
creator = digitalMedia.creator;
metadataPath = digitalMedia.metadataPath;
}
/**
* Retrieves a collection.
*/
function getCollection(uint256 _id)
external
view
returns (
uint256 id,
address creator,
string metadataPath) {
DigitalMediaCollection memory digitalMediaCollection = _getCollection(_id);
require(digitalMediaCollection.creator != address(0), "Collection not found.");
id = _id;
creator = digitalMediaCollection.creator;
metadataPath = digitalMediaCollection.metadataPath;
}
/**
* Retrieves a Digital Media Release (i.e a token)
*/
function getDigitalMediaRelease(uint256 _id)
external
view
returns (
uint256 id,
uint32 printEdition,
uint256 digitalMediaId) {
require(exists(_id));
DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id];
id = _id;
printEdition = digitalMediaRelease.printEdition;
digitalMediaId = digitalMediaRelease.digitalMediaId;
}
/**
* Creates a new collection.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createCollection(string _metadataPath)
external
whenNotPaused {
_createCollection(msg.sender, _metadataPath);
}
/**
* Creates a new digital media object.
*/
function createDigitalMedia(uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
external
whenNotPaused {
_createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
}
/**
* Creates a new digital media object and mints it's first digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleases(
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleasesInNewCollection(
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 collectionId = _createCollection(msg.sender, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new digital media release (token) for a given digital media id.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaReleases(uint256 _digitalMediaId, uint32 _numReleases)
external
whenNotPaused {
_createDigitalMediaReleases(msg.sender, _digitalMediaId, _numReleases);
}
/**
* Deletes a token / digital media release. Doesn't modify the current print index
* and total to be printed. Although dangerous, the owner of a token should always
* be able to burn a token they own.
*
* Only the owner of the token or accounts approved by the owner can burn this token.
*/
function burnToken(uint256 _tokenId) external {
_burnToken(_tokenId, msg.sender);
}
/* Support ERC721 burn method */
function burn(uint256 tokenId) public {
_burnToken(tokenId, msg.sender);
}
/**
* Ends the production run of a digital media. Afterwards no more tokens
* will be allowed to be printed for this digital media. Used when a creator
* makes a mistake and wishes to burn and recreate their digital media.
*
* When a contract is paused we do not allow new tokens to be created,
* so stopping the production of a token doesn't have much purpose.
*/
function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused {
_burnDigitalMedia(_digitalMediaId, msg.sender);
}
/**
* Resets the approval rights for a given tokenId.
*/
function resetApproval(uint256 _tokenId) external {
clearApproval(msg.sender, _tokenId);
}
/**
* Changes the creator for the current sender, in the event we
* need to be able to mint new tokens from an existing digital media
* print production. When changing creator, the old creator will
* no longer be able to mint tokens.
*
* A creator may need to be changed:
* 1. If we want to allow a creator to take control over their token minting (i.e go decentralized)
* 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function
* when the contract is paused.
* @param _creator the creator address
* @param _newCreator the new creator address
*/
function changeCreator(address _creator, address _newCreator) external {
_changeCreator(msg.sender, _creator, _newCreator);
}
/**********************************************************************/
/**Calls that are allowed to be called by approved creator addresses **/
/**********************************************************************/
/**
* Add a new approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function addApprovedTokenCreator(address _creatorAddress) external onlyOwner {
require(disabledOboOperators[_creatorAddress] != true, "Address disabled.");
approvedTokenCreators[_creatorAddress] = true;
}
/**
* Removes an approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function removeApprovedTokenCreator(address _creatorAddress) external onlyOwner {
delete approvedTokenCreators[_creatorAddress];
}
/**
* @dev Modifier to make the approved creation calls only callable by approved token creators
*/
modifier isApprovedCreator() {
require(
(approvedTokenCreators[msg.sender] == true &&
disabledOboOperators[msg.sender] != true),
"Unapproved OBO address.");
_;
}
/**
* Only the owner address can set a special obo approval list.
* When issuing OBO management accounts, we should give approvals through
* this method only so that we can very easily reset it's approval in
* the event of a disaster scenario.
*
* Only the owner themselves is allowed to give OboApproveAll access.
*/
function setOboApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender, "Approval address is same as approver.");
require(approvedTokenCreators[_to], "Unrecognized OBO address.");
require(disabledOboOperators[_to] != true, "Approval address is disabled.");
oboOperatorApprovals[msg.sender][_to] = _approved;
emit OboApprovalForAll(msg.sender, _to, _approved);
}
/**
* Only called in a disaster scenario if the account has been compromised.
* There's no turning back from this and the oboAddress will no longer be
* able to be given approval rights or perform obo functions.
*
* Only the owner of this contract is allowed to disable an Obo address.
*
*/
function disableOboAddress(address _oboAddress) public onlyOwner {
require(approvedTokenCreators[_oboAddress], "Unrecognized OBO address.");
disabledOboOperators[_oboAddress] = true;
delete approvedTokenCreators[_oboAddress];
emit OboDisabledForAll(_oboAddress);
}
/**
* Override the isApprovalForAll to check for a special oboApproval list. Reason for this
* is that we can can easily remove obo operators if they every become compromised.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
if (disabledOboOperators[_operator] == true) {
return false;
} else if (isOperatorApprovedForCustodialAccount(_operator, _owner) == true) {
return true;
} else if (oboOperatorApprovals[_owner][_operator]) {
return true;
} else {
return super.isApprovedForAll(_owner, _operator);
}
}
/**
* Creates a new digital media object and mints it's digital media release tokens.
* Called on behalf of the _owner. Pass count to mint `n` number of tokens.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleases(
address _owner,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleasesInNewCollection(
address _owner,
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 collectionId = _createCollection(_owner, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates multiple digital media releases (tokens) for a given digital media id.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaReleases(
address _owner,
uint256 _digitalMediaId,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
_createDigitalMediaReleases(_owner, _digitalMediaId, _numReleases);
}
}
|
Checks whether a given creator address matches the single creator address. Will always return true if a single creator address was never set./
|
function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) {
require(_creatorAddress != address(0), "0x0 creator addresses are not allowed.");
return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress;
}
| 890,279 |
./partial_match/4/0x41cEF5E8cE8906FDF99Aebd04eA5D2EEcfB140Cf/sources/contracts/PEther.sol
|
The sender adds to reserves. msg.value The amount of Ether to add as reserves/
|
function _addReserves() external payable {
uint err = _addReservesInternal(msg.value);
requireNoError(err, "_addReserves failed");
}
| 8,590,499 |
// File: contracts/erc20/IERC20.sol
pragma solidity >=0.4.21 <0.6.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);
}
// File: contracts/utils/Ownable.sol
pragma solidity >=0.4.21 <0.6.0;
contract Ownable {
address private _contract_owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = msg.sender;
_contract_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _contract_owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_contract_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @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(_contract_owner, newOwner);
_contract_owner = newOwner;
}
}
// File: contracts/core/IPool.sol
pragma solidity >=0.4.21 <0.6.0;
contract ICurvePool{
function deposit(uint256 _amount) public;
function withdraw(uint256 _amount) public;
function get_virtual_price() public view returns(uint256);
function get_lp_token_balance() public view returns(uint256);
function get_lp_token_addr() public view returns(address);
string public name;
}
// File: contracts/utils/TokenClaimer.sol
pragma solidity >=0.4.21 <0.6.0;
contract TokenClaimer{
event ClaimedTokens(address indexed _token, address indexed _to, uint _amount);
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function _claimStdTokens(address _token, address payable to) internal {
if (_token == address(0x0)) {
to.transfer(address(this).balance);
return;
}
IERC20 token = IERC20(_token);
uint balance = token.balanceOf(address(this));
(bool status,) = _token.call(abi.encodeWithSignature("transfer(address,uint256)", to, balance));
require(status, "call failed");
emit ClaimedTokens(_token, to, balance);
}
}
// File: contracts/utils/SafeMath.sol
pragma solidity >=0.4.21 <0.6.0;
library SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a, "add");
}
function safeSubR(uint a, uint b, string memory s) public pure returns (uint c) {
require(b <= a, s);
c = a - b;
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a, "sub");
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b, "mul");
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0, "div");
c = a / b;
}
function safeDivR(uint a, uint b, string memory s) public pure returns (uint c) {
require(b > 0, s);
c = a / b;
}
}
// File: contracts/utils/Address.sol
pragma solidity >=0.4.21 <0.6.0;
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);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
// File: contracts/erc20/SafeERC20.sol
pragma solidity >=0.4.21 <0.6.0;
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 {
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).safeAdd(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).safeSub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
// File: contracts/core/pool/IPoolBase.sol
pragma solidity >=0.4.21 <0.6.0;
contract PriceInterfaceERC20{
function get_virtual_price() public view returns(uint256);
}
contract IUSDCPoolBase is ICurvePool, Ownable{
using SafeERC20 for IERC20;
address public usdc;
address public controller;
address public vault;
address public lp_token_addr;
uint256 public lp_balance;
uint256 public deposit_usdc_amount;
uint256 public withdraw_usdc_amount;
modifier onlyController(){
require((controller == msg.sender)||(vault == msg.sender), "only controller or vault can call this");
_;
}
constructor() public{
usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
}
function deposit_usdc(uint256 _amount) internal;
//@_amount: USDC amount
function deposit(uint256 _amount) public onlyController{
deposit_usdc_amount = deposit_usdc_amount + _amount;
deposit_usdc(_amount);
uint256 cur = IERC20(lp_token_addr).balanceOf(address(this));
lp_balance = lp_balance + cur;
IERC20(lp_token_addr).safeTransfer(msg.sender, cur);
}
function withdraw_from_curve(uint256 _amount) internal;
//@_amount: lp token amount
function withdraw(uint256 _amount) public onlyController{
withdraw_from_curve(_amount);
lp_balance = lp_balance - _amount;
IERC20(usdc).safeTransfer(msg.sender, IERC20(usdc).balanceOf(address(this)));
}
function setController(address _controller, address _vault) public onlyOwner{
controller = _controller;
vault = _vault;
}
function get_lp_token_balance() public view returns(uint256){
return lp_balance;
}
function get_lp_token_addr() public view returns(address){
return lp_token_addr;
}
function callWithData(address payable to, bytes memory data)public payable onlyOwner{
(bool status, ) = to.call.value(msg.value)(data);
require(status, "call failed");
}
}
// File: contracts/core/pool/GusdPool.sol
pragma solidity >=0.4.21 <0.6.0;
contract CurveInterfaceGusd{
function add_liquidity(uint256[4] memory uamounts, uint256 min_mint_amount) public returns(uint256);
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_mint_amount) public returns(uint256);
address public pool;
}
contract GUSDPool is IUSDCPoolBase{
using SafeERC20 for IERC20;
CurveInterfaceGusd public pool_deposit;
constructor() public{
name = "GUSD";
lp_token_addr = address(0xD2967f45c4f384DEEa880F807Be904762a3DeA07);
pool_deposit = CurveInterfaceGusd(0x64448B78561690B70E17CBE8029a3e5c1bB7136e);
}
//@_amount: USDC amount
function deposit_usdc(uint256 _amount) internal {
IERC20(usdc).approve(address(pool_deposit), 0);
IERC20(usdc).approve(address(pool_deposit), _amount);
uint256[4] memory uamounts = [uint256(0), 0, _amount, 0];
pool_deposit.add_liquidity(uamounts, 0);
}
function withdraw_from_curve(uint256 _amount) internal{
require(_amount <= get_lp_token_balance(), "withdraw_from_curve: too large amount");
IERC20(lp_token_addr).approve(address(pool_deposit), _amount);
pool_deposit.remove_liquidity_one_coin(_amount, 2, 0);
}
function get_virtual_price() public view returns(uint256){
return PriceInterfaceERC20(pool_deposit.pool()).get_virtual_price();
}
}
|
@_amount: lp token amount
|
function withdraw_from_curve(uint256 _amount) internal;
function withdraw(uint256 _amount) public onlyController{
withdraw_from_curve(_amount);
lp_balance = lp_balance - _amount;
IERC20(usdc).safeTransfer(msg.sender, IERC20(usdc).balanceOf(address(this)));
}
| 16,933 |
./partial_match/1/0x420D08Dad4fcd7896500d5E183D8BA934c919220/sources/EaselyFixedCollection.sol
|
See {_getAuctionId}/
|
function getAuctionId(uint256 tokenId) external view returns (uint256) {
return _getAuctionId(tokenId);
}
| 2,825,375 |
./full_match/1/0x57556D10E6e9De56d72B9b322D433B9ed06741D0/sources/router.sol
|
ADD LIQUIDITY create the pair if it doesn't exist yet
|
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'Vulcan: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
require(amountAOptimal <= amountADesired, 'Vulcan: A_AMOUNT_EXCEEDS');
require(amountAOptimal >= amountAMin, 'Vulcan: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
| 8,373,744 |
// 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 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 _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);
}
/**
* @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);
}
/**
* @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);
}
}
}
}
/**
* @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 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 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);
}
}
interface IGenArt {
function getTokensByOwner(address owner)
external
view
returns (uint256[] memory);
function ownerOf(uint256 tokenId) external view returns (address);
function balanceOf(address owner) external view returns (uint256);
function isGoldToken(uint256 _tokenId) external view returns (bool);
}
/**
* @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 GenArtTokenAirdropPass is
Context,
Ownable,
ERC165,
IERC1155,
IERC1155MetadataURI
{
using Address for address;
using Strings for uint256;
// 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;
mapping(uint256 => uint256) private _totalSupply;
uint256[3] tokenIds = [1, 2, 3];
uint256[3] tokenId_prices = [0.5 ether, 2.25 ether, 10 ether];
uint256[3] tokenId_cap = [1875, 500, 25];
bool private _paused = false;
address genArtMembershipAddress;
uint256 endBlock;
/**
* @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);
/**
* @dev See {_setURI}.
*/
constructor(
address genArtMembershipAddress_,
uint256 endBlock_,
string memory uri_
) {
genArtMembershipAddress = genArtMembershipAddress_;
endBlock = endBlock_;
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
function uri(uint256 _tokenId)
external
view
virtual
override
returns (string memory)
{
return string(abi.encodePacked(_uri, _tokenId.toString()));
}
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates weither any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return GenArtTokenAirdropPass.totalSupply(id) > 0;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
require(
account != address(0),
"GenArtTokenAirdropPass: 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
virtual
override
returns (uint256[] memory)
{
require(
accounts.length == ids.length,
"GenArtTokenAirdropPass: accounts and ids length mismatch"
);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function setPaused(bool _pause) public onlyOwner {
_paused = _pause;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
function setUri(string memory newUri) public onlyOwner {
_setURI(newUri);
}
function withdraw(uint256 value) public onlyOwner {
address _owner = owner();
payable(_owner).transfer(value);
}
/**
* @dev See {ERC1155-_mint}.
*/
function mint(
uint256 membershipId,
address account,
uint256 id,
uint256 amount
) public payable {
require(
block.number < endBlock,
"GenArtTokenAirdropPass: mint pass sale ended"
);
require(
id == 1 || id == 2 || id == 3,
"GenArtTokenAirdropPass: invalid token id"
);
uint256 index = id - 1;
require(
_totalSupply[id] + amount <= tokenId_cap[index],
"GenArtTokenAirdropPass: requested amount too high"
);
require(
IGenArt(genArtMembershipAddress).ownerOf(membershipId) ==
msg.sender,
"GenArtTokenAirdropPass: sender is not owner of membership"
);
uint256 ethValue;
unchecked {
ethValue = tokenId_prices[index] * amount;
}
require(
ethValue <= msg.value,
"GenArtTokenAirdropPass: wrong amount sent"
);
_mint(account, id, amount, "");
_totalSupply[id] += amount;
}
/**
* @dev See {ERC1155-_burn}.
*/
function burn(
address account,
uint256 id,
uint256 amount
) public {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"GenArtTokenAirdropPass: caller is not owner nor approved"
);
_burn(account, id, amount);
_totalSupply[id] -= amount;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(
_msgSender() != operator,
"GenArtTokenAirdropPass: 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
virtual
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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"GenArtTokenAirdropPass: caller is not owner nor approved"
);
_safeTransferFrom(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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"GenArtTokenAirdropPass: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(
to != address(0),
"GenArtTokenAirdropPass: transfer to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"GenArtTokenAirdropPass: insufficient balance for transfer"
);
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(
ids.length == amounts.length,
"GenArtTokenAirdropPass: ids and amounts length mismatch"
);
require(
to != address(0),
"GenArtTokenAirdropPass: transfer to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"GenArtTokenAirdropPass: insufficient balance for transfer"
);
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += 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 `account` 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),
"GenArtTokenAirdropPass: mint to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(
operator,
address(0),
account,
id,
amount,
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),
"GenArtTokenAirdropPass: burn from the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
uint256 accountBalance = _balances[id][account];
require(
accountBalance >= amount,
"GenArtTokenAirdropPass: burn amount exceeds balance"
);
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @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() internal virtual {
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
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.onERC1155Received.selector) {
revert(
"GenArtTokenAirdropPass: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"GenArtTokenAirdropPass: 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.onERC1155BatchReceived.selector
) {
revert(
"GenArtTokenAirdropPass: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"GenArtTokenAirdropPass: 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;
}
}
|
See {IERC1155-balanceOf}. Requirements: - `account` cannot be the zero address./
|
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
require(
account != address(0),
"GenArtTokenAirdropPass: balance query for the zero address"
);
return _balances[id][account];
}
| 11,994,829 |
./full_match/5/0x5cC5B757DC347dDE73d28bB544fA8e3d5228B2d1/sources/src/utils/MinterUtilities.sol
|
Retrieves the quantity of items remaining that can be minted by the specified recipient. passportHolderMinter The address of the passport holder minter contract. friendsAndFamilyMinter The address of the friends and family minter contract. target The address of the ICre8ors contract. recipient The recipient address for which the quantity is to be calculated. return The quantity of items that can be minted by the specified recipient.
|
function quantityLeft(
address passportHolderMinter,
address friendsAndFamilyMinter,
address target,
address recipient
) external view returns (uint256) {
ICre8ors cre8ors = ICre8ors(target);
ICollectionHolderMint passportMinter = ICollectionHolderMint(
passportHolderMinter
);
FriendsAndFamilyMinter friendsAndFamily = FriendsAndFamilyMinter(
friendsAndFamilyMinter
);
uint256 totalMints = cre8ors.mintedPerAddress(recipient).totalMints;
uint256 totalClaimed = passportMinter.totalClaimed(recipient) +
friendsAndFamily.totalClaimed(recipient);
uint256 maxQuantity = maxAllowedQuantity(totalClaimed);
uint256 quantityRemaining = maxQuantity - totalMints;
if (quantityRemaining < 0) {
return 0;
}
return quantityRemaining;
}
| 7,052,833 |
//Address: 0x5ba12fa4941988e0ce19e0bbb11907ced19d3f0b
//Contract name: Deployer
//Balance: 0 Ether
//Verification Date: 1/20/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.17;
//Slightly modified SafeMath library - includes a min function
library SafeMath {
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); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint a, uint b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
//ERC20 function interface
interface ERC20_Interface {
function totalSupply() public constant returns (uint total_supply);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint _amount) public returns (bool success);
function approve(address _spender, uint _amount) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint amount);
}
//Swap factory functions - descriptions can be found in Factory.sol
interface Factory_Interface {
function createToken(uint _supply, address _party, bool _long, uint _start_date) public returns (address created, uint token_ratio);
function payToken(address _party, address _token_add) public;
function deployContract(uint _start_date) public payable returns (address created);
function getBase() public view returns(address _base1, address base2);
function getVariables() public view returns (address oracle_addr, uint swap_duration, uint swap_multiplier, address token_a_addr, address token_b_addr);
}
//DRCT_Token functions - descriptions can be found in DRCT_Token.sol
interface DRCT_Token_Interface {
function addressCount(address _swap) public constant returns (uint count);
function getHolderByIndex(uint _ind, address _swap) public constant returns (address holder);
function getBalanceByIndex(uint _ind, address _swap) public constant returns (uint bal);
function getIndexByAddress(address _owner, address _swap) public constant returns (uint index);
function createToken(uint _supply, address _owner, address _swap) public;
function pay(address _party, address _swap) public;
function partyCount(address _swap) public constant returns(uint count);
}
//Swap Oracle functions - descriptions can be found in Oracle.sol
interface Oracle_Interface{
function RetrieveData(uint _date) public view returns (uint data);
}
//This contract is the specific DRCT base contract that holds the funds of the contract and redistributes them based upon the change in the underlying values
contract TokenToTokenSwap {
using SafeMath for uint256;
/*Enums*/
//Describes various states of the Swap
enum SwapState {
created,
open,
started,
tokenized,
ready,
ended
}
/*Variables*/
//Address of the person who created this contract through the Factory
address creator;
//The Oracle address (check for list at www.github.com/DecentralizedDerivatives/Oracles)
address oracle_address;
Oracle_Interface oracle;
//Address of the Factory that created this contract
address public factory_address;
Factory_Interface factory;
//Addresses of parties going short and long the rate
address public long_party;
address public short_party;
//Enum state of the swap
SwapState public current_state;
//Start and end dates of the swaps - format is the same as block.timestamp
uint start_date;
uint end_date;
//This is the amount that the change will be calculated on. 10% change in rate on 100 Ether notional is a 10 Ether change
uint multiplier;
//This is the calculated share for the long and short side of the swap (200,000 is a fully capped move)
uint share_long;
uint share_short;
// pay_to_x refers to the amount of the base token (a or b) to pay to the long or short side based upon the share_long and share_short
uint pay_to_short_a;
uint pay_to_long_a;
uint pay_to_long_b;
uint pay_to_short_b;
//Address of created long and short DRCT tokens
address long_token_address;
address short_token_address;
//Number of DRCT Tokens distributed to both parties
uint num_DRCT_longtokens;
uint num_DRCT_shorttokens;
//Addresses of ERC20 tokens used to enter the swap
address token_a_address;
address token_b_address;
//Tokens A and B used for the notional
ERC20_Interface token_a;
ERC20_Interface token_b;
//The notional that the payment is calculated on from the change in the reference rate
uint public token_a_amount;
uint public token_b_amount;
uint public premium;
//Addresses of the two parties taking part in the swap
address token_a_party;
address token_b_party;
//Duration of the swap,pulled from the Factory contract
uint duration;
//Date by which the contract must be funded
uint enterDate;
DRCT_Token_Interface token;
address userContract;
/*Events*/
//Emitted when a Swap is created
event SwapCreation(address _token_a, address _token_b, uint _start_date, uint _end_date, address _creating_party);
//Emitted when the swap has been paid out
event PaidOut(address _long_token, address _short_token);
/*Modifiers*/
//Will proceed only if the contract is in the expected state
modifier onlyState(SwapState expected_state) {
require(expected_state == current_state);
_;
}
/*Functions*/
/*
* Constructor - Run by the factory at contract creation
*
* @param "_factory_address": Address of the factory that created this contract
* @param "_creator": Address of the person who created the contract
* @param "_userContract": Address of the _userContract that is authorized to interact with this contract
*/
function TokenToTokenSwap (address _factory_address, address _creator, address _userContract, uint _start_date) public {
current_state = SwapState.created;
creator =_creator;
factory_address = _factory_address;
userContract = _userContract;
start_date = _start_date;
}
//A getter function for retriving standardized variables from the factory contract
function showPrivateVars() public view returns (address _userContract, uint num_DRCT_long, uint numb_DRCT_short, uint swap_share_long, uint swap_share_short, address long_token_addr, address short_token_addr, address oracle_addr, address token_a_addr, address token_b_addr, uint swap_multiplier, uint swap_duration, uint swap_start_date, uint swap_end_date){
return (userContract, num_DRCT_longtokens, num_DRCT_shorttokens,share_long,share_short,long_token_address,short_token_address, oracle_address, token_a_address, token_b_address, multiplier, duration, start_date, end_date);
}
/*
* Allows the sender to create the terms for the swap
* @param "_amount_a": Amount of Token A that should be deposited for the notional
* @param "_amount_b": Amount of Token B that should be deposited for the notional
* @param "_sender_is_long": Denotes whether the sender is set as the short or long party
* @param "_senderAdd": States the owner of this side of the contract (does not have to be msg.sender)
*/
function CreateSwap(
uint _amount_a,
uint _amount_b,
bool _sender_is_long,
address _senderAdd
) payable public onlyState(SwapState.created) {
require(
msg.sender == creator || (msg.sender == userContract && _senderAdd == creator)
);
factory = Factory_Interface(factory_address);
setVars();
end_date = start_date.add(duration.mul(86400));
token_a_amount = _amount_a;
token_b_amount = _amount_b;
premium = this.balance;
token_a = ERC20_Interface(token_a_address);
token_a_party = _senderAdd;
if (_sender_is_long)
long_party = _senderAdd;
else
short_party = _senderAdd;
current_state = SwapState.open;
}
function setVars() internal{
(oracle_address,duration,multiplier,token_a_address,token_b_address) = factory.getVariables();
}
/*
* This function is for those entering the swap. The details of the swap are re-entered and checked
* to ensure the entering party is entering the correct swap. Note that the tokens you are entering with
* do not need to be entered as a variable, but you should ensure that the contract is funded.
*
* @param: all parameters have the same functions as those in the CreateSwap function
*/
function EnterSwap(
uint _amount_a,
uint _amount_b,
bool _sender_is_long,
address _senderAdd
) public onlyState(SwapState.open) {
//Require that all of the information of the swap was entered correctly by the entering party. Prevents partyA from exiting and changing details
require(
token_a_amount == _amount_a &&
token_b_amount == _amount_b &&
token_a_party != _senderAdd
);
token_b = ERC20_Interface(token_b_address);
token_b_party = _senderAdd;
//Set the entering party as the short or long party
if (_sender_is_long) {
require(long_party == 0);
long_party = _senderAdd;
} else {
require(short_party == 0);
short_party = _senderAdd;
}
SwapCreation(token_a_address, token_b_address, start_date, end_date, token_b_party);
enterDate = now;
current_state = SwapState.started;
}
/*
* This function creates the DRCT tokens for the short and long parties, and ensures the short and long parties
* have funded the contract with the correct amount of the ERC20 tokens A and B
*
*/
function createTokens() public onlyState(SwapState.started){
//Ensure the contract has been funded by tokens a and b within 1 day
require(
now < (enterDate + 86400) &&
token_a.balanceOf(address(this)) >= token_a_amount &&
token_b.balanceOf(address(this)) >= token_b_amount
);
uint tokenratio = 1;
(long_token_address,tokenratio) = factory.createToken(token_a_amount, long_party,true,start_date);
num_DRCT_longtokens = token_a_amount.div(tokenratio);
(short_token_address,tokenratio) = factory.createToken(token_b_amount, short_party,false,start_date);
num_DRCT_shorttokens = token_b_amount.div(tokenratio);
current_state = SwapState.tokenized;
if (premium > 0){
if (creator == long_party){
short_party.transfer(premium);
}
else {
long_party.transfer(premium);
}
}
}
/*
* This function calculates the payout of the swap. It can be called after the Swap has been tokenized.
* The value of the underlying cannot reach zero, but rather can only get within 0.001 * the precision
* of the Oracle.
*/
function Calculate() internal {
//require(now >= end_date + 86400);
//Comment out above for testing purposes
oracle = Oracle_Interface(oracle_address);
uint start_value = oracle.RetrieveData(start_date);
uint end_value = oracle.RetrieveData(end_date);
uint ratio;
if (start_value > 0 && end_value > 0)
ratio = (end_value).mul(100000).div(start_value);
else if (end_value > 0)
ratio = 10e10;
else if (start_value > 0)
ratio = 0;
else
ratio = 100000;
if (ratio == 100000) {
share_long = share_short = ratio;
} else if (ratio > 100000) {
share_long = ((ratio).sub(100000)).mul(multiplier).add(100000);
if (share_long >= 200000)
share_short = 0;
else
share_short = 200000-share_long;
} else {
share_short = SafeMath.sub(100000,ratio).mul(multiplier).add(100000);
if (share_short >= 200000)
share_long = 0;
else
share_long = 200000- share_short;
}
//Calculate the payouts to long and short parties based on the short and long shares
calculatePayout();
current_state = SwapState.ready;
}
/*
* Calculates the amount paid to the short and long parties per token
*/
function calculatePayout() internal {
uint ratio;
token_a_amount = token_a_amount.mul(995).div(1000);
token_b_amount = token_b_amount.mul(995).div(1000);
//If ratio is flat just swap tokens, otherwise pay the winner the entire other token and only pay the other side a portion of the opposite token
if (share_long == 100000) {
pay_to_short_a = (token_a_amount).div(num_DRCT_longtokens);
pay_to_long_b = (token_b_amount).div(num_DRCT_shorttokens);
pay_to_short_b = 0;
pay_to_long_a = 0;
} else if (share_long > 100000) {
ratio = SafeMath.min(100000, (share_long).sub(100000));
pay_to_long_b = (token_b_amount).div(num_DRCT_shorttokens);
pay_to_short_a = (SafeMath.sub(100000,ratio)).mul(token_a_amount).div(num_DRCT_longtokens).div(100000);
pay_to_long_a = ratio.mul(token_a_amount).div(num_DRCT_longtokens).div(100000);
pay_to_short_b = 0;
} else {
ratio = SafeMath.min(100000, (share_short).sub(100000));
pay_to_short_a = (token_a_amount).div(num_DRCT_longtokens);
pay_to_long_b = (SafeMath.sub(100000,ratio)).mul(token_b_amount).div(num_DRCT_shorttokens).div(100000);
pay_to_short_b = ratio.mul(token_b_amount).div(num_DRCT_shorttokens).div(100000);
pay_to_long_a = 0;
}
}
/*
* This function can be called after the swap is tokenized or after the Calculate function is called.
* If the Calculate function has not yet been called, this function will call it.
* The function then pays every token holder of both the long and short DRCT tokens
*/
function forcePay(uint _begin, uint _end) public returns (bool) {
//Calls the Calculate function first to calculate short and long shares
if(current_state == SwapState.tokenized /*&& now > end_date + 86400*/){
Calculate();
}
//The state at this point should always be SwapState.ready
require(current_state == SwapState.ready);
//Loop through the owners of long and short DRCT tokens and pay them
token = DRCT_Token_Interface(long_token_address);
uint count = token.addressCount(address(this));
uint loop_count = count < _end ? count : _end;
//Indexing begins at 1 for DRCT_Token balances
for(uint i = loop_count-1; i >= _begin ; i--) {
address long_owner = token.getHolderByIndex(i, address(this));
uint to_pay_long = token.getBalanceByIndex(i, address(this));
paySwap(long_owner, to_pay_long, true);
}
token = DRCT_Token_Interface(short_token_address);
count = token.addressCount(address(this));
loop_count = count < _end ? count : _end;
for(uint j = loop_count-1; j >= _begin ; j--) {
address short_owner = token.getHolderByIndex(j, address(this));
uint to_pay_short = token.getBalanceByIndex(j, address(this));
paySwap(short_owner, to_pay_short, false);
}
if (loop_count == count){
token_a.transfer(factory_address, token_a.balanceOf(address(this)));
token_b.transfer(factory_address, token_b.balanceOf(address(this)));
PaidOut(long_token_address, short_token_address);
current_state = SwapState.ended;
}
return true;
}
/*
* This function pays the receiver an amount determined by the Calculate function
*
* @param "_receiver": The recipient of the payout
* @param "_amount": The amount of token the recipient holds
* @param "_is_long": Whether or not the reciever holds a long or short token
*/
function paySwap(address _receiver, uint _amount, bool _is_long) internal {
if (_is_long) {
if (pay_to_long_a > 0)
token_a.transfer(_receiver, _amount.mul(pay_to_long_a));
if (pay_to_long_b > 0){
token_b.transfer(_receiver, _amount.mul(pay_to_long_b));
}
factory.payToken(_receiver,long_token_address);
} else {
if (pay_to_short_a > 0)
token_a.transfer(_receiver, _amount.mul(pay_to_short_a));
if (pay_to_short_b > 0){
token_b.transfer(_receiver, _amount.mul(pay_to_short_b));
}
factory.payToken(_receiver,short_token_address);
}
}
/*
* This function allows both parties to exit. If only the creator has entered the swap, then the swap can be cancelled and the details modified
* Once two parties enter the swap, the contract is null after cancelled. Once tokenized however, the contract cannot be ended.
*/
function Exit() public {
if (current_state == SwapState.open && msg.sender == token_a_party) {
token_a.transfer(token_a_party, token_a_amount);
if (premium>0){
msg.sender.transfer(premium);
}
delete token_a_amount;
delete token_b_amount;
delete premium;
current_state = SwapState.created;
} else if (current_state == SwapState.started && (msg.sender == token_a_party || msg.sender == token_b_party)) {
if (msg.sender == token_a_party || msg.sender == token_b_party) {
token_b.transfer(token_b_party, token_b.balanceOf(address(this)));
token_a.transfer(token_a_party, token_a.balanceOf(address(this)));
current_state = SwapState.ended;
if (premium > 0) { creator.transfer(premium);}
}
}
}
}
//Swap Deployer Contract-- purpose is to save gas for deployment of Factory contract
contract Deployer {
address owner;
address factory;
function Deployer(address _factory) public {
factory = _factory;
owner = msg.sender;
}
function newContract(address _party, address user_contract, uint _start_date) public returns (address created) {
require(msg.sender == factory);
address new_contract = new TokenToTokenSwap(factory, _party, user_contract, _start_date);
return new_contract;
}
function setVars(address _factory, address _owner) public {
require (msg.sender == owner);
factory = _factory;
owner = _owner;
}
}
|
Swap factory functions - descriptions can be found in Factory.sol
|
interface Factory_Interface {
function createToken(uint _supply, address _party, bool _long, uint _start_date) public returns (address created, uint token_ratio);
function payToken(address _party, address _token_add) public;
function deployContract(uint _start_date) public payable returns (address created);
function getBase() public view returns(address _base1, address base2);
function getVariables() public view returns (address oracle_addr, uint swap_duration, uint swap_multiplier, address token_a_addr, address token_b_addr);
}
| 7,294,756 |
./full_match/57/0xaA8Bb6F6209Ebef6D160B35134fb0C6775c8D357/sources/contracts/universal/op-nft/Optimist.sol
|
Disabled for the Optimist NFT (Soul Bound Token)./
|
function setApprovalForAll(address, bool) public virtual override {
revert("Optimist: soul bound token");
}
| 13,222,012 |
/**
*Submitted for verification at Etherscan.io on 2022-02-26
*/
// SPDX-License-Identifier: OSL-3.0
pragma solidity 0.8.11;
/*
__ __ __ __ ______ ______ __ __ __ ______
/\ \/\ \ /\ \/ / /\ == \ /\ __ \ /\ \ /\ "-.\ \ /\ ___\
\ \ \_\ \ \ \ _"-. \ \ __< \ \ __ \ \ \ \ \ \ \-. \ \ \ __\
\ \_____\ \ \_\ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\ \ \_\\"\_\ \ \_____\
\/_____/ \/_/\/_/ \/_/ /_/ \/_/\/_/ \/_/ \/_/ \/_/ \/_____/
|########################################################################|
|########################################################################|
|########################################################################|
|########################################################################|
|########################################################################|
|::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::|
|::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::|
|::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::|
|::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::|
|::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::|
Pussy Riot, Trippy Labs, PleasrDAO, CXIP
*/
contract UkraineDAO_NFT {
address private _owner;
string private _name = "UKRAINE";
string private _symbol = unicode"🇺🇦";
string private _domain = "UkraineDAO.love";
address private _tokenOwner;
address private _tokenApproval;
string private _flag = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"800\">"
"<rect width=\"1200\" height=\"800\" fill=\"#005BBB\"/>"
"<rect width=\"1200\" height=\"400\" y=\"400\" fill=\"#FFD500\"/>"
"</svg>";
string private _flagSafe = "<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"1200\\\" height=\\\"800\\\">"
"<rect width=\\\"1200\\\" height=\\\"800\\\" fill=\\\"#005BBB\\\"/>"
"<rect width=\\\"1200\\\" height=\\\"400\\\" y=\\\"400\\\" fill=\\\"#FFD500\\\"/>"
"</svg>";
mapping(address => mapping(address => bool)) private _operatorApprovals;
event Approval (address indexed wallet, address indexed operator, uint256 indexed tokenId);
event ApprovalForAll (address indexed wallet, address indexed operator, bool approved);
event Transfer (address indexed from, address indexed to, uint256 indexed tokenId);
event OwnershipTransferred (address indexed previousOwner, address indexed newOwner);
/*
* @dev Only one NFT is ever created.
*/
constructor(address contractOwner) {
_owner = contractOwner;
emit OwnershipTransferred(address(0), _owner);
_mint(_owner, 1);
}
/*
* @dev Left empty to not block any smart contract transfers from running out of gas.
*/
receive() external payable {}
/*
* @dev Left empty to not allow any other functions to be called.
*/
fallback() external {}
/*
* @dev Allows to limit certain function calls to only the contract owner.
*/
modifier onlyOwner() {
require(isOwner(), "you are not the owner");
_;
}
/*
* @dev Can transfer smart contract ownership to another wallet/smart contract.
*/
function changeOwner (address newOwner) public onlyOwner {
require(newOwner != address(0), "empty address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/*
* @dev Provisional functionality to allow the removal of any spammy NFTs.
*/
function withdrawERC1155 (address token, uint256 tokenId, uint256 amount) public onlyOwner {
ERCTransferable(token).safeTransferFrom(address(this), _owner, tokenId, amount, "");
}
/*
* @dev Provisional functionality to allow the withdrawal of accidentally received ERC20 tokens.
*/
function withdrawERC20 (address token, uint256 amount) public onlyOwner {
ERCTransferable(token).transfer(_owner, amount);
}
/*
* @dev Provisional functionality to allow the removal of any spammy NFTs.
*/
function withdrawERC721 (address token, uint256 tokenId) public onlyOwner {
ERCTransferable(token).safeTransferFrom(address(this), _owner, tokenId);
}
/*
* @dev Provisional functionality to allow the withdrawal of accidentally received ETH.
*/
function withdrawETH () public onlyOwner {
payable(address(msg.sender)).transfer(address(this).balance);
}
/*
* @dev Approve a third-party wallet/contract to manage the token on behalf of a token owner.
*/
function approve (address operator, uint256 tokenId) public {
require(operator != _tokenOwner, "one cannot approve one self");
require(_isApproved(msg.sender, tokenId), "the sender is not approved");
_tokenApproval = operator;
emit Approval(_tokenOwner, operator, tokenId);
}
/*
* @dev Safely transfer a token to another wallet/contract.
*/
function safeTransferFrom (address from, address to, uint256 tokenId) public payable {
safeTransferFrom(from, to, tokenId, "");
}
/*
* @dev Safely transfer a token to another wallet/contract.
*/
function safeTransferFrom (address from, address to, uint256 tokenId, bytes memory data) public payable {
require(_isApproved(msg.sender, tokenId), "sender is not approved");
_transferFrom(from, to, tokenId);
if (isContract(to) && ERCTransferable(to).supportsInterface(0x150b7a02)) {
require(ERCTransferable(to).onERC721Received(address(this), from, tokenId, data) == 0x150b7a02, "onERC721Received has failed");
}
}
/*
* @dev Approve a third-party wallet/contract to manage all tokens on behalf of a token owner.
*/
function setApprovalForAll (address operator, bool approved) public {
require(operator != msg.sender, "one cannot approve one self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/*
* @dev Transfer a token to anther wallet/contract.
*/
function transfer (address to, uint256 tokenId) public payable {
transferFrom(msg.sender, to, tokenId, "");
}
/*
* @dev Transfer a token to another wallet/contract.
*/
function transferFrom (address from, address to, uint256 tokenId) public payable {
transferFrom(from, to, tokenId, "");
}
/*
* @dev Transfer a token to another wallet/contract.
*/
function transferFrom (address from, address to, uint256 tokenId, bytes memory) public payable {
require(_isApproved(msg.sender, tokenId), "the sender is not approved");
_transferFrom(from, to, tokenId);
}
/*
* @dev Gets the token balance of a wallet/contract.
*/
function balanceOf (address wallet) public view returns (uint256) {
require(wallet != address(0), "empty address");
return wallet == _tokenOwner ? 1 : 0;
}
/*
* @dev Gets the base64 encoded JSON data stream of contract descriptors.
*/
function contractURI () public view returns (string memory) {
return string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
abi.encodePacked(
"{",
"\"name\":\"", _name, "\",",
unicode"\"description\":\"This is the Ukranian flag 🇺🇦 1/1\",",
"\"external_link\":\"https://", _domain, "/\",",
"\"image\":\"data:image/svg+xml;base64,", Base64.encode(_flag), "\"",
"}"
)
)
)
);
}
/*
* @dev Check if a token exists.
*/
function exists (uint256 tokenId) public pure returns (bool) {
return (tokenId == 1);
}
/*
* @dev Check if an approved wallet/address was added for a particular token.
*/
function getApproved (uint256) public view returns (address) {
return _tokenApproval;
}
/*
* @dev Check if an operator was approved for a particular wallet/contract.
*/
function isApprovedForAll (address wallet, address operator) public view returns (bool) {
return _operatorApprovals[wallet][operator];
}
/*
* @dev Check if current wallet/caller is the owner of the smart contract.
*/
function isOwner () public view returns (bool) {
return (msg.sender == _owner);
}
/*
* @dev Get the name of the collection.
*/
function name () public view returns (string memory) {
return _name;
}
/*
* @dev Get the owner of the smart contract.
*/
function owner () public view returns (address) {
return _owner;
}
/*
* @dev Get the owner of a particular token.
*/
function ownerOf (uint256 tokenId) public view returns (address) {
require(tokenId == 1, "token does not exist");
return _tokenOwner;
}
/*
* @dev Check if the smart contract supports a particular interface.
*/
function supportsInterface (bytes4 interfaceId) public pure returns (bool) {
if (
interfaceId == 0x01ffc9a7 || // ERC165
interfaceId == 0x80ac58cd || // ERC721
interfaceId == 0x780e9d63 || // ERC721Enumerable
interfaceId == 0x5b5e139f || // ERC721Metadata
interfaceId == 0x150b7a02 || // ERC721TokenReceiver
interfaceId == 0xe8a3d485 // contractURI()
) {
return true;
} else {
return false;
}
}
/*
* @dev Get the collection's symbol.
*/
function symbol () public view returns (string memory) {
return _symbol;
}
/*
* @dev Get token by index.
*/
function tokenByIndex (uint256 index) public pure returns (uint256) {
require(index == 0, "index out of bounds");
return 1;
}
/*
* @dev Get wallet/contract token by index.
*/
function tokenOfOwnerByIndex (address wallet, uint256 index) public view returns (uint256) {
require(wallet == _tokenOwner && index == 0, "index out of bounds");
return 1;
}
/*
* @dev Gets the base64 encoded data stream of token.
*/
function tokenURI (uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "token does not exist");
return string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
abi.encodePacked(
"{",
"\"name\":\"Ukrainian Flag\",",
unicode"\"description\":\"This is the Ukrainian flag 🇺🇦 1/1. Funds raised from this sale will be directed to helping the Ukrainian civilians suffering from the war initiated by Putin. \\\"Come Back Alive,\\\" one of the most effective and transparent Ukrainian charitable and volunteer initiatives can be found at: https://savelife.in.ua\\n\\n",
"This project has been organized by Pussy Riot, Trippy Labs, PleasrDAO, CXIP, and many Ukrainian humanitarian activists working tirelessly on the ground and generously consulting with us to assure we have a safe place to direct our donations that will help those who need it the most.\\n\\n",
unicode"Much support and love to Ukraine 🇺🇦\",",
"\"external_url\":\"https://", _domain, "/\",",
"\"image\":\"data:image/svg+xml;base64,", Base64.encode(_flag), "\",",
"\"image_data\":\"", _flagSafe, "\"",
"}"
)
)
)
);
}
/*
* @dev Get list of all tokens of an owner.
*/
function tokensOfOwner (address wallet) public view returns (uint256[] memory tokens) {
if (wallet == _tokenOwner) {
tokens = new uint256[](1);
tokens[0] = 1;
}
return tokens;
}
/*
* @dev Get the total supply of tokens in the collection.
*/
function totalSupply () public pure returns (uint256) {
return 1;
}
/*
* @dev Signal to sending contract that a token was received.
*/
function onERC721Received (address operator, address, uint256 tokenId, bytes calldata) public returns (bytes4) {
ERCTransferable(operator).safeTransferFrom(address(this), _owner, tokenId);
return 0x150b7a02;
}
function _clearApproval () internal {
delete _tokenApproval;
}
function _mint (address to, uint256 tokenId) internal {
require(to != address(0));
_tokenOwner = to;
emit Transfer(address(0), to, tokenId);
}
function _transferFrom (address from, address to, uint256 tokenId) internal {
require(_tokenOwner == from, "you are not token owner");
require(to != address(0), "you cannot burn this");
_clearApproval();
_tokenOwner = to;
emit Transfer(from, to, tokenId);
}
function _exists (uint256 tokenId) internal pure returns (bool) {
return (tokenId == 1);
}
function _isApproved (address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId));
return (spender == _tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(_tokenOwner, spender));
}
function isContract (address account) internal view returns (bool) {
bytes32 codehash;
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
}
interface ERCTransferable {
// ERC155
function safeTransferFrom (address from, address to, uint256 tokenid, uint256 amount, bytes calldata data) external;
// ERC20
function transfer (address recipient, uint256 amount) external returns (bool);
// ERC721
function safeTransferFrom (address from, address to, uint256 tokenId) external payable;
// ERC721
function onERC721Received (address operator, address from, uint256 tokenId, bytes calldata data) external view returns (bytes4);
// ERC721
function supportsInterface (bytes4 interfaceId) external view returns (bool);
}
library Base64 {
function encode (string memory _str) internal pure returns (string memory) {
bytes memory data = bytes(_str);
return encode(data);
}
function encode (bytes memory data) internal pure returns (string memory) {
string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint256 encodedLen = 4 * ((data.length + 2) / 3);
string memory result = new string(encodedLen + 32);
assembly {
mstore(result, encodedLen)
let tablePtr := add(table, 1)
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
let resultPtr := add(result, 32)
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
}
|
Can transfer smart contract ownership to another wallet/smart contract./
|
function changeOwner (address newOwner) public onlyOwner {
require(newOwner != address(0), "empty address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 6,549,499 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ABDKMath64x64.sol";
/**
* @title SplytStaking
* @dev Enables a user to stake tokens into this smart contract
*/
contract SplytStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private _token; // The token to be used in this smart contract
struct Compound {
uint depositStartBlock; // Block where users are allowed to start deposits
uint depositEndBlock; // Block where deposits are no longer allowed
uint interestStartBlock; // Block that starts yield gaining
uint interestEndBlock; // Block that ends yield gained
uint startTime; // Time to start computing compound yield
uint endTime; // Time to stop computing compound yield
uint apyPerSec; // Interval at which yield compounds, e.g., 31556952 seconds/year, 8600 hours/year
uint apyPerBlock; // Reward per block. We assume 15s per block
}
struct activeStaker {
address addr; // Address of active staker
uint balance; // Balance of the staker
}
Compound private compound; // Struct to hold compound information
uint constant secondsPerYear = 31556952; // Seconds in a year
uint constant blocksPerMonth = 175200; // Blocks per month
uint poolDurationByBlock; // How long to yield interest aka max amount of blocks allowed for reward
uint constant secondPerBlock = 15; // Number of seconds between blocks mined
uint feeDivisor = 10**3; // Withdrawal fee (0.1%)
uint totalPrincipal; // Total amount of token principal deposited into this smart contract
uint numUsersWithDeposits; // Total number of users who have deposited tokens into this smart contract
uint numUniqueUsers; // Total number of unique users who have called stakeTokens() so far
uint secretBonusLimit; // If secretBonusLimit reached, provide bonus to long term holders
uint secretBonusPool; // Pool amount to be distributed
mapping (address => uint256) public _balances; // Balance of tokens by user
mapping (uint256 => address) public addressByIndex; // Address by index
/**
* @dev Emitted when `_amount` tokens are staked by `_userAddress`
*/
event TokenStaked(address _userAddress, uint256 _amount);
/**
* @dev Emitted when `_amount` tokens are withdrawn by `_userAddress`
*/
event TokenWithdrawn(address _userAddress, uint256 _amount);
/**
* @dev Creates the SplytStaking smart contract
* @param token address of the token to be vested
* @param _apyPerSec APY gained per second ratio
* @param _depositStartBlock Block where deposits start
* @param _depositEndBlock Block where deposits end
*/
constructor (
address token,
uint _apyPerSec,
uint _depositStartBlock,
uint _depositEndBlock,
uint _poolDurationByBlock,
uint _secretBonusLimit,
uint _secretBonusPool
) public {
_token = IERC20(token);
// Set how long the pool will yield interest
poolDurationByBlock = _poolDurationByBlock;
// set bonus pool params
secretBonusLimit = _secretBonusLimit;
secretBonusPool = _secretBonusPool;
// Compute start and end blocks for yield compounding
uint interestStartBlock = _depositEndBlock.add(1);
uint interestEndBlock = interestStartBlock.add(poolDurationByBlock);
// Compute start and end times for the same time period
uint blocksUntilInterestStarts = interestStartBlock.sub(block.number);
uint interestStartTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = interestEndBlock.sub(interestStartBlock);
uint interestEndTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
compound = Compound({
depositStartBlock: _depositStartBlock,
depositEndBlock: _depositEndBlock,
interestStartBlock: interestStartBlock,
interestEndBlock: interestEndBlock,
startTime: interestStartTime,
endTime: interestEndTime,
apyPerSec: _apyPerSec,
apyPerBlock: _apyPerSec.mul(secondPerBlock)
});
numUsersWithDeposits = 0;
totalPrincipal = 0;
numUniqueUsers = 0;
_balances[address(this)] = 0;
}
// -----------------------------------------------------------------------
// Modifiers
// -----------------------------------------------------------------------
/**
* @dev Modifier that only lets the function continue if it is within the deposit window (depositStartBlock, depositEndBlock)
*/
modifier depositWindow() {
require (block.number > compound.depositStartBlock && block.number <= compound.depositEndBlock, "DepositWindow: Can be called only during deposit window");
_;
}
/**
* @dev Modifier that only lets the function continue if the current block is before compound.interestStartBlock
*/
modifier hasNotStartedYielding() {
require (block.number < compound.interestStartBlock, "HasNotStartedYielding: Can be called only before interest start block");
_;
}
// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
/**
* @dev Check that the amount of blocks staked does not exceed limit: poolBlockDuration=maxBlock.
* @dev If a user keeps their tokens longer than maxBlock, they only get yield up to maxBlock.
* @param numBlocksPassed Amount of blocks passed
* @param maxBlock Highest amount of blocks allowed to pass (limit)
*/
function _blocksStaked(uint numBlocksPassed, uint maxBlock) public pure returns (uint) {
if(numBlocksPassed >= maxBlock) {
return maxBlock;
} else {
return numBlocksPassed;
}
}
// -----------------------------------------------------------------------
// COMPUTATIONS
// -----------------------------------------------------------------------
/**
* @dev Estimates the power computation
* @param x base
* @param n duration
*/
function pow (int128 x, uint n) public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt (1); while (n > 0) {
if (n % 2 == 1) {
r = ABDKMath64x64.mul (r, x);
n -= 1;
} else {
x = ABDKMath64x64.mul (x, x);
n /= 2;
}
}
}
/**
* @dev Method to compute APY gained. Note: this is only used for comparison, not actually used to compute real gain
* @param principal Principal provided
* @param ratio Amount of APY gained per second
* @param n Duration
*/
function compoundInterestByTime(uint principal, uint ratio, uint n) public pure returns (uint) {
return ABDKMath64x64.mulu (
pow (
ABDKMath64x64.add (ABDKMath64x64.fromUInt (1), ABDKMath64x64.divu (ratio, 10**18)),
n),
principal);
}
/**
* @dev Wrapper method that is bound to the smart contract apyPerSec variable
* @dev Enables durations to be set manually
* @dev Not used to compute real gain
* @param principal Principal provided
* @param duration Duration
* @return the amount gained: principal + yield
*/
function compoundWithPrincipalAndTime(uint principal, uint duration) external view returns (uint) {
return compoundInterestByTime(principal, compound.apyPerSec, duration);
}
/**
* @dev Wrapper method that is bound to the smart contract apyPerSec and computes duration against live blockchain data
* @dev Not used to compute real gain
* @param principal Principal provided
* @return the amount gained: principal + yield
*/
function compoundWithPrincipal(uint principal) public view returns (uint) {
uint duration = block.timestamp - compound.startTime;
return compoundInterestByTime(principal, compound.apyPerSec, duration);
}
/**
* @dev Wrapper method that computes gain using the callers information
* @dev Uses all predefined variables in the smart contract and blockchain state
* @dev Not used to compute real gain
* @return the amount gained: principal + yield
*/
function compoundWithPrincipalByUser() external view returns (uint) {
return compoundWithPrincipal(_balances[msg.sender]);
}
/**
* @dev Raw method that computes gain using blocks instead of time
* @param principal Principal provided
* @param blocksStaked Number of blocks with which to compute gain
* @return the amount gained: principal + yield
*/
function _compoundInterestByBlock(uint principal, uint blocksStaked) public view returns (uint) {
uint reward = SafeMath.div(compound.apyPerBlock.mul(principal).mul(blocksStaked), 10**18);
return reward.add(principal);
}
/**
* @dev Computes yield gained using block raw function
* @dev Makes sure that a user cannot gain more yield than poolBlockDuration as defined in the smart contract
* @param principal Principal
* @return the amount gained: principal + yield
*/
function compoundInterestByBlock(uint principal) public view returns (uint) {
uint numBlocksPassed = block.number.sub(compound.interestStartBlock);
uint blocksStaked = _blocksStaked(numBlocksPassed, poolDurationByBlock);
return _compoundInterestByBlock(principal, blocksStaked);
}
// -----------------------------------------------------------------------
// GETTERS
// -----------------------------------------------------------------------
/**
* @dev Gets block and time information out of the smart contract
* @return _currentBlock Current block on the blockchain
* @return _depositStartBlock Block where deposits are allowed
* @return _depositEndBlock Block where deposits are no longer allowed
* @return _interestStartBlock Block where yield starts growing
* @return _interestEndBlock Block where yield stops growing
* @return _interestStartTime Estimated yield start time (for comparison only)
* @return _interestEndTime Estimated yield end time (for comparison only)
* @return _interestApyPerSec APY per second rate defined in the smart contract
* @return _interestApyPerBlock APY per block defined in the smart contract
*/
function getCompoundInfo() external view returns (
uint _currentBlock,
uint _depositStartBlock,
uint _depositEndBlock,
uint _interestStartBlock,
uint _interestEndBlock,
uint _interestStartTime,
uint _interestEndTime,
uint _interestApyPerSec,
uint _interestApyPerBlock
) {
return (
block.number,
compound.depositStartBlock,
compound.depositEndBlock,
compound.interestStartBlock,
compound.interestEndBlock,
compound.startTime,
compound.endTime,
compound.apyPerSec,
compound.apyPerBlock
);
}
/**
* @dev Gets info about secret pool. :P
* @return _secretBonusLimit Number of wallets who need to stake to unlock the secretBonusPool
* @return _secretBonusPool Total pool that will be divided by all users who stay for the entire duration (see withdrawTokens fn)
* @return _bonusUnlockable Bool is true if number of users who stake is over _secretBonusLimit
* @return _bonusUnlocked Bool controls if the bonus is going to be applied (see withdrawTokens fn)
*/
function getSecretPoolInfo() public view returns (uint _secretBonusLimit, uint _secretBonusPool, bool _bonusUnlockable, bool _bonusUnlocked) {
return (
secretBonusLimit,
secretBonusPool,
numUniqueUsers > secretBonusLimit,
block.number >= compound.interestEndBlock && numUniqueUsers > secretBonusLimit
);
}
/**
* @dev Gets staking data from this smart contract
* @return _totalPrincipal Total amount of tokens deposited as principal
* @return _numUsersWithDeposits Number of users who have staked into this smart contract
*/
function getAdminStakingInfo() public view returns (uint _totalPrincipal, uint _numUsersWithDeposits) {
return (totalPrincipal, numUsersWithDeposits);
}
/**
* @dev Gets user balance data
* @dev If this is called before any yield is gained, we manually display 0 reward
* @param userAddress Address of a given user
* @return _principal Principal that a user has staked
* @return _reward Current estimated reward earned
* @return _balance Total balance (_principal + _reward)
*/
function getUserBalances(address userAddress) external view returns (uint _principal, uint _reward, uint _balance) {
if(block.number <= compound.interestStartBlock) {
return (
_balances[userAddress],
0,
_balances[userAddress]);
} else {
uint totalBalance = compoundInterestByBlock(_balances[userAddress]);
uint reward = totalBalance.sub(_balances[userAddress]);
return (
_balances[userAddress],
reward,
totalBalance
);
}
}
/**
* @dev Get list of active stakers and balances
* @return {addr, balance},...} as an array
*/
// function getActiveStakers() public view returns (activeStaker[] memory) {
// // Array of structs for active stakers
// activeStaker[] memory activeStakers = new activeStaker[](numUsersWithDeposits);
// uint i = 0; // index for activeStakers[]
// uint j = 0; // index for addressByIndex[]
// for (; i < numUsersWithDeposits ; j++) {
// // If balances is zero, consider the address as an inactive staker
// if (_balances[addressByIndex[j]] != 0) {
// activeStakers[i].addr = addressByIndex[j];
// activeStakers[i].balance = _balances[addressByIndex[j]];
// i++;
// }
// }
// return (activeStakers);
// }
/**
* @dev Reads the APY defined in the smart contract as a percentage
* @return _apy APY in percentage form
*/
function apy() external view returns (uint _apy) {
return secondsPerYear * compound.apyPerSec * 100;
}
// -----------------------------------------------------------------------
// SETTERS
// -----------------------------------------------------------------------
/**
* @dev Enables the deposit window to be changed. Only the smart contract owner is allowed to do this
* @dev Because blocks are not always found at the same rate, we may need to change the deposit window so events start on time
* @dev We will only call this so the start time is as accurate as possible
* @dev We have to recompute the yield start block and yield end block times as well
* @param _depositStartBlock New deposit start block
* @param _depositEndBlock New deposit end block
*/
function changeDepositWindow(uint _depositStartBlock, uint _depositEndBlock) external onlyOwner {
compound.depositStartBlock = _depositStartBlock;
compound.depositEndBlock = _depositEndBlock;
compound.interestStartBlock = _depositEndBlock.add(1);
compound.interestEndBlock = compound.interestStartBlock.add(poolDurationByBlock);
uint blocksUntilInterestStarts = compound.interestStartBlock.sub(block.number);
compound.startTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = compound.interestEndBlock.sub(compound.interestStartBlock);
compound.endTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
}
/**
* @dev Change the APY of the contract. Only the smart contract owner is allowed to do this
* @dev The method should only be callable by the owner AND only if the current block is before compound.interestStartBlock
* @param _newApyRate New APY
*/
function changeAPY(uint _newApyRate) external onlyOwner hasNotStartedYielding {
compound.apyPerSec = _newApyRate;
compound.apyPerBlock = _newApyRate.mul(secondPerBlock);
}
/**
* @dev Enables a user to deposit their stake into this smart contract. A user must call approve tokens before calling this method
* @dev This can only be called during the deposit window. Calling this before or after will fail
* @dev We also make sure to track the state of [totalPrincipal, numUsersWithDeposits]
* @param _amount The amount of tokens to stake into this smart contract
*/
function stakeTokens(uint _amount) external depositWindow {
require(_token.allowance(msg.sender, address(this)) >= _amount, "TokenBalance: User has not allowed tokens to be used");
require(_token.balanceOf(msg.sender) >= _amount, "TokenBalance: msg.sender can not stake more than they have");
if(_balances[msg.sender] == 0) {
numUsersWithDeposits++;
numUniqueUsers++;
// addressByIndex[numUniqueUsers++] = msg.sender;
}
_balances[msg.sender] += _amount;
totalPrincipal += _amount;
require(_token.transferFrom(msg.sender, address(this), _amount), "TokenTransfer: failed to transfer tokens from msg.sender here");
emit TokenStaked(msg.sender, _amount);
}
/**
* @dev Lets a user withdraw all their tokens from this smart contract
* @dev A fee is charged on all withdrawals
* @dev We make sure to track the state of [totalPrincipal, numUsersWithDeposits]
*/
function withdrawTokens() external {
require(_balances[msg.sender] > 0, "TokenBalance: no tokens available to be withdrawn");
uint totalBalance = 0;
if(block.number <= compound.depositEndBlock) {
totalBalance = _balances[msg.sender];
} else {
totalBalance = compoundInterestByBlock(_balances[msg.sender]);
}
uint fee = totalBalance.div(feeDivisor);
totalBalance = totalBalance.sub(fee);
if(block.number >= compound.interestEndBlock && numUniqueUsers > secretBonusLimit) {
totalBalance += secretBonusPool.div(numUniqueUsers);
}
totalPrincipal -= _balances[msg.sender];
_balances[msg.sender] = 0;
numUsersWithDeposits -= 1;
require(_token.transfer(msg.sender, totalBalance));
emit TokenWithdrawn(msg.sender, totalBalance);
}
/**
* @dev Computes the amount of tokens the owner is allowed to withdraw
* @dev Assumes owner deposited tokens at the end of the deposit window, and not all users stay for the full 30 days
* @dev There will be a remainder because users leave before the 30 days is over. Owner withdraws the balance
*/
function adminWithdrawRemaining() external onlyOwner {
uint totalBalanceNeeded = compoundInterestByBlock(totalPrincipal);
uint contractBalance = _token.balanceOf(address(this));
// We deposit tokens and assume everyone gains yield for the full 30 days
// There is a difference because some users will withdraw tokens before the 30 days is over
if(contractBalance > totalBalanceNeeded) {
uint extraTokenBalance = contractBalance.sub(totalBalanceNeeded);
require(_token.transfer(msg.sender, extraTokenBalance));
emit TokenWithdrawn(msg.sender, extraTokenBalance);
}
}
/**
* @dev Lets owner, and only the owner, withdraw any amount of tokens
* @dev ONLY TO BE CALLED IN A CATASTROPHIC SCENARIO!!!
* @param _amount Number of tokens to withdraw
*/
function withdrawExtraTokens(uint _amount) external onlyOwner {
require(_token.transfer(msg.sender, _amount));
emit TokenWithdrawn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// 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: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
unchecked {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
unchecked {
return int64 (x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
unchecked {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (int256 (x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
unchecked {
require (x >= 0);
return uint64 (uint128 (x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
unchecked {
return int256 (x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (int256 (x)) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
unchecked {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
unchecked {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
unchecked {
require (x >= 0);
return int128 (sqrtu (uint256 (int256 (x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
return int128 (int256 (
uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
}
/**
* 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) {
unchecked {
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.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev 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;
}
}
|
Enables the deposit window to be changed. Only the smart contract owner is allowed to do this Because blocks are not always found at the same rate, we may need to change the deposit window so events start on time We will only call this so the start time is as accurate as possible We have to recompute the yield start block and yield end block times as well _depositStartBlock New deposit start block _depositEndBlock New deposit end block/
|
function changeDepositWindow(uint _depositStartBlock, uint _depositEndBlock) external onlyOwner {
compound.depositStartBlock = _depositStartBlock;
compound.depositEndBlock = _depositEndBlock;
compound.interestStartBlock = _depositEndBlock.add(1);
compound.interestEndBlock = compound.interestStartBlock.add(poolDurationByBlock);
uint blocksUntilInterestStarts = compound.interestStartBlock.sub(block.number);
compound.startTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = compound.interestEndBlock.sub(compound.interestStartBlock);
compound.endTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
}
| 1,068,551 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract Voting {
// Structures
struct Voter {
bool isRegistered;
bool hasVoted;
uint votedProposalId;
}
struct Proposal {
string description;
uint voteCount;
}
// vote mapping
struct Vote{
// Subject of the vote
string tips;
// Owner address
address owner;
// Winner ID
uint winningProposalId;
// Status ID
WorkflowStatus statusId;
//Voter mapping
mapping (address => Voter) voters;
uint votersCount;
// Proposal listing
Proposal[] proposals;
uint maxVoteCount;
}
// Enumeration
enum WorkflowStatus {
RegisteringVoters,
ProposalsRegistrationStarted,
ProposalsRegistrationEnded,
VotingSessionStarted,
VotingSessionEnded,
VotesTallied
}
mapping (uint => Vote) votes;// Maps use less gas than arrays
uint private votesCount;// So a counter is associated to retrive votes
// Events
event VoteCreated(uint voteIndex);
event VoterRegistered(uint voteIndex, address voterAddress);
event ProposalsRegistrationStarted(uint voteIndex);
event ProposalsRegistrationEnded(uint voteIndex);
event ProposalRegistered(uint voteIndex, uint proposalId);
event VotingSessionStarted(uint voteIndex);
event VotingSessionEnded(uint voteIndex);
event Voted (uint voteIndex, address voter, uint proposalId);
event VotesTallied(uint voteIndex);
event WorkflowStatusChange(uint voteIndex, WorkflowStatus previousStatus, WorkflowStatus newStatus);
modifier onlyOwner(uint index){
require(_isOwner(index, msg.sender), '0');//Ownable: caller can be only the owner of the vote
_;
}
modifier onlyRegistered(uint index){
require(votes[index].voters[msg.sender].isRegistered, '1');//Listed: caller has not been registered by the owner
_;
}
// For internal calls, the sender address should be retrived from the top call
function _isOwner(uint index, address _address) private view returns (bool) {
return votes[index].owner==_address;
}
modifier onlyRegisteredOrOwner(uint index){
require(votes[index].owner==msg.sender || votes[index].voters[msg.sender].isRegistered, '2');//Ownable or listed only
_;
}
// Setter and interaction functions //
// Add a new vote to the list
function newVote(string memory tips) external {// Everyone can add a new vote
require(bytes(tips).length>0, '3');//Tips should not be empty //didn't accept empty tips
votes[votesCount].tips = tips;
votes[votesCount].owner = msg.sender;
emit VoteCreated(votesCount);
votesCount+=1;
}
// I decided to use only one function insteed of specific status setter like "setProposalsRegistrationStartedStatus"
function setNextWorkflowStatus(uint index) external onlyOwner(index){
require(votes[index].statusId != WorkflowStatus.VotesTallied, '4');//The vote is already done
// keep the old status for the "WorkflowStatusChange" event.
WorkflowStatus oldStatus = votes[index].statusId;
// State machine for the status workflow
// 0_ Voters registration by the owner.
// 0 => 1_ I defined a minimum of two voters, otherwise the vote would not be necessary.
// Proposals registration for they registered address.
if (votes[index].statusId==WorkflowStatus.RegisteringVoters){
require(votes[index].votersCount>=2, '5');//We should have at least two voters to continue the workflow
votes[index].statusId = WorkflowStatus.ProposalsRegistrationStarted;
emit ProposalsRegistrationStarted(index);
}
// 1 => 2_ I defined a minimum of one proposal because it's the minimum to have an outcome.
// Close the registration period.
else if (votes[index].statusId==WorkflowStatus.ProposalsRegistrationStarted){
require(votes[index].proposals.length>=1, '6');//We should have at least one Proposal to continue the workflow
votes[index].statusId = WorkflowStatus.ProposalsRegistrationEnded;
emit ProposalsRegistrationEnded(index);
}
// 2 => 3_ I did not launch the voting session right afterwards to let the voters see the proposals
// Open the votes[index].
else if (votes[index].statusId==WorkflowStatus.ProposalsRegistrationEnded){
votes[index].statusId = WorkflowStatus.VotingSessionStarted;
emit VotingSessionStarted(index);
}
// 3 => 4_ Close the vote
else if (votes[index].statusId==WorkflowStatus.VotingSessionStarted){
votes[index].statusId = WorkflowStatus.VotingSessionEnded;
emit VotingSessionEnded(index);
}
// 4 => 5_ I did not launch the votes counting right after the VotingSessionEnded because there is two separated points in the exercice.
// But all results are publique so the suspense would not be there anyway.
else if (votes[index].statusId==WorkflowStatus.VotingSessionEnded){
votes[index].statusId = WorkflowStatus.VotesTallied;
emit VotesTallied(index);
}
emit WorkflowStatusChange(index, oldStatus, votes[index].statusId);
}
// Let a vote owner to register any etherum address to take part in the votes.
function authorize( uint index, address _address) external onlyOwner(index){
require(votes[index].statusId==WorkflowStatus.RegisteringVoters, '7');//Unable to register anyone after the RegisteringVoters workflow status
require(votes[index].voters[_address].isRegistered==false, '8');//Address already registered
votes[index].voters[_address] = Voter({isRegistered: true, hasVoted: false, votedProposalId: 0});
// The voter counter exists to ensure that there is a minimum of two.
votes[index].votersCount++;
emit VoterRegistered(index, _address);
}
// Registered address can add any proposition description at multiple times
function newProposal(uint index, string memory description) external onlyRegistered(index){
require(votes[index].statusId==WorkflowStatus.ProposalsRegistrationStarted, '9');//Unable to register any proposals. Proposals Registration not started or already ended
votes[index].proposals.push(Proposal({description: description, voteCount:0}));
emit ProposalRegistered(index, votes[index].proposals.length-1);
}
// Registered address can vote once for a registered proposals
function doVote(uint index, uint votedProposalId) external onlyRegistered(index){
require(votes[index].statusId==WorkflowStatus.VotingSessionStarted, '10');//Unable to vote while the current workflow status is not VotingSessionStarted
require(votes[index].voters[msg.sender].hasVoted==false, '11');//You can t vote twice
require(votes[index].proposals.length>votedProposalId, '12');//votedProposalId doesn t exist
votes[index].proposals[votedProposalId].voteCount++;
votes[index].voters[msg.sender].hasVoted = true;
votes[index].voters[msg.sender].votedProposalId = votedProposalId;
votes[index].proposals[votedProposalId].voteCount += 1;
// Check the winning proposal
if (votes[index].maxVoteCount<votes[index].proposals[votedProposalId].voteCount){
votes[index].winningProposalId = votedProposalId;
votes[index].maxVoteCount = votes[index].proposals[votedProposalId].voteCount;
}
emit Voted(index, msg.sender, votedProposalId);
}
// Some usefull getter
function getVoteCount() external view returns (uint){
return votesCount;
}
// get the vote purpos at the given index
function getVoteTips(uint index) external view returns(string memory){
require(votesCount>index, "13");//Given vote index doesn't exist
return votes[index].tips;
}
// Ask if the sender is the vote owner
function isOwner(uint index) external view returns(bool){
require(votesCount>index, "13");
return votes[index].owner==msg.sender;
}
// Ask if the sender has been registered in the vote by the owner
function isRegistered(uint index) external view returns(bool){
require(votesCount>index, "13");
return votes[index].voters[msg.sender].isRegistered;
}
// Get the current status of the vote as an ID (not very human readeable)
function getWorkflowStatus(uint index) external view returns (WorkflowStatus) {
require(votesCount>index, "13");
return votes[index].statusId;
}
function getProposalCount(uint index) external view returns(uint){
require(votesCount>index, "13");
return votes[index].proposals.length;
}
function getProposalDescriptionById(uint index, uint ProposalId) public view returns (string memory){
require(votesCount>index, "13");
require(votes[index].proposals.length>ProposalId, '12');
return votes[index].proposals[ProposalId].description;
}
// As explaned in the exercise, everyone can check the final details of the winning proposal so i did'n put the onlyRegistered modifier.
function getWinningProposalDescription(uint index) external view returns (string memory){
require(votesCount>index, "13");
require(votes[index].statusId==WorkflowStatus.VotesTallied, '15');//Vote not tallied yet
return getProposalDescriptionById(index, votes[index].winningProposalId);
}
function getProposalVoteCountById(uint index, uint ProposalId) external view onlyRegisteredOrOwner(index) returns (uint){
require(votesCount>index, "13");
require(votes[index].proposals.length>ProposalId, '12');
return votes[index].proposals[ProposalId].voteCount;
}
function getVotedProposalIdByAddress(uint index, address _address) external view returns (int){
require(votesCount>index, "13");
require(votes[index].statusId==WorkflowStatus.VotesTallied || votes[index].statusId==WorkflowStatus.VotingSessionStarted || votes[index].statusId==WorkflowStatus.VotingSessionEnded, 'Vote not started yet');
require(votes[index].voters[_address].hasVoted, '14');//This address has not voted
return int(votes[index].voters[_address].votedProposalId);
}
function hasVoted(uint index, address _address) external view returns (bool){
require(votesCount>index, "13");
return votes[index].voters[_address].hasVoted;
}
// get front vote informations
function getFullPersonalVoteInfo(uint index) external view returns(string memory, uint, bool, int, bool, uint){
require(votesCount>index, "13");
string memory tips = votes[index].tips;
uint state = uint(this.getWorkflowStatus(index));
bool registered = votes[index].voters[msg.sender].isRegistered;
int votedIndex = -1;
uint winningProposalId = 0;
if (registered && this.hasVoted(index, msg.sender)){
votedIndex = this.getVotedProposalIdByAddress(index, msg.sender);
winningProposalId = votes[index].winningProposalId;
}
bool owner = _isOwner(index, msg.sender);
return (tips, state, registered, votedIndex, owner, winningProposalId);
}
}
|
Registered address can add any proposition description at multiple times
|
function newProposal(uint index, string memory description) external onlyRegistered(index){
emit ProposalRegistered(index, votes[index].proposals.length-1);
votes[index].proposals.push(Proposal({description: description, voteCount:0}));
}
| 12,942,832 |
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
//import "@openzeppelin/contracts/math/Math.sol";
import "../openzeppelin-contracts-v3.3.0/contracts/math/Math.sol";
import "./Token.sol";
// Items, NFTs or resources
interface ERCItem {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function balanceOf(address acount) external returns (uint256);
// Used by resources - items/NFTs won't have this will this be an issue?
function stake(address account, uint256 amount) external;
function getStaked(address account) external returns(uint256);
}
contract FarmV2 {
using SafeMath for uint256;
TokenV2 private token;
struct Square {
Fruit fruit;
uint createdAt;
}
struct V1Farm {
address account;
uint tokenAmount;
uint size;
Fruit fruit;
}
uint farmCount = 0;
bool isMigrating = true;
mapping(address => Square[]) fields;
mapping(address => uint) syncedAt;
mapping(address => uint) rewardsOpenedAt;
constructor(TokenV2 _token) public {
token = _token;
}
// Need to upload these in batches so separate from constructor
function uploadV1Farms(V1Farm[] memory farms) public {
require(isMigrating, "MIGRATION_COMPLETE");
uint decimals = token.decimals();
// Carry over farms from V1
for (uint i=0; i < farms.length; i += 1) {
V1Farm memory farm = farms[i];
Square[] storage land = fields[farm.account];
// Treat them with a ripe plant
Square memory plant = Square({
fruit: farm.fruit,
createdAt: 0
});
for (uint j=0; j < farm.size; j += 1) {
land.push(plant);
}
syncedAt[farm.account] = block.timestamp;
rewardsOpenedAt[farm.account] = block.timestamp;
token.mint(farm.account, farm.tokenAmount * (10**decimals));
farmCount += 1;
}
}
function finishMigration() public {
isMigrating = false;
}
event FarmCreated(address indexed _address);
event FarmSynced(address indexed _address);
event ItemCrafted(address indexed _address, address _item);
// Function to receive Ether. msg.data must be empty
receive() external payable {}
function createFarm(address payable _charity) public payable {
require(syncedAt[msg.sender] == 0, "FARM_EXISTS");
uint decimals = token.decimals();
require(
// Donation must be at least $0.10 to play
msg.value >= 1 * 10**(decimals - 1),
"INSUFFICIENT_DONATION"
);
require(
// The Water Project - double check
_charity == address(0x060697E9d4EEa886EbeCe57A974Facd53A40865B)
// Heifer
|| _charity == address(0xD3F81260a44A1df7A7269CF66Abd9c7e4f8CdcD1)
// Cool Earth
|| _charity == address(0x3c8cB169281196737c493AfFA8F49a9d823bB9c5),
"INVALID_CHARITY"
);
Square[] storage land = fields[msg.sender];
Square memory empty = Square({
fruit: Fruit.None,
createdAt: 0
});
Square memory sunflower = Square({
fruit: Fruit.Sunflower,
createdAt: 0
});
// Each farmer starts with 5 fields & 3 Sunflowers
land.push(empty);
land.push(sunflower);
land.push(sunflower);
land.push(sunflower);
land.push(empty);
syncedAt[msg.sender] = block.timestamp;
// They must wait X days before opening their first reward
rewardsOpenedAt[msg.sender] = block.timestamp;
(bool sent, bytes memory data) = _charity.call{value: msg.value}("");
require(sent, "DONATION_FAILED");
farmCount += 1;
//Emit an event
emit FarmCreated(msg.sender);
}
function lastSyncedAt(address owner) private view returns(uint) {
return syncedAt[owner];
}
function getLand(address owner) public view returns (Square[] memory) {
return fields[owner];
}
enum Action { Plant, Harvest }
enum Fruit { None, Sunflower, Potato, Pumpkin, Beetroot, Cauliflower, Parsnip, Radish }
struct Event {
Action action;
Fruit fruit;
uint landIndex;
uint createdAt;
}
struct Farm {
Square[] land;
uint balance;
}
function getHarvestSeconds(Fruit _fruit) private pure returns (uint) {
if (_fruit == Fruit.Sunflower) {
// 1 minute
return 1 * 60;
} else if (_fruit == Fruit.Potato) {
// 5 minutes
return 5 * 60;
} else if (_fruit == Fruit.Pumpkin) {
// 1 hour
return 1 * 60 * 60;
} else if (_fruit == Fruit.Beetroot) {
// 4 hours
return 4 * 60 * 60;
} else if (_fruit == Fruit.Cauliflower) {
// 8 hours
return 8 * 60 * 60;
} else if (_fruit == Fruit.Parsnip) {
// 1 day
return 24 * 60 * 60;
} else if (_fruit == Fruit.Radish) {
// 3 days
return 3 * 24 * 60 * 60;
}
require(false, "INVALID_FRUIT");
return 9999999;
}
function getSeedPrice(Fruit _fruit) private view returns (uint price) {
uint decimals = token.decimals();
if (_fruit == Fruit.Sunflower) {
//$0.01
return 1 * 10**decimals / 100;
} else if (_fruit == Fruit.Potato) {
// $0.10
return 10 * 10**decimals / 100;
} else if (_fruit == Fruit.Pumpkin) {
// $0.40
return 40 * 10**decimals / 100;
} else if (_fruit == Fruit.Beetroot) {
// $1
return 1 * 10**decimals;
} else if (_fruit == Fruit.Cauliflower) {
// $4
return 4 * 10**decimals;
} else if (_fruit == Fruit.Parsnip) {
// $10
return 10 * 10**decimals;
} else if (_fruit == Fruit.Radish) {
// $50
return 50 * 10**decimals;
}
require(false, "INVALID_FRUIT");
return 100000 * 10**decimals;
}
function getFruitPrice(Fruit _fruit) private view returns (uint price) {
uint decimals = token.decimals();
if (_fruit == Fruit.Sunflower) {
// $0.02
return 2 * 10**decimals / 100;
} else if (_fruit == Fruit.Potato) {
// $0.16
return 16 * 10**decimals / 100;
} else if (_fruit == Fruit.Pumpkin) {
// $0.80
return 80 * 10**decimals / 100;
} else if (_fruit == Fruit.Beetroot) {
// $1.8
return 180 * 10**decimals / 100;
} else if (_fruit == Fruit.Cauliflower) {
// $8
return 8 * 10**decimals;
} else if (_fruit == Fruit.Parsnip) {
// $16
return 16 * 10**decimals;
} else if (_fruit == Fruit.Radish) {
// $80
return 80 * 10**decimals;
}
require(false, "INVALID_FRUIT");
return 0;
}
function requiredLandSize(Fruit _fruit) private pure returns (uint size) {
if (_fruit == Fruit.Sunflower || _fruit == Fruit.Potato) {
return 5;
} else if (_fruit == Fruit.Pumpkin || _fruit == Fruit.Beetroot) {
return 8;
} else if (_fruit == Fruit.Cauliflower) {
return 11;
} else if (_fruit == Fruit.Parsnip) {
return 14;
} else if (_fruit == Fruit.Radish) {
return 17;
}
require(false, "INVALID_FRUIT");
return 99;
}
function getLandPrice(uint landSize) private view returns (uint price) {
uint decimals = token.decimals();
if (landSize <= 5) {
// $1
return 1 * 10**decimals;
} else if (landSize <= 8) {
// 50
return 50 * 10**decimals;
} else if (landSize <= 11) {
// $500
return 500 * 10**decimals;
}
// $2500
return 2500 * 10**decimals;
}
modifier hasFarm {
require(lastSyncedAt(msg.sender) > 0, "NO_FARM");
_;
}
uint private THIRTY_MINUTES = 30 * 60;
function buildFarm(Event[] memory _events) private view hasFarm returns (Farm memory currentFarm) {
Square[] memory land = fields[msg.sender];
uint balance = token.balanceOf(msg.sender);
for (uint index = 0; index < _events.length; index++) {
Event memory farmEvent = _events[index];
uint thirtyMinutesAgo = block.timestamp.sub(THIRTY_MINUTES);
require(farmEvent.createdAt >= thirtyMinutesAgo, "EVENT_EXPIRED");
require(farmEvent.createdAt >= lastSyncedAt(msg.sender), "EVENT_IN_PAST");
require(farmEvent.createdAt <= block.timestamp, "EVENT_IN_FUTURE");
if (index > 0) {
require(farmEvent.createdAt >= _events[index - 1].createdAt, "INVALID_ORDER");
}
if (farmEvent.action == Action.Plant) {
require(land.length >= requiredLandSize(farmEvent.fruit), "INVALID_LEVEL");
uint price = getSeedPrice(farmEvent.fruit);
uint fmcPrice = getMarketPrice(price);
require(balance >= fmcPrice, "INSUFFICIENT_FUNDS");
balance = balance.sub(fmcPrice);
Square memory plantedSeed = Square({
fruit: farmEvent.fruit,
createdAt: farmEvent.createdAt
});
land[farmEvent.landIndex] = plantedSeed;
} else if (farmEvent.action == Action.Harvest) {
Square memory square = land[farmEvent.landIndex];
require(square.fruit != Fruit.None, "NO_FRUIT");
uint duration = farmEvent.createdAt.sub(square.createdAt);
uint secondsToHarvest = getHarvestSeconds(square.fruit);
require(duration >= secondsToHarvest, "NOT_RIPE");
// Clear the land
Square memory emptyLand = Square({
fruit: Fruit.None,
createdAt: 0
});
land[farmEvent.landIndex] = emptyLand;
uint price = getFruitPrice(square.fruit);
uint fmcPrice = getMarketPrice(price);
balance = balance.add(fmcPrice);
}
}
return Farm({
land: land,
balance: balance
});
}
function sync(Event[] memory _events) public hasFarm returns (Farm memory) {
Farm memory farm = buildFarm(_events);
// Update the land
Square[] storage land = fields[msg.sender];
for (uint i=0; i < farm.land.length; i += 1) {
land[i] = farm.land[i];
}
syncedAt[msg.sender] = block.timestamp;
uint balance = token.balanceOf(msg.sender);
// Update the balance - mint or burn
if (farm.balance > balance) {
uint profit = farm.balance.sub(balance);
token.mint(msg.sender, profit);
} else if (farm.balance < balance) {
uint loss = balance.sub(farm.balance);
token.burn(msg.sender, loss);
}
emit FarmSynced(msg.sender);
return farm;
}
function levelUp() public hasFarm {
require(fields[msg.sender].length <= 17, "MAX_LEVEL");
Square[] storage land = fields[msg.sender];
uint price = getLandPrice(land.length);
uint fmcPrice = getMarketPrice(price);
uint balance = token.balanceOf(msg.sender);
require(balance >= fmcPrice, "INSUFFICIENT_FUNDS");
// Store rewards in the Farm Contract to redistribute
token.transferFrom(msg.sender, address(this), fmcPrice);
// Add 3 sunflower fields in the new fields
Square memory sunflower = Square({
fruit: Fruit.Sunflower,
// Make them immediately harvestable in case they spent all their tokens
createdAt: 0
});
for (uint index = 0; index < 3; index++) {
land.push(sunflower);
}
emit FarmSynced(msg.sender);
}
// How many tokens do you get per dollar
// Algorithm is totalSupply / 10000 but we do this in gradual steps to avoid widly flucating prices between plant & harvest
function getMarketRate() private view returns (uint conversion) {
uint decimals = token.decimals();
uint totalSupply = token.totalSupply();
// Less than 100, 000 tokens
if (totalSupply < (100000 * 10**decimals)) {
// 1 Farm Dollar gets you 1 FMC token
return 1;
}
// Less than 500, 000 tokens
if (totalSupply < (500000 * 10**decimals)) {
return 5;
}
// Less than 1, 000, 000 tokens
if (totalSupply < (1000000 * 10**decimals)) {
return 10;
}
// Less than 5, 000, 000 tokens
if (totalSupply < (5000000 * 10**decimals)) {
return 50;
}
// Less than 10, 000, 000 tokens
if (totalSupply < (10000000 * 10**decimals)) {
return 100;
}
// Less than 50, 000, 000 tokens
if (totalSupply < (50000000 * 10**decimals)) {
return 500;
}
// Less than 100, 000, 000 tokens
if (totalSupply < (100000000 * 10**decimals)) {
return 1000;
}
// Less than 500, 000, 000 tokens
if (totalSupply < (500000000 * 10**decimals)) {
return 5000;
}
// Less than 1, 000, 000, 000 tokens
if (totalSupply < (1000000000 * 10**decimals)) {
return 10000;
}
// 1 Farm Dollar gets you a 0.00001 of a token - Linear growth from here
return totalSupply.div(10000);
}
function getMarketPrice(uint price) public view returns (uint conversion) {
uint marketRate = getMarketRate();
return price.div(marketRate);
}
function getFarm(address account) public view returns (Square[] memory farm) {
return fields[account];
}
function getFarmCount() public view returns (uint count) {
return farmCount;
}
// Depending on the fields you have determines your cut of the rewards.
function myReward() public view hasFarm returns (uint amount) {
uint lastOpenDate = rewardsOpenedAt[msg.sender];
// Block timestamp is seconds based
uint threeDaysAgo = block.timestamp.sub(60 * 60 * 24 * 3);
require(lastOpenDate < threeDaysAgo, "NO_REWARD_READY");
uint landSize = fields[msg.sender].length;
// E.g. $1000
uint farmBalance = token.balanceOf(address(this));
// E.g. $1000 / 500 farms = $2
uint farmShare = farmBalance / farmCount;
if (landSize <= 5) {
// E.g $0.2
return farmShare.div(10);
} else if (landSize <= 8) {
// E.g $0.4
return farmShare.div(5);
} else if (landSize <= 11) {
// E.g $1
return farmShare.div(2);
}
// E.g $3
return farmShare.mul(3).div(2);
}
function receiveReward() public hasFarm {
uint amount = myReward();
require(amount > 0, "NO_REWARD_AMOUNT");
rewardsOpenedAt[msg.sender] = block.timestamp;
token.transfer(msg.sender, amount);
}
/**
Multi-token economy configurability below
*/
// An in game material - Crafted Item, NFT or resource
struct Material {
address materialAddress;
bool exists;
}
struct Cost {
address materialAddress;
uint amount;
}
struct Recipe {
address outputAddress;
Cost[] costs;
}
struct Resource {
address outputAddress;
address inputAddress;
}
mapping(address => Resource) resources;
mapping(address => Recipe) recipes;
mapping(address => Material) materials;
// Put down a resource - tokens have their own mechanism for reflecting rewards
function stake(address resourceAddress, uint amount) public {
Material memory material = materials[resourceAddress];
require(material.exists, "RESOURCE_DOES_NOT_EXIST");
Resource memory resource = resources[resourceAddress];
ERCItem(resource.inputAddress).burn(msg.sender, amount);
// The resource contract will determine tokenomics and what to do with staked amount
ERCItem(resource.outputAddress).stake(msg.sender, amount);
}
function createRecipe(address tokenAddress, Cost[] memory costs) public {
require(tokenAddress != address(token), "SUNFLOWER_TOKEN_IN_USE");
require(!materials[tokenAddress].exists, "RECIPE_ALREADY_EXISTS");
// Ensure all materials are setup
for (uint i=0; i < costs.length; i += 1) {
address input = costs[i].materialAddress;
Material memory material = materials[input];
require(input == address(token) || material.exists, "MATERIAL_DOES_NOT_EXIST");
recipes[tokenAddress].costs.push(costs[i]);
}
materials[tokenAddress] = Material({
exists: true,
materialAddress: tokenAddress
});
}
function createResource(address resourceAddress, address requires) public {
require(resourceAddress != address(token), "SUNFLOWER_TOKEN_IN_USE");
require(!materials[resourceAddress].exists, "RESOURCE_ALREADY_EXISTS");
// Check the required material is setup
require(materials[requires].exists, "MATERIAL_DOES_NOT_EXIST");
resources[resourceAddress] = Resource({
outputAddress: resourceAddress,
inputAddress: requires
});
materials[resourceAddress] = Material({
exists: true,
materialAddress: resourceAddress
});
}
function burnCosts(address recipeAddress, uint total) private {
Recipe memory recipe = recipes[recipeAddress];
// ERC20 contracts will validate as needed
for (uint i=0; i < recipe.costs.length; i += 1) {
Cost memory cost = recipe.costs[i];
uint price = cost.amount * total;
// Never burn SFF - Store rewards in the Farm Contract to redistribute
if (cost.materialAddress == address(token)) {
token.transferFrom(msg.sender, address(this), price);
} else {
ERCItem(cost.materialAddress).burn(msg.sender, price);
}
}
}
function craft(address recipeAddress, uint amount) public {
Material memory material = materials[recipeAddress];
require(material.exists, "RECIPE_DOES_NOT_EXIST");
burnCosts(recipeAddress, amount);
ERCItem(recipeAddress).mint(msg.sender, amount);
emit ItemCrafted(msg.sender, recipeAddress);
}
function mintNFT(address recipeAddress, uint tokenId) public {
Material memory material = materials[recipeAddress];
require(material.exists, "RECIPE_DOES_NOT_EXIST");
burnCosts(recipeAddress, 1);
ERCItem(recipeAddress).mint(msg.sender, tokenId);
emit ItemCrafted(msg.sender, recipeAddress);
}
function getRecipe(address recipeAddress) public view returns (Recipe memory recipe) {
return recipes[recipeAddress];
}
function getResource(address resourceAddress) public view returns (Resource memory resource) {
return resources[resourceAddress];
}
}
|
Donation must be at least $0.10 to play The Water Project - double check Heifer Cool Earth
|
function createFarm(address payable _charity) public payable {
require(syncedAt[msg.sender] == 0, "FARM_EXISTS");
uint decimals = token.decimals();
require(
msg.value >= 1 * 10**(decimals - 1),
"INSUFFICIENT_DONATION"
);
require(
_charity == address(0x060697E9d4EEa886EbeCe57A974Facd53A40865B)
|| _charity == address(0xD3F81260a44A1df7A7269CF66Abd9c7e4f8CdcD1)
|| _charity == address(0x3c8cB169281196737c493AfFA8F49a9d823bB9c5),
"INVALID_CHARITY"
);
Square[] storage land = fields[msg.sender];
Square memory empty = Square({
fruit: Fruit.None,
createdAt: 0
});
Square memory sunflower = Square({
fruit: Fruit.Sunflower,
createdAt: 0
});
land.push(sunflower);
land.push(sunflower);
land.push(sunflower);
land.push(empty);
syncedAt[msg.sender] = block.timestamp;
require(sent, "DONATION_FAILED");
farmCount += 1;
}
| 2,573,127 |
pragma solidity ^ 0.8.0;
import "hardhat/console.sol";
import { IDiamondCut } from "../interfaces/IDiamondCut.sol";
import { LibDiamond } from "../libraries/LibDiamond.sol";
import "../libraries/AppStorage.sol";
contract SLAInitializing{
AppStorage internal s;
function setBlkNeeded(uint8 _blkNeed)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
require(_blkNeed > 1);
s.BlkNeeded = _blkNeed;
}
////the unit is Szabo = 0.001 finney
function setCompensationFee(uint _compensationFee)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
require(_compensationFee > 0);
uint oneUnit = 1e12;
s.CompensationFee = _compensationFee*oneUnit;
}
function setServiceFee(uint _serviceFee)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
require(_serviceFee > 0);
uint oneUnit = 1e12;
s.ServiceFee = _serviceFee*oneUnit;
}
function setWitnessFee(uint _witnessFee)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
require(_witnessFee > 0);
uint oneUnit = 1e12;
s.WF4NoViolation = _witnessFee*oneUnit;
s.VoteFee = s.WF4NoViolation;
}
//the unit is minutes
function setServiceDuration(uint _serviceDuration)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
require(_serviceDuration > 0);
uint oneUnit = 1 minutes;
s.ServiceDuration = _serviceDuration*oneUnit;
}
//Set the witness committee number, which is the 'N'
function setWitnessCommNum(uint _witnessCommNum)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
require(_witnessCommNum > 2);
require(_witnessCommNum > s.witnessCommittee.length);
s.WitnessNumber = _witnessCommNum;
}
// Set the 'M' out of 'N' to confirm the violation
function setConfirmNum(uint _confirmNum)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
//// N/2 < M < N
require(_confirmNum > (s.WitnessNumber/2));
require(_confirmNum < s.WitnessNumber);
s.ConfirmNumRequired = _confirmNum;
}
//Set the customer address
// function setCustomer(address _customer)
// public
// checkState(State.Fresh)
// checkProvider
// {
// Customer = _customer;
// }
//// this is for Cloud provider to publish its service detail
function publishService(string memory _serviceDetail)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
s.cloudServiceDetail = _serviceDetail;
}
}
|
/the unit is Szabo = 0.001 finney
|
function setCompensationFee(uint _compensationFee)
public
{
require(s.SLAState == State.Fresh);
require(msg.sender == s.Provider);
require(_compensationFee > 0);
uint oneUnit = 1e12;
s.CompensationFee = _compensationFee*oneUnit;
}
| 6,459,886 |
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
uint private constant MINIMUM_FUNDING_THRESHOLD = 10 ether;
uint private constant MAXIMUM_INSURANCE_AMOUNT = 1 ether;
uint private constant PAYOUT_MULTIPLIER_TIMES_TEN = 15;
// Flight status codes
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
FlightSuretyData flightSuretyData;
struct Poll {
bool isActive;
address target;
uint requiredVotes;
uint yesVotes;
uint noVotes;
}
Poll private airlineRegisterPoll;
mapping(address => bool) private hasVoted;
address[] private voterList;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
// uint private tempIndex;
/********************************************************************************************/
/* 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() {
// Modify to call data contract's status
require(true, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the caller to be an an existing airline
*/
modifier isAirline() {
require(flightSuretyData.isAirline(msg.sender), "Caller is not a registered airline");
_;
}
/**
* @dev Modifier that requires the caller to be a funded airline
*/
modifier isFunded() {
require(flightSuretyData.getFunding(msg.sender) >= MINIMUM_FUNDING_THRESHOLD, "Caller does not have required funding");
_;
}
modifier isNotDuplicated(address newAirline) {
require(!flightSuretyData.isAirline(newAirline), "Airline is already registered");
_;
}
/**
* @dev Determines if the target address is being voted on
*/
modifier isActiveVote(address newAirline) {
require(newAirline == airlineRegisterPoll.target, "This address is not open for voting");
require(airlineRegisterPoll.isActive, "This vote has already concluded");
_;
}
/**
* @dev Determines if the sender has already voted
*/
modifier isNotDuplicateVoter() {
require(!hasVoted[msg.sender], "Caller has already voted");
_;
}
modifier inTheFuture(uint timestamp) {
require(timestamp > now, "Provided timestamp is in the past");
_;
}
modifier flightIsRegistered(address airline, string flight, uint timestamp) {
require(flights[getFlightKey(airline, flight, timestamp)].isRegistered, "Flight has not yet been registered");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address dataContract) public {
contractOwner = msg.sender;
flightSuretyData = FlightSuretyData(dataContract);
}
/********************************************************************************************/
/* 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 getPollStatus() public view returns (bool, address, uint, uint, uint) {
return (airlineRegisterPoll.isActive, airlineRegisterPoll.target, airlineRegisterPoll.requiredVotes,
airlineRegisterPoll.yesVotes, airlineRegisterPoll.noVotes);
}
function getVoterList() public view returns (address[] memory) {
return voterList;
}
function getHasVoted(address voter) public view returns (bool) {
return hasVoted[voter];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline(address newAirline) external
requireIsOperational()
isAirline()
isFunded()
isNotDuplicated(newAirline) {
uint numAirlines = flightSuretyData.getAirlineAddresses().length;
if (numAirlines < 4) {
flightSuretyData.registerAirline(newAirline);
} else {
openPoll(newAirline);
}
}
/**
* @dev Existing airlines can vote for a new airline to be registered
*
*/
function voteAirline(address newAirline, bool approve) external
requireIsOperational()
isAirline()
isFunded()
isActiveVote(newAirline)
isNotDuplicateVoter() {
if (approve) {
airlineRegisterPoll.yesVotes = airlineRegisterPoll.yesVotes.add(1);
} else {
airlineRegisterPoll.noVotes = airlineRegisterPoll.noVotes.add(1);
}
hasVoted[msg.sender] = true;
voterList.push(msg.sender);
if(airlineRegisterPoll.yesVotes >= airlineRegisterPoll.requiredVotes) {
closePollSuccess(newAirline);
} else if(airlineRegisterPoll.yesVotes.add(airlineRegisterPoll.noVotes) >= getNumberOfFundedAirlines()) {
closePollFail();
}
}
/**
* @dev Adds funding to the airline
*
*/
function fund() external payable
requireIsOperational()
isAirline() {
flightSuretyData.fund.value(msg.value)(msg.sender);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(string flight, uint timestamp) external
requireIsOperational()
isAirline()
isFunded()
inTheFuture(timestamp) {
bytes32 flightKey = getFlightKey(msg.sender, flight, timestamp);
flights[flightKey].isRegistered = true;
flights[flightKey].statusCode = STATUS_CODE_ON_TIME;
flights[flightKey].updatedTimestamp = timestamp;
flights[flightKey].airline = msg.sender;
}
/**
* @dev Buy insurance for a flight
*
*/
function buyFlightInsurance(address airline, string flight, uint timestamp) external payable
requireIsOperational()
flightIsRegistered(airline, flight, timestamp) {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flightSuretyData.buy.value(msg.value)(msg.sender, flightKey, MAXIMUM_INSURANCE_AMOUNT);
}
function withdraw() external
requireIsOperational() {
flightSuretyData.pay(msg.sender);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus(address airline, string memory flight, uint256 timestamp, uint8 statusCode) internal {
if(statusCode == STATUS_CODE_LATE_AIRLINE) {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flightSuretyData.creditInsurees(flightKey, PAYOUT_MULTIPLIER_TIMES_TEN);
}
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus(
address airline,
string flight,
uint256 timestamp
) external
requireIsOperational() {
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(
abi.encodePacked(index, airline, flight, timestamp)
);
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
// tempIndex = index;
emit OracleRequest(index, airline, flight, timestamp);
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
event OracleReport(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(
uint8 index,
address airline,
string flight,
uint256 timestamp
);
// Register an oracle with the contract
function registerOracle() external payable
requireIsOperational() {
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes});
}
function getMyIndexes() external view returns (uint8[3] memory) {
require(
oracles[msg.sender].isRegistered,
"Not registered as an oracle"
);
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
) external
requireIsOperational() {
require(
(oracles[msg.sender].indexes[0] == index) ||
(oracles[msg.sender].indexes[1] == index) ||
(oracles[msg.sender].indexes[2] == index),
"Index does not match oracle request"
);
bytes32 key = keccak256(
abi.encodePacked(index, airline, flight, timestamp)
);
require(
oracleResponses[key].isOpen,
"Flight or timestamp do not match oracle request"
);
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (
oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES
) {
//Prevent processFlightStatus from being called more than once
oracleResponses[key].isOpen = false;
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
function getFlightKey(address airline, string memory flight, uint256 timestamp) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getPassengerKey(address passenger, bytes32 flightKey) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(passenger, flightKey));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address account) internal returns (uint8[3] memory) {
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address account) internal returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(
uint256(
keccak256(
abi.encodePacked(blockhash(block.number - nonce++), account)
)
) % maxValue
);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function getFlight(address airline, string flight, uint256 timestamp) external view returns (bool, uint8, uint256, address) {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
return (flights[flightKey].isRegistered, flights[flightKey].statusCode, flights[flightKey].updatedTimestamp, flights[flightKey].airline);
}
// function getTempIndex() external view returns (uint) {
// return tempIndex;
// }
/********************************************************************************************/
/* HELPER FUNCTIONS */
/********************************************************************************************/
function getNumberOfFundedAirlines() internal returns (uint) {
address[] memory allAirlines = flightSuretyData.getAirlineAddresses();
uint numFundedAirlines = 0;
for (uint i = 0; i < allAirlines.length; i++) {
address currentAirline = allAirlines[i];
if (flightSuretyData.getFunding(currentAirline) >= MINIMUM_FUNDING_THRESHOLD) {
numFundedAirlines = numFundedAirlines.add(1);
}
}
return numFundedAirlines;
}
function openPoll(address newAirline) internal {
airlineRegisterPoll = Poll({
isActive: true,
target: newAirline,
requiredVotes: getRequiredVotes(),
yesVotes: 1,
noVotes: 0
});
hasVoted[msg.sender] = true;
voterList.push(msg.sender);
if (airlineRegisterPoll.yesVotes >= airlineRegisterPoll.requiredVotes) {
closePollSuccess(newAirline);
}
}
function closePollFail() internal {
uint numVoters = voterList.length;
for (uint i = 0; i < numVoters; i++) {
hasVoted[voterList[i]] = false;
}
delete voterList;
airlineRegisterPoll.isActive = false;
}
function closePollSuccess(address newAirline) internal {
closePollFail();
flightSuretyData.registerAirline(newAirline);
}
function getRequiredVotes() internal returns (uint) {
uint requiredVotes = 0;
uint numFundedAirlines = getNumberOfFundedAirlines();
// If even number of airlines, required votes = number of airlines / 2.
// If odd number of airlines, required votes = number of airlines / 2 + 1.
if (numFundedAirlines.div(2).mul(2) == numFundedAirlines) {
requiredVotes = numFundedAirlines.div(2);
} else {
requiredVotes = numFundedAirlines.div(2).add(1);
}
return requiredVotes;
}
}
// Define interface to interact with the data contract
contract FlightSuretyData {
function registerAirline(address newAirline) external;
function isAirline(address id) external returns (bool);
function fund(address airline) public payable;
function getFunding(address id) external returns (uint);
function getAirlineAddresses() external returns (address[] memory);
function buy(address passenger, bytes32 flightKey, uint limit) external payable;
function creditInsurees(bytes32 flightKey, uint multiplierTimesTen) external;
function pay(address account) external;
}
|
Called by oracle when a response is available to an outstanding request For the response to be accepted, there must be a pending request that is open and matches one of the three Indexes randomly assigned to the oracle at the time of registration (i.e. uninvited oracles are not welcome) Information isn't considered verified until at least MIN_RESPONSES oracles respond with the same informationPrevent processFlightStatus from being called more than once Handle flight status as appropriate
|
function submitOracleResponse(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
) external
requireIsOperational() {
require(
(oracles[msg.sender].indexes[0] == index) ||
(oracles[msg.sender].indexes[1] == index) ||
(oracles[msg.sender].indexes[2] == index),
"Index does not match oracle request"
);
bytes32 key = keccak256(
abi.encodePacked(index, airline, flight, timestamp)
);
require(
oracleResponses[key].isOpen,
"Flight or timestamp do not match oracle request"
);
oracleResponses[key].responses[statusCode].push(msg.sender);
emit OracleReport(airline, flight, timestamp, statusCode);
if (
oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES
) {
oracleResponses[key].isOpen = false;
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
| 6,358,839 |
pragma solidity ^0.4.24;
contract Factory {
address developer = 0x0033F8dAcBc75F53549298100E85102be995CdBF59;
event ContractCreated(address creator, address newcontract, uint timestamp, string contract_type);
function setDeveloper (address _dev) public {
if(developer==address(0) || developer==msg.sender){
developer = _dev;
}
}
function createContract (bool isbroker, string contract_type, bool _brokerrequired)
public {
address newContract = new Broker(isbroker, developer, msg.sender, _brokerrequired);
emit ContractCreated(msg.sender, newContract, block.timestamp, contract_type);
}
}
contract Broker {
enum State { Created, Validated, Locked, Finished }
State public state;
enum FileState {
Created,
Invalidated
// , Confirmed
}
struct File{
// The purpose of this file. Like, picture, license info., etc.
// to save the space, we better use short name.
// Dapps should match proper long name for this.
bytes32 purpose;
// name of the file
string name;
// ipfs id for this file
string ipfshash;
FileState state;
}
struct Item{
string name;
// At least 0.1 Finney, because it's the fee to the developer
uint price;
// this could be a link to an Web page explaining about this item
string detail;
File[] documents;
}
struct BuyInfo{
address buyer;
bool completed;
}
Item public item;
address public seller = address(0);
address public broker = address(0);
uint public brokerFee;
// Minimum 0.1 Finney (0.0001 eth ~ 25Cent) to 0.01% of the price.
uint public developerfee = 0.1 finney;
uint minimumdeveloperfee = 0.1 finney;
address developer = 0x0033F8dAcBc75F53549298100E85102be995CdBF59;
// bool public validated;
address creator = 0x0;
address factory = 0x0;
bool bBrokerRequired = true;
BuyInfo[] public buyinfo;
modifier onlySeller() {
require(msg.sender == seller);
_;
}
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
modifier onlyBroker() {
require(msg.sender == broker);
_;
}
modifier inState(State _state) {
require(state == _state);
_;
}
modifier condition(bool _condition) {
require(_condition);
_;
}
event AbortedBySeller();
event AbortedByBroker();
event PurchaseConfirmed(address buyer);
event ItemReceived();
event IndividualItemReceived(address buyer);
event Validated();
event ItemInfoChanged(string name, uint price, string detail, uint developerfee);
event SellerChanged(address seller);
event BrokerChanged(address broker);
event BrokerFeeChanged(uint fee);
// The constructor
constructor(bool isbroker, address _dev, address _creator, bool _brokerrequired)
public
{
bBrokerRequired = _brokerrequired;
if(creator==address(0)){
//storedData = initialValue;
if(isbroker)
broker = _creator;
else
seller = _creator;
creator = _creator;
// value = msg.value / 2;
// require((2 * value) == msg.value);
state = State.Created;
// validated = false;
brokerFee = 50;
}
if(developer==address(0) || developer==msg.sender){
developer = _dev;
}
if(factory==address(0)){
factory = msg.sender;
}
}
function joinAsBroker() public {
if(broker==address(0)){
broker = msg.sender;
}
}
function createOrSet(string name, uint price, string detail)
public
inState(State.Created)
onlyCreator
{
require(price > minimumdeveloperfee);
item.name = name;
item.price = price;
item.detail = detail;
developerfee = (price/1000)<minimumdeveloperfee ? minimumdeveloperfee : (price/1000);
emit ItemInfoChanged(name, price, detail, developerfee);
}
function getBroker()
public
constant returns(address, uint)
{
return (broker, brokerFee);
}
function getSeller()
public
constant returns(address)
{
return (seller);
}
function getBuyers()
public
constant returns(address[])
{
address[] memory buyers = new address[](buyinfo.length);
//uint val = address(this).balance / buyinfo.length;
for (uint256 x = 0; x < buyinfo.length; x++) {
buyers[x] = buyinfo[x].buyer;
}
return (buyers);
}
function getBuyerInfoAt(uint256 x)
public
constant returns(address, bool)
{
return (buyinfo[x].buyer, buyinfo[x].completed);
}
function setBroker(address _address)
public
onlySeller
inState(State.Created)
{
broker = _address;
emit BrokerChanged(broker);
}
function setBrokerFee(uint fee)
public
onlyCreator
inState(State.Created)
{
brokerFee = fee;
emit BrokerFeeChanged(fee);
}
function setSeller(address _address)
public
onlyBroker
inState(State.Created)
{
seller = _address;
emit SellerChanged(seller);
}
// We will have some 'peculiar' list of documents
// for each deals.
// For ex, for House we will require
// proof of documents about the basic information of the House,
// and some insurance information.
// So we can make a template for each differene kind of deals.
// Deals for a house, deals for a Car, etc.
function addDocument(bytes32 _purpose, string _name, string _ipfshash)
public
{
require(state != State.Finished);
require(state != State.Locked);
item.documents.push( File({
purpose:_purpose, name:_name, ipfshash:_ipfshash, state:FileState.Created}
)
);
}
// deleting actual file on the IPFS network is very hard.
function deleteDocument(uint index)
public
{
require(state != State.Finished);
require(state != State.Locked);
if(index<item.documents.length){
item.documents[index].state = FileState.Invalidated;
}
}
function validate()
public
onlyBroker
inState(State.Created)
{
// if(index<item.documents.length){
// item.documents[index].state = FileState.Confirmed;
// }
emit Validated();
// validated = true;
state = State.Validated;
}
function returnMoneyToBuyers()
private
{
require(state != State.Finished);
if(buyinfo.length>0){
uint val = address(this).balance / buyinfo.length;
for (uint256 x = 0; x < buyinfo.length; x++) {
if(buyinfo[x].completed==false){
buyinfo[x].buyer.transfer(val);
}
}
}
state = State.Finished;
}
/// Abort the purchase and reclaim the ether.
/// Can only be called by the seller before
/// the contract is locked.
function abort()
public
onlySeller
{
returnMoneyToBuyers();
emit AbortedBySeller();
// validated = false;
seller.transfer(address(this).balance);
}
function abortByBroker()
public
onlyBroker
{
if(!bBrokerRequired)
return;
returnMoneyToBuyers();
emit AbortedByBroker();
}
/// Confirm the purchase as buyer.
/// The ether will be locked until confirmReceived
/// is called.
function confirmPurchase()
public
condition(msg.value == item.price)
payable
{
if(bBrokerRequired){
if(state != State.Validated && state != State.Locked){
return;
}
}
if(state == State.Finished){
return;
}
state = State.Locked;
emit PurchaseConfirmed(msg.sender);
bool complete = false;
if(!bBrokerRequired){
// send money right away
complete = true;
seller.transfer(item.price-developerfee);
developer.transfer(developerfee);
}
buyinfo.push(BuyInfo(msg.sender, complete));
}
/// Confirm that you (the buyer) received the item.
/// This will release the locked ether.
function confirmReceived()
public
onlyBroker
inState(State.Locked)
{
if(buyinfo.length>0){
for (uint256 x = 0; x < buyinfo.length; x++) {
confirmReceivedAt(x);
}
}
// It is important to change the state first because
// otherwise, the contracts called using `send` below
// can call in again here.
state = State.Finished;
}
//
function confirmReceivedAt(uint index)
public
onlyBroker
inState(State.Locked)
{
// In this case the broker is confirming one by one,
// the other purchase should go on. So we don't change the status.
if(index>=buyinfo.length)
return;
if(buyinfo[index].completed)
return;
// NOTE: This actually allows both the buyer and the seller to
// block the refund - the withdraw pattern should be used.
seller.transfer(item.price-brokerFee-developerfee);
broker.transfer(brokerFee);
developer.transfer(developerfee);
buyinfo[index].completed = true;
emit IndividualItemReceived(buyinfo[index].buyer);
}
function getInfo() constant
public
returns (State, string, uint, string, uint, uint, address, address, bool)
{
return (state, item.name, item.price, item.detail, item.documents.length,
developerfee, seller, broker, bBrokerRequired);
}
function getBalance() constant
public
returns (uint256)
{
return address(this).balance;
}
function getFileAt(uint index)
public
constant returns(uint, bytes32, string, string, FileState)
{
return (index,
item.documents[index].purpose,
item.documents[index].name,
item.documents[index].ipfshash,
item.documents[index].state);
}
}
|
Abort the purchase and reclaim the ether. Can only be called by the seller before the contract is locked. validated = false;
|
function abort()
public
onlySeller
{
returnMoneyToBuyers();
emit AbortedBySeller();
seller.transfer(address(this).balance);
}
| 1,257,578 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./PegStabilityModule.sol";
/// @notice ETH PSM that allows separate pausing of mint and redeem
/// by the guardian and governor
contract MintRedeemPausePSM is PegStabilityModule {
/// @notice boolean switch that indicates whether redemptions are paused
bool public redeemPaused;
/// @notice event that is emitted when redemptions are paused
event RedemptionsPaused(address account);
/// @notice event that is emitted when redemptions are unpaused
event RedemptionsUnpaused(address account);
constructor(
OracleParams memory params,
uint256 _mintFeeBasisPoints,
uint256 _redeemFeeBasisPoints,
uint256 _reservesThreshold,
uint256 _feiLimitPerSecond,
uint256 _mintingBufferCap,
IERC20 _underlyingToken,
IPCVDeposit _surplusTarget
) PegStabilityModule(
params,
_mintFeeBasisPoints,
_redeemFeeBasisPoints,
_reservesThreshold,
_feiLimitPerSecond,
_mintingBufferCap,
_underlyingToken,
_surplusTarget
) {}
/// @notice modifier that allows execution when redemptions are not paused
modifier whileRedemptionsNotPaused {
require(!redeemPaused, "EthPSM: Redeem paused");
_;
}
/// @notice modifier that allows execution when redemptions are paused
modifier whileRedemptionsPaused {
require(redeemPaused, "EthPSM: Redeem not paused");
_;
}
/// @notice set secondary pausable methods to paused
function pauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsNotPaused {
redeemPaused = true;
emit RedemptionsPaused(msg.sender);
}
/// @notice set secondary pausable methods to unpaused
function unpauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsPaused {
redeemPaused = false;
emit RedemptionsUnpaused(msg.sender);
}
/// @notice override redeem function that allows secondary pausing
function redeem(
address to,
uint256 amountFeiIn,
uint256 minAmountOut
) external override nonReentrant whileRedemptionsNotPaused returns (uint256 amountOut) {
amountOut = _redeem(to, amountFeiIn, minAmountOut);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./../pcv/PCVDeposit.sol";
import "./../fei/minter/RateLimitedMinter.sol";
import "./IPegStabilityModule.sol";
import "./../refs/OracleRef.sol";
import "../Constants.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract PegStabilityModule is IPegStabilityModule, RateLimitedMinter, OracleRef, PCVDeposit, ReentrancyGuard {
using Decimal for Decimal.D256;
using SafeCast for *;
using SafeERC20 for IERC20;
/// @notice the fee in basis points for selling asset into FEI
uint256 public override mintFeeBasisPoints;
/// @notice the fee in basis points for buying the asset for FEI
uint256 public override redeemFeeBasisPoints;
/// @notice the amount of reserves to be held for redemptions
uint256 public override reservesThreshold;
/// @notice the PCV deposit target
IPCVDeposit public override surplusTarget;
/// @notice the token this PSM will exchange for FEI
/// This token will be set to WETH9 if the bonding curve accepts eth
IERC20 public immutable override underlyingToken;
/// @notice the max mint and redeem fee in basis points
/// Governance can change this fee
uint256 public override MAX_FEE = 300;
/// @notice struct for passing constructor parameters related to OracleRef
struct OracleParams {
address coreAddress;
address oracleAddress;
address backupOracle;
int256 decimalsNormalizer;
bool doInvert;
}
/// @notice constructor
/// @param params PSM constructor parameter struct
constructor(
OracleParams memory params,
uint256 _mintFeeBasisPoints,
uint256 _redeemFeeBasisPoints,
uint256 _reservesThreshold,
uint256 _feiLimitPerSecond,
uint256 _mintingBufferCap,
IERC20 _underlyingToken,
IPCVDeposit _surplusTarget
)
OracleRef(params.coreAddress, params.oracleAddress, params.backupOracle, params.decimalsNormalizer, params.doInvert)
/// rate limited minter passes false as the last param as there can be no partial mints
RateLimitedMinter(_feiLimitPerSecond, _mintingBufferCap, false)
{
underlyingToken = _underlyingToken;
_setReservesThreshold(_reservesThreshold);
_setMintFee(_mintFeeBasisPoints);
_setRedeemFee(_redeemFeeBasisPoints);
_setSurplusTarget(_surplusTarget);
_setContractAdminRole(keccak256("PSM_ADMIN_ROLE"));
}
/// @notice withdraw assets from PSM to an external address
function withdraw(address to, uint256 amount) external override virtual onlyPCVController {
_withdrawERC20(address(underlyingToken), to, amount);
}
/// @notice set the mint fee vs oracle price in basis point terms
function setMintFee(uint256 newMintFeeBasisPoints) external override onlyGovernorOrAdmin {
_setMintFee(newMintFeeBasisPoints);
}
/// @notice set the redemption fee vs oracle price in basis point terms
function setRedeemFee(uint256 newRedeemFeeBasisPoints) external override onlyGovernorOrAdmin {
_setRedeemFee(newRedeemFeeBasisPoints);
}
/// @notice set the ideal amount of reserves for the contract to hold for redemptions
function setReservesThreshold(uint256 newReservesThreshold) external override onlyGovernorOrAdmin {
_setReservesThreshold(newReservesThreshold);
}
/// @notice set the target for sending surplus reserves
function setSurplusTarget(IPCVDeposit newTarget) external override onlyGovernorOrAdmin {
_setSurplusTarget(newTarget);
}
/// @notice set the mint fee vs oracle price in basis point terms
function _setMintFee(uint256 newMintFeeBasisPoints) internal {
require(newMintFeeBasisPoints <= MAX_FEE, "PegStabilityModule: Mint fee exceeds max fee");
uint256 _oldMintFee = mintFeeBasisPoints;
mintFeeBasisPoints = newMintFeeBasisPoints;
emit MintFeeUpdate(_oldMintFee, newMintFeeBasisPoints);
}
/// @notice internal helper function to set the redemption fee
function _setRedeemFee(uint256 newRedeemFeeBasisPoints) internal {
require(newRedeemFeeBasisPoints <= MAX_FEE, "PegStabilityModule: Redeem fee exceeds max fee");
uint256 _oldRedeemFee = redeemFeeBasisPoints;
redeemFeeBasisPoints = newRedeemFeeBasisPoints;
emit RedeemFeeUpdate(_oldRedeemFee, newRedeemFeeBasisPoints);
}
/// @notice helper function to set reserves threshold
function _setReservesThreshold(uint256 newReservesThreshold) internal {
require(newReservesThreshold > 0, "PegStabilityModule: Invalid new reserves threshold");
uint256 oldReservesThreshold = reservesThreshold;
reservesThreshold = newReservesThreshold;
emit ReservesThresholdUpdate(oldReservesThreshold, newReservesThreshold);
}
/// @notice helper function to set the surplus target
function _setSurplusTarget(IPCVDeposit newSurplusTarget) internal {
require(address(newSurplusTarget) != address(0), "PegStabilityModule: Invalid new surplus target");
IPCVDeposit oldTarget = surplusTarget;
surplusTarget = newSurplusTarget;
emit SurplusTargetUpdate(oldTarget, newSurplusTarget);
}
// ----------- Public State Changing API -----------
/// @notice send any surplus reserves to the PCV allocation
function allocateSurplus() external override {
int256 currentSurplus = reservesSurplus();
require(currentSurplus > 0, "PegStabilityModule: No surplus to allocate");
_allocate(currentSurplus.toUint256());
}
/// @notice function to receive ERC20 tokens from external contracts
function deposit() external override {
int256 currentSurplus = reservesSurplus();
if (currentSurplus > 0) {
_allocate(currentSurplus.toUint256());
}
}
/// @notice internal helper method to redeem fei in exchange for an external asset
function _redeem(
address to,
uint256 amountFeiIn,
uint256 minAmountOut
) internal virtual returns(uint256 amountOut) {
updateOracle();
amountOut = _getRedeemAmountOut(amountFeiIn);
require(amountOut >= minAmountOut, "PegStabilityModule: Redeem not enough out");
IERC20(fei()).safeTransferFrom(msg.sender, address(this), amountFeiIn);
_transfer(to, amountOut);
emit Redeem(to, amountFeiIn, amountOut);
}
/// @notice internal helper method to mint fei in exchange for an external asset
function _mint(
address to,
uint256 amountIn,
uint256 minAmountOut
) internal virtual returns(uint256 amountFeiOut) {
updateOracle();
amountFeiOut = _getMintAmountOut(amountIn);
require(amountFeiOut >= minAmountOut, "PegStabilityModule: Mint not enough out");
_transferFrom(msg.sender, address(this), amountIn);
uint256 amountFeiToTransfer = Math.min(fei().balanceOf(address(this)), amountFeiOut);
uint256 amountFeiToMint = amountFeiOut - amountFeiToTransfer;
IERC20(fei()).safeTransfer(to, amountFeiToTransfer);
if (amountFeiToMint > 0) {
_mintFei(to, amountFeiToMint);
}
emit Mint(to, amountIn, amountFeiOut);
}
/// @notice function to redeem FEI for an underlying asset
/// We do not burn Fei; this allows the contract's balance of Fei to be used before the buffer is used
/// In practice, this helps prevent artificial cycling of mint-burn cycles and prevents a griefing vector.
function redeem(
address to,
uint256 amountFeiIn,
uint256 minAmountOut
) external virtual override nonReentrant whenNotPaused returns (uint256 amountOut) {
amountOut = _redeem(to, amountFeiIn, minAmountOut);
}
/// @notice function to buy FEI for an underlying asset
/// We first transfer any contract-owned fei, then mint the remaining if necessary
function mint(
address to,
uint256 amountIn,
uint256 minAmountOut
) external virtual override nonReentrant whenNotPaused returns (uint256 amountFeiOut) {
amountFeiOut = _mint(to, amountIn, minAmountOut);
}
// ----------- Public View-Only API ----------
/// @notice calculate the amount of FEI out for a given `amountIn` of underlying
/// First get oracle price of token
/// Then figure out how many dollars that amount in is worth by multiplying price * amount.
/// ensure decimals are normalized if on underlying they are not 18
function getMintAmountOut(uint256 amountIn) public override view returns (uint256 amountFeiOut) {
amountFeiOut = _getMintAmountOut(amountIn);
}
/// @notice calculate the amount of underlying out for a given `amountFeiIn` of FEI
/// First get oracle price of token
/// Then figure out how many dollars that amount in is worth by multiplying price * amount.
/// ensure decimals are normalized if on underlying they are not 18
function getRedeemAmountOut(uint256 amountFeiIn) public override view returns (uint256 amountTokenOut) {
amountTokenOut = _getRedeemAmountOut(amountFeiIn);
}
/// @notice the maximum mint amount out
function getMaxMintAmountOut() external override view returns (uint256) {
return fei().balanceOf(address(this)) + buffer();
}
/// @notice a flag for whether the current balance is above (true) or below (false) the reservesThreshold
function hasSurplus() external override view returns (bool) {
return balance() > reservesThreshold;
}
/// @notice an integer representing the positive surplus or negative deficit of contract balance vs reservesThreshold
function reservesSurplus() public override view returns (int256) {
return balance().toInt256() - reservesThreshold.toInt256();
}
/// @notice function from PCVDeposit that must be overriden
function balance() public view override virtual returns(uint256) {
return underlyingToken.balanceOf(address(this));
}
/// @notice returns address of token this contracts balance is reported in
function balanceReportedIn() external view override returns (address) {
return address(underlyingToken);
}
/// @notice override default behavior of not checking fei balance
function resistantBalanceAndFei() public view override returns(uint256, uint256) {
return (balance(), feiBalance());
}
// ----------- Internal Methods -----------
/// @notice helper function to get mint amount out based on current market prices
/// @dev will revert if price is outside of bounds and bounded PSM is being used
function _getMintAmountOut(uint256 amountIn) private view returns (uint256 amountFeiOut) {
Decimal.D256 memory price = readOracle();
_validatePriceRange(price);
Decimal.D256 memory adjustedAmountIn = price.mul(amountIn);
amountFeiOut = adjustedAmountIn
.mul(Constants.BASIS_POINTS_GRANULARITY - mintFeeBasisPoints)
.div(Constants.BASIS_POINTS_GRANULARITY)
.asUint256();
}
/// @notice helper function to get redeem amount out based on current market prices
/// @dev will revert if price is outside of bounds and bounded PSM is being used
function _getRedeemAmountOut(uint256 amountFeiIn) private view returns (uint256 amountTokenOut) {
Decimal.D256 memory price = readOracle();
_validatePriceRange(price);
/// get amount of dollars being provided
Decimal.D256 memory adjustedAmountIn = Decimal.from(
amountFeiIn * (Constants.BASIS_POINTS_GRANULARITY - redeemFeeBasisPoints) / Constants.BASIS_POINTS_GRANULARITY
);
/// now turn the dollars into the underlying token amounts
/// dollars / price = how much token to pay out
amountTokenOut = adjustedAmountIn.div(price).asUint256();
}
/// @notice Allocates a portion of escrowed PCV to a target PCV deposit
function _allocate(uint256 amount) internal {
_transfer(address(surplusTarget), amount);
surplusTarget.deposit();
emit AllocateSurplus(msg.sender, amount);
}
/// @notice transfer ERC20 token
function _transfer(address to, uint256 amount) internal {
SafeERC20.safeTransfer(underlyingToken, to, amount);
}
/// @notice transfer assets from user to this contract
function _transferFrom(address from, address to, uint256 amount) internal {
SafeERC20.safeTransferFrom(underlyingToken, from, to, amount);
}
/// @notice mint amount of FEI to the specified user on a rate limit
function _mintFei(address to, uint256 amount) internal override(CoreRef, RateLimitedMinter) {
super._mintFei(to, amount);
}
// ----------- Hooks -----------
/// @notice overriden function in the bounded PSM
function _validatePriceRange(Decimal.D256 memory price) internal view virtual {}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "./IPCVDeposit.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller
/// @author Fei Protocol
abstract contract PCVDeposit is IPCVDeposit, CoreRef {
using SafeERC20 for IERC20;
/// @notice withdraw ERC20 from the contract
/// @param token address of the ERC20 to send
/// @param to address destination of the ERC20
/// @param amount quantity of ERC20 to send
function withdrawERC20(
address token,
address to,
uint256 amount
) public virtual override onlyPCVController {
_withdrawERC20(token, to, amount);
}
function _withdrawERC20(
address token,
address to,
uint256 amount
) internal {
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(msg.sender, token, to, amount);
}
/// @notice withdraw ETH from the contract
/// @param to address to send ETH
/// @param amountOut amount of ETH to send
function withdrawETH(address payable to, uint256 amountOut) external virtual override onlyPCVController {
Address.sendValue(to, amountOut);
emit WithdrawETH(msg.sender, to, amountOut);
}
function balance() public view virtual override returns(uint256);
function resistantBalanceAndFei() public view virtual override returns(uint256, uint256) {
return (balance(), 0);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice a role used with a subset of governor permissions for this contract only
bytes32 public override CONTRACT_ADMIN_ROLE;
/// @notice boolean to check whether or not the contract has been initialized.
/// cannot be initialized twice.
bool private _initialized;
constructor(address coreAddress) {
_initialize(coreAddress);
}
/// @notice CoreRef constructor
/// @param coreAddress Fei Core to reference
function _initialize(address coreAddress) internal {
require(!_initialized, "CoreRef: already initialized");
_initialized = true;
_core = ICore(coreAddress);
_setContractAdminRole(_core.GOVERN_ROLE());
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernorOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not a governor or contract admin"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier isGovernorOrGuardianOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not governor or guardian or admin");
_;
}
modifier onlyFei() {
require(msg.sender == address(fei()), "CoreRef: Caller is not FEI");
_;
}
/// @notice set new Core reference address
/// @param newCore the new core address
function setCore(address newCore) external override onlyGovernor {
require(newCore != address(0), "CoreRef: zero address");
address oldCore = address(_core);
_core = ICore(newCore);
emit CoreUpdate(oldCore, newCore);
}
/// @notice sets a new admin role for this contract
function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor {
_setContractAdminRole(newContractAdminRole);
}
/// @notice returns whether a given address has the admin role for this contract
function isContractAdmin(address _admin) public view override returns (bool) {
return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _core.fei();
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20) {
return _core.tribe();
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return fei().balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return tribe().balanceOf(address(this));
}
function _burnFeiHeld() internal {
fei().burn(feiBalance());
}
function _mintFei(address to, uint256 amount) internal virtual {
if (amount != 0) {
fei().mint(to, amount);
}
}
function _setContractAdminRole(bytes32 newContractAdminRole) internal {
bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE;
CONTRACT_ADMIN_ROLE = newContractAdminRole;
emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed oldCore, address indexed newCore);
event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole);
// ----------- Governor only state changing api -----------
function setCore(address newCore) external;
function setContractAdminRole(bytes32 newContractAdminRole) external;
// ----------- Governor or Guardian only state changing api -----------
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
function CONTRACT_ADMIN_ROLE() external view returns (bytes32);
function isContractAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPermissions.sol";
import "../fei/IFei.sol";
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event FeiUpdate(address indexed _fei);
event TribeUpdate(address indexed _tribe);
event GenesisGroupUpdate(address indexed _genesisGroup);
event TribeAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setFei(address token) external;
function setTribe(address token) external;
function allocateTribe(address to, uint256 amount) external;
// ----------- Getters -----------
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./IPermissionsRead.sol";
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions is IAccessControl, IPermissionsRead {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function GUARDIAN_ROLE() external view returns (bytes32);
function GOVERN_ROLE() external view returns (bytes32);
function BURNER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function PCV_CONTROLLER_ROLE() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title Permissions Read interface
/// @author Fei Protocol
interface IPermissionsRead {
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IFei is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPCVDepositBalances.sol";
/// @title a PCV Deposit interface
/// @author Fei Protocol
interface IPCVDeposit is IPCVDepositBalances {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
event WithdrawETH(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external;
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function withdrawERC20(address token, address to, uint256 amount) external;
function withdrawETH(address payable to, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title a PCV Deposit interface for only balance getters
/// @author Fei Protocol
interface IPCVDepositBalances {
// ----------- Getters -----------
/// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn
function balance() external view returns (uint256);
/// @notice gets the token address in which this deposit returns its balance
function balanceReportedIn() external view returns (address);
/// @notice gets the resistant token balance and protocol owned fei of this deposit
function resistantBalanceAndFei() external view returns (uint256, uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../../utils/RateLimited.sol";
/// @title abstract contract for putting a rate limit on how fast a contract can mint FEI
/// @author Fei Protocol
abstract contract RateLimitedMinter is RateLimited {
uint256 private constant MAX_FEI_LIMIT_PER_SECOND = 10_000e18; // 10000 FEI/s or ~860m FEI/day
constructor(
uint256 _feiLimitPerSecond,
uint256 _mintingBufferCap,
bool _doPartialMint
)
RateLimited(MAX_FEI_LIMIT_PER_SECOND, _feiLimitPerSecond, _mintingBufferCap, _doPartialMint)
{}
/// @notice override the FEI minting behavior to enforce a rate limit
function _mintFei(address to, uint256 amount) internal virtual override {
uint256 mintAmount = _depleteBuffer(amount);
super._mintFei(to, mintAmount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @title abstract contract for putting a rate limit on how fast a contract can perform an action e.g. Minting
/// @author Fei Protocol
abstract contract RateLimited is CoreRef {
/// @notice maximum rate limit per second governance can set for this contract
uint256 public immutable MAX_RATE_LIMIT_PER_SECOND;
/// @notice the rate per second for this contract
uint256 public rateLimitPerSecond;
/// @notice the last time the buffer was used by the contract
uint256 public lastBufferUsedTime;
/// @notice the cap of the buffer that can be used at once
uint256 public bufferCap;
/// @notice a flag for whether to allow partial actions to complete if the buffer is less than amount
bool public doPartialAction;
/// @notice the buffer at the timestamp of lastBufferUsedTime
uint256 private _bufferStored;
event BufferUsed(uint256 amountUsed, uint256 bufferRemaining);
event BufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap);
event RateLimitPerSecondUpdate(uint256 oldRateLimitPerSecond, uint256 newRateLimitPerSecond);
constructor(uint256 _maxRateLimitPerSecond, uint256 _rateLimitPerSecond, uint256 _bufferCap, bool _doPartialAction) {
lastBufferUsedTime = block.timestamp;
_setBufferCap(_bufferCap);
_bufferStored = _bufferCap;
require(_rateLimitPerSecond <= _maxRateLimitPerSecond, "RateLimited: rateLimitPerSecond too high");
_setRateLimitPerSecond(_rateLimitPerSecond);
MAX_RATE_LIMIT_PER_SECOND = _maxRateLimitPerSecond;
doPartialAction = _doPartialAction;
}
/// @notice set the rate limit per second
function setRateLimitPerSecond(uint256 newRateLimitPerSecond) external virtual onlyGovernorOrAdmin {
require(newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND, "RateLimited: rateLimitPerSecond too high");
_updateBufferStored();
_setRateLimitPerSecond(newRateLimitPerSecond);
}
/// @notice set the buffer cap
function setBufferCap(uint256 newBufferCap) external virtual onlyGovernorOrAdmin {
_setBufferCap(newBufferCap);
}
/// @notice the amount of action used before hitting limit
/// @dev replenishes at rateLimitPerSecond per second up to bufferCap
function buffer() public view returns(uint256) {
uint256 elapsed = block.timestamp - lastBufferUsedTime;
return Math.min(_bufferStored + (rateLimitPerSecond * elapsed), bufferCap);
}
/**
@notice the method that enforces the rate limit. Decreases buffer by "amount".
If buffer is <= amount either
1. Does a partial mint by the amount remaining in the buffer or
2. Reverts
Depending on whether doPartialAction is true or false
*/
function _depleteBuffer(uint256 amount) internal returns(uint256) {
uint256 newBuffer = buffer();
uint256 usedAmount = amount;
if (doPartialAction && usedAmount > newBuffer) {
usedAmount = newBuffer;
}
require(newBuffer != 0, "RateLimited: no rate limit buffer");
require(usedAmount <= newBuffer, "RateLimited: rate limit hit");
_bufferStored = newBuffer - usedAmount;
lastBufferUsedTime = block.timestamp;
emit BufferUsed(usedAmount, _bufferStored);
return usedAmount;
}
function _setRateLimitPerSecond(uint256 newRateLimitPerSecond) internal {
uint256 oldRateLimitPerSecond = rateLimitPerSecond;
rateLimitPerSecond = newRateLimitPerSecond;
emit RateLimitPerSecondUpdate(oldRateLimitPerSecond, newRateLimitPerSecond);
}
function _setBufferCap(uint256 newBufferCap) internal {
_updateBufferStored();
uint256 oldBufferCap = bufferCap;
bufferCap = newBufferCap;
emit BufferCapUpdate(oldBufferCap, newBufferCap);
}
function _resetBuffer() internal {
_bufferStored = bufferCap;
}
function _updateBufferStored() internal {
_bufferStored = buffer();
lastBufferUsedTime = block.timestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../pcv/IPCVDeposit.sol";
/**
* @title Fei Peg Stability Module
* @author Fei Protocol
* @notice The Fei PSM is a contract which holds a reserve of assets in order to exchange FEI at $1 of underlying assets with a fee.
* `mint()` - buy FEI for $1 of underlying tokens
* `redeem()` - sell FEI back for $1 of the same
*
* The contract has a reservesThreshold() of underlying meant to stand ready for redemptions. Any surplus reserves can be sent into the PCV using `allocateSurplus()`
*
* The contract is a
* PCVDeposit - to track reserves
* OracleRef - to determine price of underlying, and
* RateLimitedMinter - to stop infinite mints and related issues (but this is in the implementation due to inheritance-linearization difficulties)
*
* Inspired by MakerDAO PSM, code written without reference
*/
interface IPegStabilityModule {
// ----------- Public State Changing API -----------
/// @notice mint `amountFeiOut` FEI to address `to` for `amountIn` underlying tokens
/// @dev see getMintAmountOut() to pre-calculate amount out
function mint(address to, uint256 amountIn, uint256 minAmountOut) external returns (uint256 amountFeiOut);
/// @notice redeem `amountFeiIn` FEI for `amountOut` underlying tokens and send to address `to`
/// @dev see getRedeemAmountOut() to pre-calculate amount out
function redeem(address to, uint256 amountFeiIn, uint256 minAmountOut) external returns (uint256 amountOut);
/// @notice send any surplus reserves to the PCV allocation
function allocateSurplus() external;
// ----------- Governor or Admin Only State Changing API -----------
/// @notice set the mint fee vs oracle price in basis point terms
function setMintFee(uint256 newMintFeeBasisPoints) external;
/// @notice set the redemption fee vs oracle price in basis point terms
function setRedeemFee(uint256 newRedeemFeeBasisPoints) external;
/// @notice set the ideal amount of reserves for the contract to hold for redemptions
function setReservesThreshold(uint256 newReservesThreshold) external;
/// @notice set the target for sending surplus reserves
function setSurplusTarget(IPCVDeposit newTarget) external;
// ----------- Getters -----------
/// @notice calculate the amount of FEI out for a given `amountIn` of underlying
function getMintAmountOut(uint256 amountIn) external view returns (uint256 amountFeiOut);
/// @notice calculate the amount of underlying out for a given `amountFeiIn` of FEI
function getRedeemAmountOut(uint256 amountFeiIn) external view returns (uint256 amountOut);
/// @notice the maximum mint amount out
function getMaxMintAmountOut() external view returns(uint256);
/// @notice a flag for whether the current balance is above (true) or below and equal (false) to the reservesThreshold
function hasSurplus() external view returns (bool);
/// @notice an integer representing the positive surplus or negative deficit of contract balance vs reservesThreshold
function reservesSurplus() external view returns (int256);
/// @notice the ideal amount of reserves for the contract to hold for redemptions
function reservesThreshold() external view returns (uint256);
/// @notice the mint fee vs oracle price in basis point terms
function mintFeeBasisPoints() external view returns (uint256);
/// @notice the redemption fee vs oracle price in basis point terms
function redeemFeeBasisPoints() external view returns (uint256);
/// @notice the underlying token exchanged for FEI
function underlyingToken() external view returns (IERC20);
/// @notice the PCV deposit target to send surplus reserves
function surplusTarget() external view returns (IPCVDeposit);
/// @notice the max mint and redeem fee in basis points
function MAX_FEE() external view returns (uint256);
// ----------- Events -----------
/// @notice event emitted when excess PCV is allocated
event AllocateSurplus(address indexed caller, uint256 amount);
/// @notice event emitted when a new max fee is set
event MaxFeeUpdate(uint256 oldMaxFee, uint256 newMaxFee);
/// @notice event emitted when a new mint fee is set
event MintFeeUpdate(uint256 oldMintFee, uint256 newMintFee);
/// @notice event emitted when a new redeem fee is set
event RedeemFeeUpdate(uint256 oldRedeemFee, uint256 newRedeemFee);
/// @notice event emitted when reservesThreshold is updated
event ReservesThresholdUpdate(uint256 oldReservesThreshold, uint256 newReservesThreshold);
/// @notice event emitted when surplus target is updated
event SurplusTargetUpdate(IPCVDeposit oldTarget, IPCVDeposit newTarget);
/// @notice event emitted upon a redemption
event Redeem(address to, uint256 amountFeiIn, uint256 amountAssetOut);
/// @notice event emitted when fei gets minted
event Mint(address to, uint256 amountIn, uint256 amountFeiOut);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IOracleRef.sol";
import "./CoreRef.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title Reference to an Oracle
/// @author Fei Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
using SafeCast for int256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice the backup oracle reference by the contract
IOracle public override backupOracle;
/// @notice number of decimals to scale oracle price by, i.e. multiplying by 10^(decimalsNormalizer)
int256 public override decimalsNormalizer;
bool public override doInvert;
/// @notice OracleRef constructor
/// @param _core Fei Core to reference
/// @param _oracle oracle to reference
/// @param _backupOracle backup oracle to reference
/// @param _decimalsNormalizer number of decimals to normalize the oracle feed if necessary
/// @param _doInvert invert the oracle price if this flag is on
constructor(address _core, address _oracle, address _backupOracle, int256 _decimalsNormalizer, bool _doInvert) CoreRef(_core) {
_setOracle(_oracle);
if (_backupOracle != address(0) && _backupOracle != _oracle) {
_setBackupOracle(_backupOracle);
}
_setDoInvert(_doInvert);
_setDecimalsNormalizer(_decimalsNormalizer);
}
/// @notice sets the referenced oracle
/// @param newOracle the new oracle to reference
function setOracle(address newOracle) external override onlyGovernor {
_setOracle(newOracle);
}
/// @notice sets the flag for whether to invert or not
/// @param newDoInvert the new flag for whether to invert
function setDoInvert(bool newDoInvert) external override onlyGovernor {
_setDoInvert(newDoInvert);
}
/// @notice sets the new decimalsNormalizer
/// @param newDecimalsNormalizer the new decimalsNormalizer
function setDecimalsNormalizer(int256 newDecimalsNormalizer) external override onlyGovernor {
_setDecimalsNormalizer(newDecimalsNormalizer);
}
/// @notice sets the referenced backup oracle
/// @param newBackupOracle the new backup oracle to reference
function setBackupOracle(address newBackupOracle) external override onlyGovernorOrAdmin {
_setBackupOracle(newBackupOracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per FEI
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice updates the referenced oracle
function updateOracle() public override {
oracle.update();
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as FEI per X with X being ETH, dollars, etc
function readOracle() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
if (!valid && address(backupOracle) != address(0)) {
(_peg, valid) = backupOracle.read();
}
require(valid, "OracleRef: oracle invalid");
// Scale the oracle price by token decimals delta if necessary
uint256 scalingFactor;
if (decimalsNormalizer < 0) {
scalingFactor = 10 ** (-1 * decimalsNormalizer).toUint256();
_peg = _peg.div(scalingFactor);
} else {
scalingFactor = 10 ** decimalsNormalizer.toUint256();
_peg = _peg.mul(scalingFactor);
}
// Invert the oracle price if necessary
if (doInvert) {
_peg = invert(_peg);
}
return _peg;
}
function _setOracle(address newOracle) internal {
require(newOracle != address(0), "OracleRef: zero address");
address oldOracle = address(oracle);
oracle = IOracle(newOracle);
emit OracleUpdate(oldOracle, newOracle);
}
// Supports zero address if no backup
function _setBackupOracle(address newBackupOracle) internal {
address oldBackupOracle = address(backupOracle);
backupOracle = IOracle(newBackupOracle);
emit BackupOracleUpdate(oldBackupOracle, newBackupOracle);
}
function _setDoInvert(bool newDoInvert) internal {
bool oldDoInvert = doInvert;
doInvert = newDoInvert;
if (oldDoInvert != newDoInvert) {
_setDecimalsNormalizer( -1 * decimalsNormalizer);
}
emit InvertUpdate(oldDoInvert, newDoInvert);
}
function _setDecimalsNormalizer(int256 newDecimalsNormalizer) internal {
int256 oldDecimalsNormalizer = decimalsNormalizer;
decimalsNormalizer = newDecimalsNormalizer;
emit DecimalsNormalizerUpdate(oldDecimalsNormalizer, newDecimalsNormalizer);
}
function _setDecimalsNormalizerFromToken(address token) internal {
int256 feiDecimals = 18;
int256 _decimalsNormalizer = feiDecimals - int256(uint256(IERC20Metadata(token).decimals()));
if (doInvert) {
_decimalsNormalizer = -1 * _decimalsNormalizer;
}
_setDecimalsNormalizer(_decimalsNormalizer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Fei Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed oldOracle, address indexed newOracle);
event InvertUpdate(bool oldDoInvert, bool newDoInvert);
event DecimalsNormalizerUpdate(int256 oldDecimalsNormalizer, int256 newDecimalsNormalizer);
event BackupOracleUpdate(address indexed oldBackupOracle, address indexed newBackupOracle);
// ----------- State changing API -----------
function updateOracle() external;
// ----------- Governor only state changing API -----------
function setOracle(address newOracle) external;
function setBackupOracle(address newBackupOracle) external;
function setDecimalsNormalizer(int256 newDecimalsNormalizer) external;
function setDoInvert(bool newDoInvert) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function backupOracle() external view returns (IOracle);
function doInvert() external view returns (bool);
function decimalsNormalizer() external view returns (int256);
function readOracle() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../external/Decimal.sol";
/// @title generic oracle interface for Fei Protocol
/// @author Fei Protocol
interface IOracle {
// ----------- Events -----------
event Update(uint256 _peg);
// ----------- State changing API -----------
function update() external;
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
function isOutdated() external view returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
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.8.4;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol";
library Constants {
/// @notice the denominator for basis points granularity (10,000)
uint256 public constant BASIS_POINTS_GRANULARITY = 10_000;
uint256 public constant ONE_YEAR = 365.25 days;
/// @notice WETH9 address
IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
/// @notice USD stand-in address
address public constant USD = 0x1111111111111111111111111111111111111111;
/// @notice Wei per ETH, i.e. 10**18
uint256 public constant ETH_GRANULARITY = 1e18;
/// @notice number of decimals in ETH, 18
uint256 public constant ETH_DECIMALS = 18;
}
// 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 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// 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 (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 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/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.
*/
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());
}
}
// 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 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* 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, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override onlyRole(getRoleAdmin(role)) {
_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 override onlyRole(getRoleAdmin(role)) {
_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 revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
}
// 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 (utils/math/Math.sol)
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
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 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} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
|
Fei Peg Stability Module Fei Protocol The Fei PSM is a contract which holds a reserve of assets in order to exchange FEI at $1 of underlying assets with a fee. `mint()` - buy FEI for $1 of underlying tokens `redeem()` - sell FEI back for $1 of the same The contract has a reservesThreshold() of underlying meant to stand ready for redemptions. Any surplus reserves can be sent into the PCV using `allocateSurplus()` The contract is a PCVDeposit - to track reserves OracleRef - to determine price of underlying, and RateLimitedMinter - to stop infinite mints and related issues (but this is in the implementation due to inheritance-linearization difficulties) Inspired by MakerDAO PSM, code written without reference/ ----------- Public State Changing API ----------- ----------- Governor or Admin Only State Changing API ----------- ----------- Getters ----------- ----------- Events -----------
|
interface IPegStabilityModule {
function mint(address to, uint256 amountIn, uint256 minAmountOut) external returns (uint256 amountFeiOut);
function redeem(address to, uint256 amountFeiIn, uint256 minAmountOut) external returns (uint256 amountOut);
function allocateSurplus() external;
function setMintFee(uint256 newMintFeeBasisPoints) external;
function setRedeemFee(uint256 newRedeemFeeBasisPoints) external;
function setReservesThreshold(uint256 newReservesThreshold) external;
function setSurplusTarget(IPCVDeposit newTarget) external;
function getMintAmountOut(uint256 amountIn) external view returns (uint256 amountFeiOut);
function getRedeemAmountOut(uint256 amountFeiIn) external view returns (uint256 amountOut);
function getMaxMintAmountOut() external view returns(uint256);
function hasSurplus() external view returns (bool);
function reservesSurplus() external view returns (int256);
function reservesThreshold() external view returns (uint256);
function mintFeeBasisPoints() external view returns (uint256);
function redeemFeeBasisPoints() external view returns (uint256);
function underlyingToken() external view returns (IERC20);
function surplusTarget() external view returns (IPCVDeposit);
function MAX_FEE() external view returns (uint256);
event AllocateSurplus(address indexed caller, uint256 amount);
event MaxFeeUpdate(uint256 oldMaxFee, uint256 newMaxFee);
event MintFeeUpdate(uint256 oldMintFee, uint256 newMintFee);
event RedeemFeeUpdate(uint256 oldRedeemFee, uint256 newRedeemFee);
event ReservesThresholdUpdate(uint256 oldReservesThreshold, uint256 newReservesThreshold);
event SurplusTargetUpdate(IPCVDeposit oldTarget, IPCVDeposit newTarget);
event Redeem(address to, uint256 amountFeiIn, uint256 amountAssetOut);
event Mint(address to, uint256 amountIn, uint256 amountFeiOut);
pragma solidity ^0.8.4;
}
| 292,375 |
/**
*Submitted for verification at Etherscan.io on 2022-03-15
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @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);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @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 whiteed 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 whiteed 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;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @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);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @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);
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @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);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @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);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @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;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @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 whiteed 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.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 {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @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);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @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 whites 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();
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @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 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 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.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_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(), "ERC721A: global index out of bounds");
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), "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");
}
function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
if (tokenCount == 0)
{
return tokenIds;
}
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) {
tokenIds[tokenIdsIdx] = i;
tokenIdsIdx++;
if (tokenIdsIdx == tokenCount) {
return tokenIds;
}
}
}
revert("ERC721A: unable to get walletOfOwner");
}
/**
* @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 virtual override {
_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 {
_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:
*
* - `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 > 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), "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 {}
}
contract Praverse is ERC721A, Ownable {
constructor() ERC721A("Praverse Pass", "PASS",50) {}
using SafeMath for uint256;
using Strings for uint256;
string private blindURI;
uint256 public constant BUY_LIMIT_PER_TX = 50;
uint256 public MAX_NFT_PUBLIC = 100;
uint256 public MAX_NFT = 100000;
uint256 public NFTPrice = 0; // O ETH - FREE MINT
bool public isActive;
bool public isPresaleActive;
bytes32 public root;
uint256 public WHITELIST_MAX_MINT = 1;
mapping(address => uint256) public whiteListClaimed;
/*
* Function setIsActive to activate/desactivate the smart contract
*/
function setIsActive(
bool _isActive
)
external
onlyOwner
{
isActive = _isActive;
}
/*
* Function setPresaleActive to activate/desactivate the whitelist presale
*/
function setPresaleActive(
bool _isActive
)
external
onlyOwner
{
isPresaleActive = _isActive;
}
/*
* Function to set Base and Blind URI
*/
function setURIs(
string memory _blindURI
)
external
onlyOwner
{
blindURI = _blindURI;
}
/*
* Function to set MAX NFT PUBLIC & MAX NFT
*/
function setMaxNft(uint256 _public,uint256 _total) external onlyOwner {
require(_public<_total ,"total must be > than public");
MAX_NFT_PUBLIC=_public;
MAX_NFT=_total;
}
/*
* Function to mint new NFTs during the public sale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFT(
uint256 _numOfTokens
)
public
payable
{
require(isActive, 'Contract is not active');
require(!isPresaleActive, 'Presale is still active');
require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit");
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whitelisted');
whiteListClaimed[msg.sender] += _numOfTokens;
_safeMint(msg.sender, _numOfTokens);
}
/*
* Function to mint new NFTs during the presale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFTDuringPresale(
uint256 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require(isActive, 'Sale is not active');
require(isPresaleActive, 'Whitelist is not active');
require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted");
require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted');
require(_numOfTokens <= WHITELIST_MAX_MINT, 'Cannot purchase this many tokens');
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whitelisted');
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
whiteListClaimed[msg.sender] += _numOfTokens;
_safeMint(msg.sender, _numOfTokens);
}
/*
* Function to mint NFTs for giveaway and partnerships
*/
function mintByOwner(
address _to
)
public
onlyOwner
{
require(totalSupply()+1 <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to, 1);
}
/*
* Function to mint all NFTs for giveaway and partnerships
*/
function mintMultipleByOwner(
address[] memory _to
)
public
onlyOwner
{
for(uint256 i = 0; i < _to.length; i++){
require(totalSupply()+1 <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to[i], 1);
}
}
/*
* Function to get token URI of given token ID
* URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC
*/
function tokenURI(
uint256 _tokenId
)
public
view
virtual
override
returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(blindURI));
}
// Set Root for whitelist to participate in presale
function setRootAndMax(uint256 _root,uint256 _max) onlyOwner() public {
root = bytes32(_root);
WHITELIST_MAX_MINT=_max;
}
// Verify MerkleProof
function verify(bytes32[] memory proof, bytes32 leaf) public view returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = sha256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = sha256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
|
Function setIsActive to activate/desactivate the smart contract/
|
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
{
isActive = _isActive;
}
| 7,647,575 |
pragma solidity 0.5.4;
library SafeMath {
uint256 constant internal MAX_UINT = 2 ** 256 - 1; // max uint256
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns(uint256) {
if (_a == 0) {
return 0;
}
require(MAX_UINT / _a >= _b);
return _a * _b;
}
/**
* @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);
return _a / _b;
}
/**
* @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);
return _a - _b;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns(uint256) {
require(MAX_UINT - _a >= _b);
return _a + _b;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) 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;
}
}
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() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract StandardToken {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @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) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns(uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(_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);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns(bool) {
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 decreaseApproval(address _spender, uint256 _subtractedValue) public returns(bool) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
totalSupply = totalSupply.sub(value);
balances[account] = balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 {
// 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);
}
}
contract BurnableToken is StandardToken {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract PausableToken is StandardToken, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
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);
}
function increaseApproval(address spender, uint256 addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(spender, addedValue);
}
function decreaseApproval(address spender, uint256 subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(spender, subtractedValue);
}
}
/**
* @title token
* @dev Standard template for ERC20 Token
*/
contract Token is PausableToken, BurnableToken {
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Constructor, to initialize the basic information of token
* @param _name The name of token
* @param _symbol The symbol of token
* @param _decimals The dicemals of token
* @param _INIT_TOTALSUPPLY The total supply of token
*/
constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _INIT_TOTALSUPPLY) public {
totalSupply = _INIT_TOTALSUPPLY * 10 ** uint256(_decimals);
balances[owner] = totalSupply; // Transfers all tokens to owner
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
/**
* @dev Interface of BDR contract
*/
interface BDRContract {
function tokenFallback(address _from, uint256 _value, bytes calldata _data) external;
function transfer(address _to, uint256 _value) external returns (bool);
function decimals() external returns (uint8);
}
/**
* @title IOAEX ENTITY TOKEN
*/
contract IOAEX is Token {
// The address of BDR contract
BDRContract public BDRInstance;
// The total amount of locked tokens at the specified address
mapping(address => uint256) public totalLockAmount;
// The released amount of the specified address
mapping(address => uint256) public releasedAmount;
//
mapping(address => timeAndAmount[]) public allocations;
// Stores the timestamp and the amount of tokens released each time
struct timeAndAmount {
uint256 releaseTime;
uint256 releaseAmount;
}
// events
event LockToken(address _beneficiary, uint256 totalLockAmount);
event ReleaseToken(address indexed user, uint256 releaseAmount, uint256 releaseTime);
event ExchangeBDR(address from, uint256 value);
event SetBDRContract(address BDRInstanceess);
/**
* @dev Throws if called by any account other than the BDR contract
*/
modifier onlyBDRContract() {
require(msg.sender == address(BDRInstance));
_;
}
/**
* @dev Constructor, to initialize the basic information of token
*/
constructor (string memory _name, string memory _symbol, uint8 _decimals, uint256 _INIT_TOTALSUPPLY) Token (_name, _symbol, _decimals, _INIT_TOTALSUPPLY) public {
}
/**
* @dev Sets the address of BDR contract
*/
function setBDRContract(address BDRAddress) public onlyOwner {
require(BDRAddress != address(0));
BDRInstance = BDRContract(BDRAddress);
emit SetBDRContract(BDRAddress);
}
/**
* @dev The owner can call this function to send tokens to the specified address, but these tokens are only available for more than the specified time
* @param _beneficiary The address to receive tokens
* @param _releaseTimes Array, the timestamp for releasing token
* @param _releaseAmount Array, the amount for releasing token
*/
function lockToken(address _beneficiary, uint256[] memory _releaseTimes, uint256[] memory _releaseAmount) public onlyOwner returns(bool) {
require(totalLockAmount[_beneficiary] == 0); // The beneficiary is not in any lock-plans at the current timestamp.
require(_beneficiary != address(0)); // The beneficiary cannot be an empty address
require(_releaseTimes.length == _releaseAmount.length); // These two lists are equal in length.
releasedAmount[_beneficiary] = 0;
for (uint256 i = 0; i < _releaseTimes.length; i++) {
totalLockAmount[_beneficiary] = totalLockAmount[_beneficiary].add(_releaseAmount[i]);
require(_releaseAmount[i] > 0); // The amount to release is greater than 0.
require(_releaseTimes[i] >= now); // Each release time is not lower than the current timestamp.
// Saves the lock-token information
allocations[_beneficiary].push(timeAndAmount(_releaseTimes[i], _releaseAmount[i]));
}
balances[owner] = balances[owner].sub(totalLockAmount[_beneficiary]); // Removes this part of the locked token from the owner
emit LockToken(_beneficiary, totalLockAmount[_beneficiary]);
return true;
}
/**
* Releases token
*/
function releaseToken() public returns (bool) {
release(msg.sender);
}
/**
* @dev The basic function of releasing token
*/
function release(address addr) internal {
require(totalLockAmount[addr] > 0); // The address has joined a lock-plan.
uint256 amount = releasableAmount(addr); // Gets the amount of release and updates the lock-plans data
// Unlocks token. Converting locked tokens into normal tokens
balances[addr] = balances[addr].add(amount);
// Updates the amount of released tokens.
releasedAmount[addr] = releasedAmount[addr].add(amount);
// If the token on this address has been completely released, clears the Record of locking token
if (releasedAmount[addr] == totalLockAmount[addr]) {
delete allocations[addr];
totalLockAmount[addr] = 0;
}
emit ReleaseToken(addr, amount, now);
}
/**
* @dev Gets the amount that can be released at current timestamps
* @param addr A specified address.
*/
function releasableAmount(address addr) public view returns (uint256) {
if(totalLockAmount[addr] == 0) {
return 0;
}
uint256 num = 0;
for (uint256 i = 0; i < allocations[addr].length; i++) {
if (now >= allocations[addr][i].releaseTime) { // Determines the releasable stage under the current timestamp.
num = num.add(allocations[addr][i].releaseAmount);
}
}
return num.sub(releasedAmount[addr]); // the amount of current timestamps that can be released - the released amount.
}
/**
* @dev Gets the amount of tokens that are still locked at current timestamp.
* @param addr A specified address.
*/
function balanceOfLocked(address addr) public view returns(uint256) {
if (totalLockAmount[addr] > releasedAmount[addr]) {
return totalLockAmount[addr].sub(releasedAmount[addr]);
} else {
return 0;
}
}
/**
* @dev Transfers token to a specified address.
* If 'msg.sender' has releasable tokens, this part of the token will be released automatically.
* If the target address of transferring is BDR contract, the operation of changing BDR tokens will be executed.
* @param to The target address of transfer, which may be the BDR contract
* @param value The amount of tokens transferred
*/
function transfer(address to, uint value) public returns (bool) {
if(releasableAmount(msg.sender) > 0) {
release(msg.sender); // Calls 'release' function
}
super.transfer(to, value); // Transfers tokens to address 'to'
if(to == address(BDRInstance)) {
BDRInstance.tokenFallback(msg.sender, value, bytes("")); // Calls 'tokenFallback' function in BDR contract to exchange tokens
emit ExchangeBDR(msg.sender, value);
}
return true;
}
/**
* @dev Transfers tokens from one address to another.
* If 'from' has releasable tokens, this part of the token will be released automatically.
* If the target address of transferring is BDR contract, the operation of changing BDR tokens will be executed.
* @param from The address which you want to send tokens from
* @param to The address which you want to transfer to
* @param value The amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint value) public returns (bool) {
if(releasableAmount(from) > 0) {
release(from); // Calls the 'release' function
}
super.transferFrom(from, to, value); // Transfers token to address 'to'
if(to == address(BDRInstance)) {
BDRInstance.tokenFallback(from, value, bytes("")); // Calls 'tokenFallback' function in BDR contract to exchange tokens
emit ExchangeBDR(from, value);
}
return true;
}
/**
* @dev Function that is called by the BDR contract to exchange 'Abc' tokens
*/
function tokenFallback(address from, uint256 value, bytes calldata) external onlyBDRContract {
require(from != address(0));
require(value != uint256(0));
uint256 AbcValue = value.mul(10**uint256(decimals)).div(10**uint256(BDRInstance.decimals())); // Calculates the number of 'Abc' tokens that can be exchanged
require(AbcValue <= balances[address(BDRInstance)]);
balances[address(BDRInstance)] = balances[address(BDRInstance)].sub(AbcValue);
balances[from] = balances[from].add(AbcValue);
emit Transfer(owner, from, AbcValue);
}
}
|
Transfers tokens from one address to another. If 'from' has releasable tokens, this part of the token will be released automatically. If the target address of transferring is BDR contract, the operation of changing BDR tokens will be executed. from The address which you want to send tokens from to The address which you want to transfer to value The amount of tokens to be transferred/
|
function transferFrom(address from, address to, uint value) public returns (bool) {
if(releasableAmount(from) > 0) {
}
if(to == address(BDRInstance)) {
emit ExchangeBDR(from, value);
}
return true;
}
| 7,220,030 |
./partial_match/62320/0xd536b521b542D05533b0AC8fA3018aBe9e03DE1d/sources/redstone-oracles-monorepo-789f66c/packages/on-chain-relayer/contracts/core/RedstoneAdapterBase.sol
|
Reverts if the proposed timestamp of data packages it too old or too new comparing to the current block timestamp dataPackagesTimestamp The proposed timestamp (usually in milliseconds)/
|
function validateDataPackagesTimestampOnce(uint256 dataPackagesTimestamp) public view virtual {
uint256 receivedTimestampSeconds = dataPackagesTimestamp / 1000;
(uint256 maxDataAheadSeconds, uint256 maxDataDelaySeconds) = getAllowedTimestampDiffsInSeconds();
uint256 blockTimestamp = getBlockTimestamp();
if (blockTimestamp < receivedTimestampSeconds) {
if ((receivedTimestampSeconds - blockTimestamp) > maxDataAheadSeconds) {
revert RedstoneDefaultsLib.TimestampFromTooLongFuture(receivedTimestampSeconds, blockTimestamp);
}
revert RedstoneDefaultsLib.TimestampIsTooOld(receivedTimestampSeconds, blockTimestamp);
}
}
| 11,034,319 |
pragma solidity 0.5.10;
contract Context {
constructor () internal { }
function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this;
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(a, b, "SafeMath: subtraction overflow");
}
function SUB97(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 MUL111(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 DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV358(a, b, "SafeMath: division by zero");
}
function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD464(a, b, "SafeMath: modulo by zero");
}
function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
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 TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER927(_MSGSENDER793(), recipient, amount);
return true;
}
function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, amount);
return true;
}
function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER927(sender, recipient, amount);
_APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue));
return true;
}
function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER927(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].SUB97(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD803(amount);
emit TRANSFER432(sender, recipient, amount);
}
function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD803(amount);
_balances[account] = _balances[account].ADD803(amount);
emit TRANSFER432(address(0), account, amount);
}
function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB97(amount);
emit TRANSFER432(account, address(0), amount);
}
function _APPROVE171(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 APPROVAL431(owner, spender, amount);
}
function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN826(account, amount);
_APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance"));
}
}
library BytesLib {
function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
bytes memory tempBytes;
assembly {
tempBytes := mload(0x40)
let length := mload(_preBytes)
mstore(tempBytes, length)
let mc := add(tempBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
mc := end
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31)
))
}
return tempBytes;
}
function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING
assembly {
let fslot := sload(_preBytes_slot)
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
sstore(
_preBytes_slot,
add(
fslot,
add(
mul(
div(
mload(add(_postBytes, 0x20)),
exp(0x100, sub(32, mlength))
),
exp(0x100, sub(32, newlength))
),
mul(mlength, 2)
)
)
)
}
case 1 {
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + _length), "Slice out of bounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
tempBytes := mload(0x40)
let lengthmod := and(_length, 31)
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
mstore(0x40, and(add(mc, 31), not(31)))
}
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 20), "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 32), "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let length := mload(_preBytes)
switch eq(length, mload(_postBytes))
case 1 {
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
if iszero(eq(mload(mc), mload(cc))) {
success := 0
cb := 0
}
}
}
default {
success := 0
}
}
return success;
}
function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let fslot := sload(_preBytes_slot)
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
switch eq(slength, mlength)
case 1 {
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
success := 0
}
}
default {
let cb := 1
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
success := 0
cb := 0
}
}
}
}
}
default {
success := 0
}
}
return success;
}
function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING
bytes memory tempEmptyStringTest = bytes(_source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
}
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING
uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING
uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING
function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING
if (uint8(_flag[0]) == 0xff) {
return 8;
}
if (uint8(_flag[0]) == 0xfe) {
return 4;
}
if (uint8(_flag[0]) == 0xfd) {
return 2;
}
return 0;
}
function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
bytes memory _newValue = new bytes(_b.length);
for (uint i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 _number;
for (uint i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _start = _b.length.SUB97(_num);
return _b.SLICE479(_start, _num);
}
function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571();
}
function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i ++) {
_remaining = _vin.SLICE479(_offset, _vin.length - _offset);
_len = DETERMINEINPUTLENGTH677(_remaining);
_offset = _offset + _len;
}
_remaining = _vin.SLICE479(_offset, _vin.length - _offset);
_len = DETERMINEINPUTLENGTH677(_remaining);
return _vin.SLICE479(_offset, _len);
}
function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING
return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00");
}
function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4);
}
function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input);
bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence);
return uint32(BYTESTOUINT790(_beSequence));
}
function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen);
}
function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING
bytes memory _varIntTag = _input.SLICE479(36, 1);
uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag);
uint256 _len;
if (_varIntDataLen == 0) {
_len = uint8(_varIntTag[0]);
} else {
_len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen)));
}
return (_varIntDataLen, _len);
}
function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(37, 4);
}
function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input);
bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence);
return uint32(BYTESTOUINT790(_inputeSequence));
}
function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(0, 36);
}
function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return _input.SLICE479(0, 32).TOBYTES32571();
}
function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input));
bytes memory _beId = REVERSEENDIANNESS18(_leId);
return _beId.TOBYTES32571();
}
function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(32, 4);
}
function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leIndex = EXTRACTTXINDEXLE408(_input);
bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex);
return uint32(BYTESTOUINT790(_beIndex));
}
function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint8 _len = uint8(_output.SLICE479(8, 1)[0]);
require(_len < 0xfd, "Multi-byte VarInts not supported");
return _len + 8 + 1;
}
function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i ++) {
_remaining = _vout.SLICE479(_offset, _vout.length - _offset);
_len = DETERMINEOUTPUTLENGTH588(_remaining);
_offset = _offset + _len;
}
_remaining = _vout.SLICE479(_offset, _vout.length - _offset);
_len = DETERMINEOUTPUTLENGTH588(_remaining);
return _vout.SLICE479(_offset, _len);
}
function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _output.SLICE479(8, 1);
}
function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _output.SLICE479(0, 8);
}
function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING
bytes memory _leValue = EXTRACTVALUELE862(_output);
bytes memory _beValue = REVERSEENDIANNESS18(_leValue);
return uint64(BYTESTOUINT790(_beValue));
}
function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) {
return hex"";
}
bytes memory _dataLen = _output.SLICE479(10, 1);
return _output.SLICE479(11, BYTESTOUINT790(_dataLen));
}
function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
if (uint8(_output.SLICE479(9, 1)[0]) == 0) {
uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2;
if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) {
return hex"";
}
return _output.SLICE479(11, _len);
} else {
bytes32 _tag = keccak256(_output.SLICE479(8, 3));
if (_tag == keccak256(hex"1976a9")) {
if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 ||
keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) {
return hex"";
}
return _output.SLICE479(12, 20);
} else if (_tag == keccak256(hex"17a914")) {
if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) {
return hex"";
}
return _output.SLICE479(11, 20);
}
}
return hex"";
}
function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING
uint256 _offset = 1;
uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]);
if (_nIns >= 0xfd || _nIns == 0) {
return false;
}
for (uint8 i = 0; i < _nIns; i++) {
_offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset));
if (_offset > _vin.length) {
return false;
}
}
return _offset == _vin.length;
}
function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING
uint256 _offset = 1;
uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]);
if (_nOuts >= 0xfd || _nOuts == 0) {
return false;
}
for (uint8 i = 0; i < _nOuts; i++) {
_offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset));
if (_offset > _vout.length) {
return false;
}
}
return _offset == _vout.length;
}
function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(36, 32);
}
function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header));
}
function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING
bytes memory _m = _header.SLICE479(72, 3);
uint8 _e = uint8(_header[75]);
uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m));
uint _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return diff1_target719.DIV358(_target);
}
function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(4, 32);
}
function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header));
}
function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(68, 4);
}
function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING
return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header))));
}
function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header));
}
function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return HASH256986(abi.encodePacked(_a, _b));
}
function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (_proof.length % 32 != 0) {
return false;
}
if (_proof.length == 32) {
return true;
}
if (_proof.length == 64) {
return false;
}
uint _idx = _index;
bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571();
bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571();
for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) {
if (_idx % 2 == 1) {
_current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current));
} else {
_current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32));
}
_idx = _idx >> 1;
}
return _current == _root;
}
function RETARGETALGORITHM78( //inject NONSTANDARD NAMING
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) internal pure returns (uint256) {
uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp);
if (_elapsedTime < retarget_period820.DIV358(4)) {
_elapsedTime = retarget_period820.DIV358(4);
}
if (_elapsedTime > retarget_period820.MUL111(4)) {
_elapsedTime = retarget_period820.MUL111(4);
}
uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime);
return _adjusted.DIV358(retarget_period820).MUL111(65536);
}
}
interface FundsInterface {
function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING
function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING
function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING
}
interface SalesInterface {
function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING
function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING
}
interface CollateralInterface {
function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING
function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING
function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING
function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING
}
contract DSMath {
function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x + y) >= x);
}
function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x - y) <= x);
}
function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require(y == 0 || (z = x * y) / y == x);
}
function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING
require(b > 0);
c = a / b;
}
function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
return x <= y ? x : y;
}
function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
return x >= y ? x : y;
}
function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING
return x <= y ? x : y;
}
function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING
return x >= y ? x : y;
}
uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING
uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING
uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING
function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), col735 / 2) / col735;
}
function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), wad510 / 2) / wad510;
}
function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), ray271 / 2) / ray271;
}
function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, col735), y / 2) / y;
}
function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, wad510), y / 2) / y;
}
function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, ray271), y / 2) / y;
}
function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = n % 2 != 0 ? x : ray271;
for (n /= 2; n != 0; n /= 2) {
x = RMUL965(x, x);
if (n % 2 != 0) {
z = RMUL965(z, x);
}
}
}
}
contract Medianizer {
function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING
function READ913() external returns (bytes32); //inject NONSTANDARD NAMING
function POKE561() external; //inject NONSTANDARD NAMING
function POKE561(bytes32) external; //inject NONSTANDARD NAMING
function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING
}
contract Loans is DSMath {
FundsInterface funds;
Medianizer med;
SalesInterface sales;
CollateralInterface col;
uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING
uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING
uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING
uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING
uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING
uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING
uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING
mapping (bytes32 => Loan) public loans;
mapping (bytes32 => PubKeys) public pubKeys;
mapping (bytes32 => SecretHashes) public secretHashes;
mapping (bytes32 => Bools) public bools;
mapping (bytes32 => bytes32) public fundIndex;
mapping (bytes32 => uint256) public repayments;
mapping (address => bytes32[]) public borrowerLoans;
mapping (address => bytes32[]) public lenderLoans;
mapping (address => mapping(uint256 => bool)) public addressToTimestamp;
uint256 public loanIndex;
ERC20 public token;
uint256 public decimals;
address deployer;
struct Loan {
address borrower;
address lender;
address arbiter;
uint256 createdAt;
uint256 loanExpiration;
uint256 requestTimestamp;
uint256 closedTimestamp;
uint256 principal;
uint256 interest;
uint256 penalty;
uint256 fee;
uint256 liquidationRatio;
}
struct PubKeys {
bytes borrowerPubKey;
bytes lenderPubKey;
bytes arbiterPubKey;
}
struct SecretHashes {
bytes32 secretHashA1;
bytes32[3] secretHashAs;
bytes32 secretHashB1;
bytes32[3] secretHashBs;
bytes32 secretHashC1;
bytes32[3] secretHashCs;
bytes32 withdrawSecret;
bytes32 acceptSecret;
bool set;
}
struct Bools {
bool funded;
bool approved;
bool withdrawn;
bool sale;
bool paid;
bool off;
}
event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING
event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING
event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING
event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING
event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING
event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING
event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING
event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING
event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING
event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING
function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].borrower;
}
function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].lender;
}
function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].arbiter;
}
function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].createdAt, approve_exp_threshold840);
}
function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].loanExpiration, accept_exp_threshold947);
}
function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443);
}
function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699);
}
function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].principal;
}
function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].interest;
}
function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].fee;
}
function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].penalty;
}
function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return col.COLLATERAL382(loan);
}
function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.REFUNDABLECOLLATERAL879(loan);
}
function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.SEIZABLECOLLATERAL368(loan);
}
function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.TEMPORARYREFUNDABLECOLLATERAL760(loan);
}
function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.TEMPORARYSEIZABLECOLLATERAL228(loan);
}
function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return repayments[loan];
}
function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].liquidationRatio;
}
function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(PRINCIPAL566(loan), INTEREST523(loan));
}
function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(OWEDTOLENDER7(loan), FEE426(loan));
}
function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan));
}
function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(OWEDFORLOAN262(loan), REPAID307(loan));
}
function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].funded;
}
function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].approved;
}
function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].withdrawn;
}
function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].sale;
}
function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].paid;
}
function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].off;
}
function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING
return MUL111(x, (10 ** SUB97(18, decimals)));
}
function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING
return DIV358(x, (10 ** SUB97(18, decimals)));
}
function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING
return borrowerLoans[borrower_].length;
}
function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING
return lenderLoans[lender_].length;
}
function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
(bytes32 val, bool set) = med.PEEK685();
require(set, "Loans.minSeizableCollateral: Medianizer must be set");
uint256 price = uint(val);
return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735));
}
function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
(bytes32 val, bool set) = med.PEEK685();
require(set, "Loans.collateralValue: Medianizer must be set");
uint256 price = uint(val);
return CMUL87(price, COLLATERAL382(loan));
}
function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan));
}
function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317);
}
function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan);
}
constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public {
require(address(funds_) != address(0), "Funds address must be non-zero");
require(address(med_) != address(0), "Medianizer address must be non-zero");
require(address(token_) != address(0), "Token address must be non-zero");
deployer = msg.sender;
funds = funds_;
med = med_;
token = token_;
decimals = decimals_;
require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed");
}
function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this");
require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set");
require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero");
sales = sales_;
}
function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this");
require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set");
require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero");
col = col_;
}
function CREATE943( //inject NONSTANDARD NAMING
uint256 loanExpiration_,
address[3] calldata usrs_,
uint256[7] calldata vals_,
bytes32 fund
) external returns (bytes32 loan) {
if (fund != bytes32(0)) {
require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args");
}
require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed");
require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`");
require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero");
require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero");
require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero");
loanIndex = ADD803(loanIndex, 1);
loan = bytes32(loanIndex);
loans[loan].createdAt = now;
loans[loan].loanExpiration = loanExpiration_;
loans[loan].borrower = usrs_[0];
loans[loan].lender = usrs_[1];
loans[loan].arbiter = usrs_[2];
loans[loan].principal = vals_[0];
loans[loan].interest = vals_[1];
loans[loan].penalty = vals_[2];
loans[loan].fee = vals_[3];
uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan);
col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol);
loans[loan].liquidationRatio = vals_[5];
loans[loan].requestTimestamp = vals_[6];
fundIndex[loan] = fund;
secretHashes[loan].set = false;
borrowerLoans[usrs_[0]].push(bytes32(loanIndex));
lenderLoans[usrs_[1]].push(bytes32(loanIndex));
addressToTimestamp[usrs_[0]][vals_[6]] = true;
emit CREATE22(loan);
}
function SETSECRETHASHES742( //inject NONSTANDARD NAMING
bytes32 loan,
bytes32[4] calldata borrowerSecretHashes,
bytes32[4] calldata lenderSecretHashes,
bytes32[4] calldata arbiterSecretHashes,
bytes calldata borrowerPubKey_,
bytes calldata lenderPubKey_,
bytes calldata arbiterPubKey_
) external {
require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set");
require(
msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds),
"Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address"
);
secretHashes[loan].secretHashA1 = borrowerSecretHashes[0];
secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ];
secretHashes[loan].secretHashB1 = lenderSecretHashes[0];
secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ];
secretHashes[loan].secretHashC1 = arbiterSecretHashes[0];
secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ];
pubKeys[loan].borrowerPubKey = borrowerPubKey_;
pubKeys[loan].lenderPubKey = lenderPubKey_;
pubKeys[loan].arbiterPubKey = arbiterPubKey_;
secretHashes[loan].set = true;
}
function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING
require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set");
require(bools[loan].funded == false, "Loans.fund: Loan is already funded");
bools[loan].funded = true;
require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens");
emit FUNDLOAN50(loan);
}
function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING
require(bools[loan].funded == true, "Loans.approve: Loan must be funded");
require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan");
require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline");
bools[loan].approved = true;
emit APPROVE490(loan);
}
function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive");
require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded");
require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved");
require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn");
require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match");
bools[loan].withdrawn = true;
require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens");
secretHashes[loan].withdrawSecret = secretA1;
if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);}
emit WITHDRAW160(loan, secretA1);
}
function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.repay: Loan cannot be inactive");
require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation");
require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn");
require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired");
require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount");
require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens");
repayments[loan] = ADD803(amount, repayments[loan]);
if (REPAID307(loan) == OWEDFORLOAN262(loan)) {
bools[loan].paid = true;
if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);}
}
emit REPAY404(loan, amount);
}
function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.refund: Loan cannot be inactive");
require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation");
require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration");
require(bools[loan].paid == true, "Loans.refund: The loan must be repaid");
require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund");
bools[loan].off = true;
loans[loan].closedTimestamp = now;
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
funds.CALCGLOBALINTEREST773();
}
require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens");
emit REFUND289(loan);
}
function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING
ACCEPT922(loan, secret);
emit CANCEL833(loan, secret);
}
function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.cancel: Loan must not be inactive");
require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn");
require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached");
require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation");
CLOSE691(loan);
emit CANCEL833(loan, bytes32(0));
}
function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.accept: Loan must not be inactive");
require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid");
require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter");
require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past");
require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation");
require(
sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1,
"Loans.accept: Invalid secret"
);
secretHashes[loan].acceptSecret = secret;
CLOSE691(loan);
emit ACCEPT489(loan, secret);
}
function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING
bools[loan].off = true;
loans[loan].closedTimestamp = now;
if (bools[loan].withdrawn == false) {
if (fundIndex[loan] == bytes32(0)) {
require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender");
} else {
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
}
funds.DEPOSIT909(fundIndex[loan], loans[loan].principal);
}
}
else {
if (fundIndex[loan] == bytes32(0)) {
require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender");
} else {
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
}
funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan));
}
require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter");
}
}
function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive");
require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn");
require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party");
require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero");
if (sales.NEXT199(loan) == 0) {
if (now > loans[loan].loanExpiration) {
require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid");
} else {
require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio");
}
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
funds.CALCGLOBALINTEREST773();
}
} else {
require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached");
require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted");
require(
now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)),
"Loans.liquidate: Previous liquidation settlement expiration hasn't expired"
);
}
require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate");
require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed");
SecretHashes storage h = secretHashes[loan];
uint256 i = sales.NEXT199(loan);
sale_ = sales.CREATE943(
loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender,
h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash
);
if (bools[loan].sale == false) {
bools[loan].sale = true;
require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed");
}
if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);}
emit LIQUIDATE130(loan, secretHash, pubKeyHash);
}
}
interface CTokenInterface {
function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING
function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING
function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING
function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING
function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING
function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING
function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING
function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING
function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
interface CERC20Interface {
function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING
function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING
function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING
function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING
}
interface ERC20Interface {
function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
interface TrollerInterface {
function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING
function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING
function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING
function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING
}
contract Helpers is DSMath {
address public comptroller;
function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING
return comptroller;
}
function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING
TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117());
address[] memory markets = troller.GETASSETSIN764(address(this));
bool isEntered = false;
for (uint i = 0; i < markets.length; i++) {
if (markets[i] == cErc20) {
isEntered = true;
}
}
if (!isEntered) {
address[] memory toEnter = new address[](1);
toEnter[0] = cErc20;
troller.ENTERMARKETS395(toEnter);
}
}
function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING
ERC20Interface erc20Contract = ERC20Interface(erc20);
uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to);
if (srcAmt > tokenAllowance) {
erc20Contract.APPROVE357(to, 2**255);
}
}
}
contract ALCompound is Helpers {
function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING
ENTERMARKET780(cErc20);
ERC20Interface token = ERC20Interface(erc20);
uint toDeposit = token.BALANCEOF227(address(this));
if (toDeposit > tokenAmt) {
toDeposit = tokenAmt;
}
CERC20Interface cToken = CERC20Interface(cErc20);
SETAPPROVAL391(erc20, toDeposit, cErc20);
assert(cToken.MINT386(toDeposit) == 0);
}
function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken = CTokenInterface(cErc20);
SETAPPROVAL391(cErc20, 10**50, cErc20);
uint toBurn = cToken.BALANCEOF227(address(this));
uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666());
if (tokenToReturn > tokenAmt) {
tokenToReturn = tokenAmt;
}
require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong");
}
function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken = CTokenInterface(cErc20);
uint toBurn = cToken.BALANCEOF227(address(this));
if (toBurn > cTokenAmt) {
toBurn = cTokenAmt;
}
SETAPPROVAL391(cErc20, toBurn, cErc20);
require(cToken.REDEEM46(toBurn) == 0, "something went wrong");
}
}
contract Funds is DSMath, ALCompound {
Loans loans;
uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING
uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING
uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING
uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING
uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING
uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING
uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING
uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING
mapping (address => bytes32[]) public secretHashes;
mapping (address => uint256) public secretHashIndex;
mapping (address => bytes) public pubKeys;
mapping (bytes32 => Fund) public funds;
mapping (address => bytes32) public fundOwner;
mapping (bytes32 => Bools) public bools;
uint256 public fundIndex;
uint256 public lastGlobalInterestUpdated;
uint256 public tokenMarketLiquidity;
uint256 public cTokenMarketLiquidity;
uint256 public marketLiquidity;
uint256 public totalBorrow;
uint256 public globalInterestRateNumerator;
uint256 public lastUtilizationRatio;
uint256 public globalInterestRate;
uint256 public maxUtilizationDelta;
uint256 public utilizationInterestDivisor;
uint256 public maxInterestRateNumerator;
uint256 public minInterestRateNumerator;
uint256 public interestUpdateDelay;
uint256 public defaultArbiterFee;
ERC20 public token;
uint256 public decimals;
CTokenInterface public cToken;
bool compoundSet;
address deployer;
struct Fund {
address lender;
uint256 minLoanAmt;
uint256 maxLoanAmt;
uint256 minLoanDur;
uint256 maxLoanDur;
uint256 fundExpiry;
uint256 interest;
uint256 penalty;
uint256 fee;
uint256 liquidationRatio;
address arbiter;
uint256 balance;
uint256 cBalance;
}
struct Bools {
bool custom;
bool compoundEnabled;
}
event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING
event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING
event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING
event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING
event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING
event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING
event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING
constructor(
ERC20 token_,
uint256 decimals_
) public {
require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero");
require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero");
deployer = msg.sender;
token = token_;
decimals = decimals_;
utilizationInterestDivisor = 10531702972595856680093239305;
maxUtilizationDelta = 95310179948351216961192521;
globalInterestRateNumerator = 95310179948351216961192521;
maxInterestRateNumerator = 182321557320989604265864303;
minInterestRateNumerator = 24692612600038629323181834;
interestUpdateDelay = 86400;
defaultArbiterFee = 1000000000236936036262880196;
globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521));
}
function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this");
require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set");
require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero");
loans = loans_;
require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved");
}
function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending");
require(!compoundSet, "Funds.setCompound: Compound address has already been set");
require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero");
require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero");
cToken = cToken_;
comptroller = comptroller_;
compoundSet = true;
}
function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this");
require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero");
utilizationInterestDivisor = utilizationInterestDivisor_;
}
function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this");
require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero");
maxUtilizationDelta = maxUtilizationDelta_;
}
function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this");
require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero");
globalInterestRateNumerator = globalInterestRateNumerator_;
}
function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this");
require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero");
globalInterestRate = globalInterestRate_;
}
function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this");
require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero");
maxInterestRateNumerator = maxInterestRateNumerator_;
}
function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this");
require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero");
minInterestRateNumerator = minInterestRateNumerator_;
}
function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this");
require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero");
interestUpdateDelay = interestUpdateDelay_;
}
function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this");
require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%");
defaultArbiterFee = defaultArbiterFee_;
}
function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING
return funds[fund].lender;
}
function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].minLoanAmt;}
else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));}
}
function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].maxLoanAmt;}
else {return default_max_loan_amt507;}
}
function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].minLoanDur;}
else {return default_min_loan_dur981;}
}
function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
return funds[fund].maxLoanDur;
}
function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
return funds[fund].fundExpiry;
}
function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].interest;}
else {return globalInterestRate;}
}
function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].penalty;}
else {return default_liquidation_penalty756;}
}
function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].fee;}
else {return defaultArbiterFee;}
}
function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].liquidationRatio;}
else {return default_liquidation_ratio475;}
}
function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING
return funds[fund].arbiter;
}
function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].compoundEnabled) {
return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666());
} else {
return funds[fund].balance;
}
}
function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING
if (compoundSet) {
return cToken.EXCHANGERATECURRENT666();
} else {
return 0;
}
}
function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[fund].custom;
}
function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING
return secretHashes[addr_].length;
}
function CREATE943( //inject NONSTANDARD NAMING
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address");
require(
ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66,
"Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years"
);
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");}
fundIndex = ADD803(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false);
funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true);
funds[fund].arbiter = arbiter_;
bools[fund].custom = false;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {DEPOSIT909(fund, amount_);}
emit CREATE22(fund);
}
function CREATECUSTOM959( //inject NONSTANDARD NAMING
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 liquidationRatio_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address");
require(
ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66,
"Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years"
);
require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur");
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");}
fundIndex = ADD803(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false);
funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true);
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
funds[fund].arbiter = arbiter_;
bools[fund].custom = true;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {DEPOSIT909(fund, amount_);}
emit CREATE22(fund);
}
function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING
require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens");
if (bools[fund].compoundEnabled) {
MINTCTOKEN703(address(token), address(cToken), amount_);
uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666());
funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd);
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);}
} else {
funds[fund].balance = ADD803(funds[fund].balance, amount_);
if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();}
emit DEPOSIT856(fund, amount_);
}
function UPDATE438( //inject NONSTANDARD NAMING
bytes32 fund,
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_
) public {
require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund");
require(
ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66,
"Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years"
);
funds[fund].maxLoanDur = maxLoanDur_;
funds[fund].fundExpiry = fundExpiry_;
funds[fund].arbiter = arbiter_;
emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_);
}
function UPDATECUSTOM705( //inject NONSTANDARD NAMING
bytes32 fund,
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
uint256 liquidationRatio_,
address arbiter_
) external {
require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund");
require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur");
UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_);
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
}
function REQUEST711( //inject NONSTANDARD NAMING
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_,
bytes32[8] calldata secretHashes_,
bytes calldata pubKeyA_,
bytes calldata pubKeyB_
) external returns (bytes32 loanIndex) {
require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request");
require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance");
require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt");
require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt");
require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur");
require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry");
require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero");
require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero");
require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero");
require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero");
require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero");
loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_);
LOANUPDATEMARKETLIQUIDITY912(fund, amount_);
loans.FUND172(loanIndex);
emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
}
function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING
WITHDRAWTO298(fund, amount_, msg.sender);
}
function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING
require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens");
require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance");
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
REDEEMUNDERLYING614(address(cToken), amount_);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove);
require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = SUB97(funds[fund].balance, amount_);
require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();}
emit WITHDRAW160(fund, amount_, recipient_);
}
function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING
for (uint i = 0; i < secretHashes_.length; i++) {
secretHashes[msg.sender].push(secretHashes_[i]);
}
}
function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING
pubKeys[msg.sender] = pubKey_;
}
function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING
require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured");
require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled");
require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound");
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
MINTCTOKEN703(address(token), address(cToken), funds[fund].balance);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore);
tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance);
cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn);
bools[fund].compoundEnabled = true;
funds[fund].balance = 0;
funds[fund].cBalance = cTokenToReturn;
emit ENABLECOMPOUND170(fund);
}
function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING
require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled");
require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound");
uint256 balanceBefore = token.BALANCEOF227(address(this));
REDEEMCTOKEN224(address(cToken), funds[fund].cBalance);
uint256 balanceAfter = token.BALANCEOF227(address(this));
uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore);
tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn);
cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance);
bools[fund].compoundEnabled = false;
funds[fund].cBalance = 0;
funds[fund].balance = tokenToReturn;
emit DISABLECOMPOUND118(fund);
}
function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING
require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this");
totalBorrow = SUB97(totalBorrow, amount_);
}
function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING
marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725()));
if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) {
uint256 utilizationRatio;
if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));}
if (utilizationRatio > lastUtilizationRatio) {
uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio);
globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
} else {
uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio);
globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
}
globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521));
lastGlobalInterestUpdated = now;
lastUtilizationRatio = utilizationRatio;
}
}
function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_);
}
function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING
if (value == 0) {
if (addNow) {
return now + max_loan_length66;
}
return max_loan_length66;
}
return value;
}
function CREATELOAN338( //inject NONSTANDARD NAMING
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_
) private returns (bytes32 loanIndex) {
loanIndex = loans.CREATE943(
now + loanDur_,
[borrower_, LENDER92(fund), funds[fund].arbiter],
[
amount_,
CALCINTEREST818(amount_, INTEREST523(fund), loanDur_),
CALCINTEREST818(amount_, PENALTY434(fund), loanDur_),
CALCINTEREST818(amount_, FEE426(fund), loanDur_),
collateral_,
LIQUIDATIONRATIO684(fund),
requestTimestamp_
],
fund
);
}
function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING
bytes32 fund,
bytes32 loan,
bytes32[8] memory secretHashes_,
bytes memory pubKeyA_,
bytes memory pubKeyB_
) private {
loans.SETSECRETHASHES742(
loan,
[ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ],
[ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ],
GETSECRETHASHESFORLOAN447(ARBITER4(fund)),
pubKeyA_,
pubKeyB_,
pubKeys[ARBITER4(fund)]
);
}
function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
REDEEMUNDERLYING614(address(cToken), amount_);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove);
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = SUB97(funds[fund].balance, amount_);
if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {
totalBorrow = ADD803(totalBorrow, amount_);
CALCGLOBALINTEREST773();
}
}
function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING
secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4);
require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated");
return [
secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)]
];
}
}
|
inject NONSTANDARD NAMING
|
function FEE426(bytes32 fund) public view returns (uint256) {
| 1,784,275 |
pragma solidity ^0.4.24;
import "../ERC20/IERC20.sol";
import "../crowdsale/ICrowdsale.sol";
import "./IPresale.sol";
import "../access/roles/ManagerRole.sol";
import "../access/roles/RecoverRole.sol";
import "../math/SafeMath.sol";
/**
* @title Presale module contract
*
*/
contract Presale is IPresale, ManagerRole, RecoverRole {
using SafeMath for uint256;
/*
* Storage
*/
mapping (address => uint256) private _presaleBalances;
uint256 private _presaleAllocation;
uint256 private _totalPresaleSupply;
IERC20 private _erc20;
ICrowdsale private _crowdsale;
Stages public stages;
/*
* Enums
*/
enum Stages {
PresaleDeployed,
Presale,
PresaleEnded
}
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
require(stages == _stage, "functionality not allowed at current stage");
_;
}
modifier onlyCrowdsale() {
require(msg.sender == address(_crowdsale), "only the crowdsale can call this function");
_;
}
/**
* @dev Constructor
* @param token_ TBNERC20 token contract
*/
constructor(
IERC20 token
) public {
require(token != address(0), "token address cannot be 0x0");
_erc20 = token;
stages = Stages.PresaleDeployed;
}
/**
* @dev Safety fallback reverts missent ETH payments
*/
function () public payable {
revert ();
}
/**
* @dev Safety function for recovering missent ERC20 tokens (and recovering the un-distributed allocation after PresaleEnded)
* @param token address of the ERC20 contract to recover
*/
function recoverTokens(IERC20 token) external onlyRecoverer atStage(Stages.PresaleEnded) returns (bool) {
uint256 recovered = token.balanceOf(address(this));
token.transfer(msg.sender, recovered);
emit TokensRecovered(token, recovered);
return true;
}
/**
* @dev Total number of tokens allocated to presale
*/
function getPresaleAllocation() public view returns (uint256) {
return _presaleAllocation;
}
/**
* @dev Total number of presale tokens un-distributed to presale accounts
*/
function totalPresaleSupply() public view returns (uint256) {
return _totalPresaleSupply;
}
/**
* @dev Total number of presale tokens distributed to presale accounts
*/
function getPresaleDistribution() public view returns (uint256) {
return _presaleAllocation.sub(_totalPresaleSupply);
}
/**
* @dev Gets the balance of the specified address.
* @param account The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function presaleBalanceOf(address account) public view returns (uint256) {
return _presaleBalances[account];
}
function getERC20() public view returns (address) {
return address(_erc20);
}
function getCrowdsale() public view returns (address) {
return address(_crowdsale);
}
/**
* @dev Assigns the presale token allocation to this contract. Note: fundkeeper must give this contract an allowance before callin intialize
* @param presaleAllocation the amount of tokens to assign to this contract for presale distribution
*/
function initilize(
uint256 presaleAllocation
)
external
onlyManager
atStage(Stages.PresaleDeployed)
returns (bool)
{
require(presaleAllocation > 0, "presaleAllocation must be greater than zero");
address fundkeeper = _erc20.fundkeeper();
require(_erc20.allowance(address(fundkeeper), address(this)) == presaleAllocation, "presale allocation must be equal to the amount of tokens approved for this contract");
_presaleAllocation = presaleAllocation;
_totalPresaleSupply = presaleAllocation;
// place presale allocation in this contract (uses the approve/transferFrom pattern)
_erc20.transferFrom(fundkeeper, address(this), presaleAllocation);
stages = Stages.Presale;
emit PresaleInitialized(presaleAllocation);
return true;
}
/**
* @dev Transfer presale tokens to another account
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return bool true on success
*/
function presaleTransfer(address from, address to, uint256 value) external onlyManager atStage(Stages.Presale) returns (bool) {
_presaleTransfer(from, to, value);
return true;
}
/**
* @dev Set the crowdsale contract storage (only contract Manger and only at Presale Stage)
* @param TBNCrowdsale The crowdsale contract deployment
*/
function setCrowdsale(ICrowdsale TBNCrowdsale)
external
onlyManager
atStage(Stages.Presale)
returns (bool)
{
require(TBNCrowdsale.getERC20() == address(_erc20), "Crowdsale contract must be assigned to the same ERC20 instance as this contract");
_crowdsale = TBNCrowdsale;
emit SetCrowdsale(_crowdsale);
return true;
}
/**
* @dev Assign presale tokens to accounts (only contract Manger and only at Presale Stage)
* @param presaleAccounts The accounts to add presale token balances from
* @param values The amount of tokens to be add to each account
*/
function addPresaleBalance(address[] presaleAccounts, uint256[] values) external onlyManager atStage(Stages.Presale) returns (bool) {
require(presaleAccounts.length == values.length, "presaleAccounts and values must have one-to-one relationship");
for (uint32 i = 0; i < presaleAccounts.length; i++) {
_addPresaleBalance(presaleAccounts[i], values[i]);
}
return true;
}
/**
* @dev Subtract presale tokens to accounts (only contract Manger and only at Presale Stage)
* @param presaleAccounts The accounts to subtract presale token balances from
* @param values The amount of tokens to subtract from each account
*/
function subPresaleBalance(address[] presaleAccounts, uint256[] values) external onlyManager atStage(Stages.Presale) returns (bool) {
require(presaleAccounts.length == values.length, "presaleAccounts and values must have one-to-one relationship");
for (uint32 i = 0; i < presaleAccounts.length; i++) {
_subPresaleBalance(presaleAccounts[i], values[i]);
}
return true;
}
/**
* @dev Called to end presale Stage. Can only be called by the crowdsale contract and will only be called when the Crowdsale begins
*/
function presaleEnd() external onlyCrowdsale atStage(Stages.Presale) returns (bool) {
uint256 presaleDistribution = getPresaleDistribution();
_erc20.transfer(_crowdsale, presaleDistribution);
stages = Stages.PresaleEnded;
emit PresaleEnded();
return true;
}
/**
* @dev Transfer presale tokens to another account (internal operation)
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _presaleTransfer(address from, address to, uint256 value) internal {
require(value <= _presaleBalances[from], "transfer value must be less than the balance of the from account");
require(to != address(0), "cannot transfer to the 0x0 address");
_presaleBalances[from] = _presaleBalances[from].sub(value);
_presaleBalances[to] = _presaleBalances[to].add(value);
emit PresaleTransfer(from, to, value);
}
/**
* @dev Add presale tokens to an account (internal operation)
* @param presaleAccount The account which is assigned presale holdings
* @param value The amount of tokens to be assigned to this account
*/
function _addPresaleBalance(address presaleAccount, uint256 value) internal {
require(presaleAccount != address(0), "cannot add balance to the 0x0 account");
require(value <= _totalPresaleSupply, "");
_totalPresaleSupply = _totalPresaleSupply.sub(value);
_presaleBalances[presaleAccount] = _presaleBalances[presaleAccount].add(value);
emit PresaleBalanceAdded(presaleAccount, value);
}
/**
* @dev Assign presale tokens to an account (internal operation)
* @param presaleAccount The account which is assigned presale holdings
* @param value The amount of tokens to be assigned to this account
*/
function _subPresaleBalance(address presaleAccount, uint256 value) internal {
require(_presaleBalances[presaleAccount] > 0, "presaleAccount must have presale balance to subtract");
require(value <= _presaleBalances[presaleAccount], "value must be less than or equal to the presale Account balance");
_totalPresaleSupply = _totalPresaleSupply.add(value);
_presaleBalances[presaleAccount] = _presaleBalances[presaleAccount].sub(value);
emit PresaleBalanceASubtracted(presaleAccount, value);
}
}
|
Add presale tokens to an account (internal operation) presaleAccount The account which is assigned presale holdings value The amount of tokens to be assigned to this account/
|
function _addPresaleBalance(address presaleAccount, uint256 value) internal {
require(presaleAccount != address(0), "cannot add balance to the 0x0 account");
require(value <= _totalPresaleSupply, "");
_totalPresaleSupply = _totalPresaleSupply.sub(value);
_presaleBalances[presaleAccount] = _presaleBalances[presaleAccount].add(value);
emit PresaleBalanceAdded(presaleAccount, value);
}
| 14,034,857 |
./partial_match/42/0x4ffADC639B57e864150ff98a55D249fed53fa63B/sources/ZuniBadge.sol
|
Get the denormalized weight of a token viewlock to prevent calling if it's being updated return token weight/
|
function getDenormalizedWeight(address token)
external
view
viewlock
needsBPool
returns (uint256)
{
return bPool.getDenormalizedWeight(token);
}
| 3,449,035 |
./full_match/1/0x0D062790F26947074B27da07346E4FF9FDf946EE/sources/src/Facets/PolygonBridgeFacet.sol
|
Bridges tokens via Polygon Bridge _bridgeData Data containing core information for bridging
|
function startBridgeTokensViaPolygonBridge(
ILiFi.BridgeData memory _bridgeData
)
external
payable
nonReentrant
refundExcessNative(payable(msg.sender))
doesNotContainSourceSwaps(_bridgeData)
doesNotContainDestinationCalls(_bridgeData)
validateBridgeData(_bridgeData)
{
LibAsset.depositAsset(
_bridgeData.sendingAssetId,
_bridgeData.minAmount
);
_startBridge(_bridgeData);
}
| 17,018,344 |
pragma solidity 0.5.8;
import "./OZStorage.sol";
import "./SecurityTokenStorage.sol";
import "../libraries/TokenLib.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../modules/PermissionManager/IPermissionManager.sol";
contract STGetter is OZStorage, SecurityTokenStorage {
using SafeMath for uint256;
/**
* @notice A security token issuer can specify that issuance has finished for the token
* (i.e. no new tokens can be minted or issued).
* @dev If a token returns FALSE for `isIssuable()` then it MUST always return FALSE in the future.
* If a token returns FALSE for `isIssuable()` then it MUST never allow additional tokens to be issued.
* @return bool `true` signifies the minting is allowed. While `false` denotes the end of minting
*/
function isIssuable() external view returns (bool) {
return issuance;
}
/**
* @notice Gets list of times that checkpoints were created
* @return List of checkpoint times
*/
function getCheckpointTimes() external view returns(uint256[] memory) {
return checkpointTimes;
}
/**
* @notice Returns the count of address that were added as (potential) investors
* @return Investor count
*/
function getInvestorCount() external view returns(uint256) {
return dataStore.getAddressArrayLength(INVESTORSKEY);
}
/**
* @notice returns an array of investors
* NB - this length may differ from investorCount as it contains all investors that ever held tokens
* @return list of addresses
*/
function getInvestors() public view returns(address[] memory investors) {
investors = dataStore.getAddressArray(INVESTORSKEY);
}
/**
* @notice returns an array of investors with non zero balance at a given checkpoint
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @return list of investors
*/
function getInvestorsAt(uint256 _checkpointId) external view returns(address[] memory) {
uint256 count;
uint256 i;
address[] memory investors = dataStore.getAddressArray(INVESTORSKEY);
for (i = 0; i < investors.length; i++) {
if (balanceOfAt(investors[i], _checkpointId) > 0) {
count++;
} else {
investors[i] = address(0);
}
}
address[] memory holders = new address[](count);
count = 0;
for (i = 0; i < investors.length; i++) {
if (investors[i] != address(0)) {
holders[count] = investors[i];
count++;
}
}
return holders;
}
/**
* @notice returns an array of investors with non zero balance at a given checkpoint
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/
function getInvestorsSubsetAt(uint256 _checkpointId, uint256 _start, uint256 _end) external view returns(address[] memory) {
uint256 count;
uint256 i;
address[] memory investors = dataStore.getAddressArrayElements(INVESTORSKEY, _start, _end);
for (i = 0; i < investors.length; i++) {
if (balanceOfAt(investors[i], _checkpointId) > 0) {
count++;
} else {
investors[i] = address(0);
}
}
address[] memory holders = new address[](count);
count = 0;
for (i = 0; i < investors.length; i++) {
if (investors[i] != address(0)) {
holders[count] = investors[i];
count++;
}
}
return holders;
}
/**
* @notice Returns the data associated to a module
* @param _module address of the module
* @return bytes32 name
* @return address module address
* @return address module factory address
* @return bool module archived
* @return uint8 array of module types
* @return bytes32 module label
*/
function getModule(address _module) external view returns(bytes32, address, address, bool, uint8[] memory, bytes32) {
return (
modulesToData[_module].name,
modulesToData[_module].module,
modulesToData[_module].moduleFactory,
modulesToData[_module].isArchived,
modulesToData[_module].moduleTypes,
modulesToData[_module].label
);
}
/**
* @notice Returns a list of modules that match the provided name
* @param _name name of the module
* @return address[] list of modules with this name
*/
function getModulesByName(bytes32 _name) external view returns(address[] memory) {
return names[_name];
}
/**
* @notice Returns a list of modules that match the provided module type
* @param _type type of the module
* @return address[] list of modules with this type
*/
function getModulesByType(uint8 _type) external view returns(address[] memory) {
return modules[_type];
}
/**
* @notice use to return the global treasury wallet
*/
function getTreasuryWallet() external view returns(address) {
return dataStore.getAddress(TREASURY);
}
/**
* @notice Queries balances as of a defined checkpoint
* @param _investor Investor to query balance for
* @param _checkpointId Checkpoint ID to query as of
*/
function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256) {
require(_checkpointId <= currentCheckpointId);
return TokenLib.getValueAt(checkpointBalances[_investor], _checkpointId, balanceOf(_investor));
}
/**
* @notice Queries totalSupply as of a defined checkpoint
* @param _checkpointId Checkpoint ID to query
* @return uint256
*/
function totalSupplyAt(uint256 _checkpointId) external view returns(uint256) {
require(_checkpointId <= currentCheckpointId);
return checkpointTotalSupply[_checkpointId];
}
/**
* @notice generates subset of investors
* NB - can be used in batches if investor list is large. start and end both are included in array.
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/
function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[] memory) {
return dataStore.getAddressArrayElements(INVESTORSKEY, _start, _end);
}
/**
* @notice Validate permissions with PermissionManager if it exists, If no Permission return false
* @dev Note that IModule withPerm will allow ST owner all permissions anyway
* @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
* @param _delegate address of delegate
* @param _module address of PermissionManager module
* @param _perm the permissions
* @return success
*/
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) {
for (uint256 i = 0; i < modules[PERMISSION_KEY].length; i++) {
if (!modulesToData[modules[PERMISSION_KEY][i]].isArchived) {
if (IPermissionManager(modules[PERMISSION_KEY][i]).checkPermission(_delegate, _module, _perm)) {
return true;
}
}
}
return false;
}
/**
* @notice Determines whether `_operator` is an operator for all partitions of `_tokenHolder`
* @param _operator The operator to check
* @param _tokenHolder The token holder to check
* @return Whether the `_operator` is an operator for all partitions of `_tokenHolder`
*/
function isOperator(address _operator, address _tokenHolder) external view returns (bool) {
return (_allowance(_tokenHolder, _operator) == uint(-1));
}
/**
* @notice Determines whether `_operator` is an operator for a specified partition of `_tokenHolder`
* @param _partition The partition to check
* @param _operator The operator to check
* @param _tokenHolder The token holder to check
* @return Whether the `_operator` is an operator for a specified partition of `_tokenHolder`
*/
function isOperatorForPartition(bytes32 _partition, address _operator, address _tokenHolder) external view returns (bool) {
return partitionApprovals[_tokenHolder][_partition][_operator];
}
/**
* @notice Return all partitions
* @return List of partitions
*/
function partitionsOf(address /*_tokenHolder*/) external pure returns (bytes32[] memory) {
bytes32[] memory result = new bytes32[](2);
result[0] = UNLOCKED;
result[1] = LOCKED;
return result;
}
/**
* @notice Returns the version of the SecurityToken
*/
function getVersion() external view returns(uint8[] memory) {
uint8[] memory version = new uint8[](3);
version[0] = securityTokenVersion.major;
version[1] = securityTokenVersion.minor;
version[2] = securityTokenVersion.patch;
return version;
}
/**
* @notice Used to return the details of a document with a known name (`bytes32`).
* @param _name Name of the document
* @return string The URI associated with the document.
* @return bytes32 The hash (of the contents) of the document.
* @return uint256 the timestamp at which the document was last modified.
*/
function getDocument(bytes32 _name) external view returns (string memory, bytes32, uint256) {
return (
_documents[_name].uri,
_documents[_name].docHash,
_documents[_name].lastModified
);
}
/**
* @notice Used to retrieve a full list of documents attached to the smart contract.
* @return bytes32 List of all documents names present in the contract.
*/
function getAllDocuments() external view returns (bytes32[] memory) {
return _docNames;
}
}
|
Return all partitions return List of partitions/
|
function partitionsOf(address /*_tokenHolder*/) external pure returns (bytes32[] memory) {
bytes32[] memory result = new bytes32[](2);
result[0] = UNLOCKED;
result[1] = LOCKED;
return result;
}
| 5,376,736 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
// dependencies
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// interfaces
import {IPerpetual} from "./interfaces/IPerpetual.sol";
import {IVault} from "./interfaces/IVault.sol";
// libraries
import {LibMath} from "./lib/LibMath.sol";
import {LibPerpetual} from "./lib/LibPerpetual.sol";
import {IncreOwnable} from "./utils/IncreOwnable.sol";
import {MockStableSwap} from "./mocks/MockStableSwap.sol";
import "hardhat/console.sol";
contract Perpetual is IPerpetual, Context, IncreOwnable {
using SafeCast for uint256;
using SafeCast for int256;
// parameterization
int256 constant MIN_MARGIN = 25e15; // 2.5%
int256 constant LIQUIDATION_FEE = 60e15; // 6%
int256 constant PRECISION = 10e18;
// global state
MockStableSwap private market;
LibPerpetual.GlobalPosition private globalPosition;
LibPerpetual.Price[] private prices;
mapping(IVault => bool) private vaultInitialized;
// user state
mapping(address => LibPerpetual.TraderPosition) private userPosition;
mapping(address => IVault) private vaultUsed;
constructor(uint256 _vQuote, uint256 _vBase) {
market = new MockStableSwap(_vQuote, _vBase);
}
// global getter
function getStableSwap() public view returns (address) {
return address(market);
}
function isVault(address vaultAddress) public view returns (bool) {
return vaultInitialized[IVault(vaultAddress)];
}
function getLatestPrice() public view override returns (LibPerpetual.Price memory) {
return getPrice(prices.length - 1);
}
function getPrice(uint256 period) public view override returns (LibPerpetual.Price memory) {
return prices[period];
}
function getGlobalPosition() public view override returns (LibPerpetual.GlobalPosition memory) {
return globalPosition;
}
// user getter
function getVault(address account) public view override returns (IVault) {
return vaultUsed[account];
}
function getUserPosition(address account) public view override returns (LibPerpetual.TraderPosition memory) {
return userPosition[account];
}
// functions
function setVault(address vaultAddress) public onlyOwner {
IVault vault = IVault(vaultAddress);
require(vaultInitialized[vault] == false, "Vault is already initialized");
vaultInitialized[vault] = true;
emit VaultRegistered(vaultAddress);
}
function setPrice(LibPerpetual.Price memory newPrice) external override {
prices.push(newPrice);
}
function _verifyAndSetVault(IVault vault) internal {
require(vaultInitialized[vault], "Vault is not initialized");
IVault oldVault = vaultUsed[_msgSender()];
if (address(oldVault) == address(0)) {
// create new vault
vaultUsed[_msgSender()] = vault;
emit VaultAssigned(_msgSender(), address(vault));
} else {
// check uses same vault
require(oldVault == vault, "Uses other vault");
}
}
/// @notice Deposits tokens into the vault. Note that a vault can support multiple collateral tokens.
function deposit(
uint256 amount,
IVault vault,
IERC20 token
) external override {
_verifyAndSetVault(vault);
vault.deposit(_msgSender(), amount, token);
emit Deposit(_msgSender(), address(token), amount);
}
/// @notice Withdraw tokens from the vault. Note that a vault can support multiple collateral tokens.
function withdraw(uint256 amount, IERC20 token) external override {
require(getUserPosition(_msgSender()).notional == 0, "Has open position");
IVault vault = vaultUsed[_msgSender()];
vault.withdraw(_msgSender(), amount, token);
emit Withdraw(_msgSender(), address(token), amount);
}
/// @notice Buys long Quote derivatives
/// @param amount Amount of Quote tokens to be bought
/// @dev No checks are done if bought amount exceeds allowance
function openPosition(uint256 amount, LibPerpetual.Side direction) external override returns (uint256) {
LibPerpetual.TraderPosition storage user = userPosition[_msgSender()];
LibPerpetual.GlobalPosition storage global = globalPosition;
require(user.notional == 0, "Trader position is not allowed to have position open");
uint256 quoteBought = _openPosition(user, global, direction, amount);
emit OpenPosition(_msgSender(), uint128(block.timestamp), direction, amount, quoteBought);
return quoteBought;
}
function _openPosition(
LibPerpetual.TraderPosition storage user,
LibPerpetual.GlobalPosition storage global,
LibPerpetual.Side direction,
uint256 amount
) internal returns (uint256) {
// buy derivative tokens
user.side = direction;
uint256 quoteBought = _openPositionOnMarket(amount, direction);
// set trader position
user.notional = amount.toInt256();
user.positionSize = quoteBought.toInt256();
user.profit = 0;
user.timeStamp = global.timeStamp;
user.cumFundingRate = global.cumFundingRate;
return quoteBought;
}
function _openPositionOnMarket(uint256 amount, LibPerpetual.Side direction) internal returns (uint256) {
uint256 quoteBought = 0;
if (direction == LibPerpetual.Side.Long) {
quoteBought = market.mintVBase(amount);
} else if (direction == LibPerpetual.Side.Short) {
quoteBought = market.burnVBase(amount);
}
return quoteBought;
}
/// @notice Closes position from account holder
function closePosition() external override {
LibPerpetual.TraderPosition storage user = userPosition[_msgSender()];
LibPerpetual.GlobalPosition storage global = globalPosition;
// get information about position
_closePosition(user, global);
// apply changes to collateral
IVault userVault = vaultUsed[_msgSender()];
userVault.settleProfit(_msgSender(), user.profit);
}
function _closePosition(LibPerpetual.TraderPosition storage user, LibPerpetual.GlobalPosition storage global)
internal
{
uint256 amount = (user.positionSize).toUint256();
LibPerpetual.Side direction = user.side;
// settle funding rate
_settle(user, global);
// sell derivative tokens
uint256 quoteSold = _closePositionOnMarket(amount, direction);
// set trader position
user.profit += _calculatePnL(user.notional, quoteSold.toInt256());
user.notional = 0;
user.positionSize = 0;
}
// get information about position
function _calculatePnL(int256 boughtPrice, int256 soldPrice) internal pure returns (int256) {
return soldPrice - boughtPrice;
}
/// notional sell derivative tokens on (external) market
function _closePositionOnMarket(uint256 amount, LibPerpetual.Side direction) internal returns (uint256) {
uint256 quoteSold = 0;
if (direction == LibPerpetual.Side.Long) {
quoteSold = market.mintVQuote(amount);
} else {
quoteSold = market.burnVQuote(amount);
}
return quoteSold;
}
/// @notice Settle funding rate
function settle(address account) public override {
LibPerpetual.TraderPosition storage user = userPosition[account];
LibPerpetual.GlobalPosition storage global = globalPosition;
_settle(user, global);
}
function _settle(LibPerpetual.TraderPosition storage user, LibPerpetual.GlobalPosition storage global) internal {
if (user.notional != 0 && user.timeStamp < global.timeStamp) {
// update user variables when position opened before last update
int256 upcomingFundingPayment = getFundingPayments(user, global);
_applyFundingPayment(user, upcomingFundingPayment);
emit Settlement(_msgSender(), user.timeStamp, upcomingFundingPayment);
}
// update user variables to global state
user.timeStamp = global.timeStamp;
user.cumFundingRate = global.cumFundingRate;
}
/// @notice Apply funding payments
function _applyFundingPayment(LibPerpetual.TraderPosition storage user, int256 payments) internal {
user.profit += payments;
}
/// @notice Calculate missed funing payments
function getFundingPayments(LibPerpetual.TraderPosition memory user, LibPerpetual.GlobalPosition memory global)
public
pure
returns (int256)
{
/* Funding rates (as defined in our protocol) are paid from shorts to longs
case 1: user is long => has missed receiving funding payments (positive or negative)
case 2: user is short => has missed making funding payments (positive or negative)
comment: Making an negative funding payment is equvalent to receiving a positive one.
*/
int256 upcomingFundingRate = 0;
int256 upcomingFundingPayment = 0;
if (user.cumFundingRate != global.cumFundingRate) {
if (user.side == LibPerpetual.Side.Long) {
upcomingFundingRate = global.cumFundingRate - user.cumFundingRate;
} else {
upcomingFundingRate = user.cumFundingRate - global.cumFundingRate;
}
upcomingFundingPayment = LibMath.mul(upcomingFundingRate, user.notional);
}
return upcomingFundingPayment;
}
function marginIsValid(address account) public view override returns (bool) {
return marginRatio(account) <= MIN_MARGIN;
}
/// @notice Calculate the margin Ratio of some account
function marginRatio(address account) public view override returns (int256) {
LibPerpetual.TraderPosition memory user = getUserPosition(account);
LibPerpetual.GlobalPosition memory global = getGlobalPosition();
IVault userVault = getVault(account);
// calcuate margin ratio = = (margin + pnl + fundingPayments) / position.getNotional()
int256 margin = userVault.getReserveValue(account);
int256 fundingPayments = getFundingPayments(user, global);
int256 unrealizedPnl = 0; /// toDO: requires implementation of curve pool;
int256 profit = getUserPosition(account).profit;
return LibMath.div(margin + unrealizedPnl + fundingPayments + profit, user.notional);
}
function liquidate(address account, IVault liquidatorVault) external {
require(!marginIsValid(account), "Margin is not valid");
address liquidator = _msgSender();
// load information about state
LibPerpetual.TraderPosition storage user = userPosition[account];
LibPerpetual.GlobalPosition storage global = globalPosition;
int256 notionalAmount = user.notional;
// get information about position
_closePosition(user, global);
// liquidation costs
int256 liquidationFee = (notionalAmount * LIQUIDATION_FEE) / PRECISION;
// profits - liquidationFee gets paid out
int256 reducedProfit = user.profit - liquidationFee;
// substract fee from user account
IVault userVault = vaultUsed[account];
userVault.settleProfit(account, reducedProfit);
// add fee to liquidator account
_verifyAndSetVault(liquidatorVault);
liquidatorVault.settleProfit(liquidator, liquidationFee);
emit LiquidationCall(account, _msgSender(), uint128(block.timestamp), notionalAmount);
}
}
|
get information about position
|
function _calculatePnL(int256 boughtPrice, int256 soldPrice) internal pure returns (int256) {
return soldPrice - boughtPrice;
}
| 994,504 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Context.sol";
// ============ Errors ============
error InvalidCall();
// ============ Contract ============
abstract contract ERC721 is Context, ERC165, IERC721 {
// ============ Storage ============
// Mapping from token ID to owner address
mapping(uint256 => address) internal _owners;
// Mapping owner address to token count
mapping(address => uint256) internal _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;
// ============ Modifiers ============
modifier isOwner(uint256 tokenId, address owner) {
if (_owners[tokenId] != owner) revert InvalidCall();
_;
}
modifier isToken(uint256 tokenId) {
if (_owners[tokenId] == address(0)) revert InvalidCall();
_;
}
modifier isNotToken(uint256 tokenId) {
if (_owners[tokenId] != address(0)) revert InvalidCall();
_;
}
modifier notZeroAddress(address location) {
if (location == address(0)) revert InvalidCall();
_;
}
modifier isApproved(address from, uint256 tokenId) {
address spender = _msgSender();
if (spender != from
&& getApproved(tokenId) != spender
&& !isApprovedForAll(from, spender)
) revert InvalidCall();
_;
}
// ============ Read Methods ============
/**
* @dev Returns the number of tokens in `owner`'s account.
*/
function balanceOf(
address owner
) public virtual view returns(uint256 balance) {
return _balances[owner];
}
/**
* @dev Returns the account approved for `tokenId` token.
*/
function getApproved(
uint256 tokenId
) public virtual view returns(address operator) {
return _tokenApprovals[tokenId];
}
/**
* @dev Returns if the `operator` is allowed to manage all of the
* assets of `owner`.
*/
function isApprovedForAll(
address owner,
address operator
) public virtual view returns(bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Returns the owner of the `tokenId` token.
*/
function ownerOf(
uint256 tokenId
) public virtual view returns(address owner) {
return _owners[tokenId];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
virtual
view
override(ERC165, IERC165)
returns(bool)
{
return
interfaceId == type(IERC721).interfaceId
|| super.supportsInterface(interfaceId);
}
// ============ Approve Methods ============
/**
* @dev Gives permission to `to` to transfer `tokenId` token to
* another account. The approval is cleared when the token is
* transferred.
*/
function approve(address to, uint256 tokenId) public virtual {
address owner = _owners[tokenId];
if (to == owner) revert InvalidCall();
address sender = _msgSender();
if (sender != owner && !isApprovedForAll(owner, sender))
revert InvalidCall();
_approve(to, tokenId, owner);
}
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any
* token owned by the caller.
*/
function setApprovalForAll(
address operator,
bool approved
) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId, address owner)
internal virtual
{
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any
* token owned by the caller.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
if (owner == operator) revert InvalidCall();
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
// ============ Burn Methods ============
/**
* @dev Blindly burns `tokenId`.
*/
function _burn(uint256 tokenId) internal virtual isToken(tokenId) {
address from = _owners[tokenId];
//allow other contracts to tap into this
_beforeTokenTransfer(from, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId, from);
unchecked {
_balances[from] -= 1;
delete _owners[tokenId];
}
emit Transfer(from, address(0), tokenId);
}
// ============ Mint Methods ============
/**
* @dev Blindly mints `tokenId` to `to`.
*/
function _mint(
address to,
uint256 tokenId
) internal virtual notZeroAddress(to) isNotToken(tokenId) {
//allow other contracts to tap into this
_beforeTokenTransfer(address(0), to, tokenId);
unchecked {
_balances[to] += 1;
_owners[tokenId] = to;
}
emit Transfer(address(0), 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);
//if smart contract
if (to.code.length > 0
//and not received
&& !_checkOnERC721Received(address(0), to, tokenId, _data)
) revert InvalidCall();
}
// ============ Transfer Methods ============
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @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.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override isApproved(from, tokenId) {
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override isApproved(from, tokenId) {
//go ahead and transfer
_transfer(from, 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.
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
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 InvalidCall();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @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.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
//see: @openzep/utils/Address.sol
if (to.code.length > 0
&& !_checkOnERC721Received(from, to, tokenId, data)
) revert InvalidCall();
}
/**
* @dev Blindly transfers `tokenId` token from `from` to `to`.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual isToken(tokenId) isOwner(tokenId, from) {
//allow other contracts to tap into this
_beforeTokenTransfer(from, to, tokenId);
unchecked {
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
}
emit Transfer(from, to, tokenId);
}
// ============ TODO Methods ============
/**
* @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
* amount - 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 _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
|
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract./
|
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(
_msgSender(), from, tokenId, _data
) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert InvalidCall();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
| 977,352 |
// SPDX-License-Identifier: GPLv2
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../DigitalaxAccessControls.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IDigitalaxRewards.sol";
import "../EIP2771/BaseRelayRecipient.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/**
* @title Digitalax Staking
* @dev Stake MONA tokens, earn MONA on the Digitalax platform
* @author DIGITALAX CORE TEAM
* @author Based on original staking contract by Adrian Guerrera (deepyr)
*/
contract DigitalaxMonaStaking is BaseRelayRecipient, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public monaToken; // MONA ERC20s
uint256 public MAX_NUMBER_OF_POOLS = 20;
uint256 constant SECONDS_IN_A_DAY = 86400;
DigitalaxAccessControls public accessControls;
IDigitalaxRewards public rewardsContract;
/**
@notice Struct to track what user is staking which tokens
@dev balance is the current ether balance of the staker
@dev lastRewardPoints is the amount of rewards (revenue) that were accumulated at the last checkpoint
@dev cycleStartTimestamp is the timestamp their cycle starts. This is only reset if someone unstakes 100% and resets. Any earnings are pro-rata if stake is increased
@dev monaRevenueRewardsEarned is the total reward for the staker till now - revenue sharing
@dev rewardsReleased is how much reward has been paid to the staker - revenue sharing
@dev isEarlyRewardsStaker is whether this staker qualifies as an early bird for extra bonus
@dev earlyRewardsEarned the amount of early rewards earned so far by staker
@dev earlyRewardsReleased is the amount of early rewards that have been released to the staker
@dev monaMintingRewardsEarned the amount of mona minted rewards earned so far by staker
@dev earlyRewardsReleased is the amount of mona minted rewardsthat have been released to the staker
@dev ethDepositRewardsEarned the amount of ETH rewards earned so far by staker
@dev ethDepositRewardsReleased is the amount of ETH rewards that have been released to the staker
*/
struct Staker {
uint256 balance;
uint256 lastRewardPoints;
uint256 lastBonusRewardPoints;
uint256 lastRewardUpdateTime;
uint256 cycleStartTimestamp;
uint256 monaRevenueRewardsPending;
uint256 bonusMonaRevenueRewardsPending;
uint256 monaRevenueRewardsEarned;
uint256 monaRevenueRewardsReleased;
bool isEarlyRewardsStaker;
}
/**
@notice Struct to track the active pools
@dev stakers is a mapping of existing stakers in the pool
@dev lastUpdateTime last time the pool was updated with rewards per token points
@dev rewardsPerTokenPoints amount of rewards overall for that pool (revenue sharing)
@dev daysInCycle the number of minimum days to stake, the length of a cycle (e.g. 30, 90, 180 days)
@dev minimumStakeInMona the minimum stake to be in the pool
@dev maximumStakeInMona the maximum stake to be in the pool
@dev maximumNumberOfStakersInPool maximum total number of stakers that can get into this pool
@dev maximumNumberOfEarlyRewardsUsers number of people that receive early rewards for staking early
@dev currentNumberOfEarlyRewardsUsers number of people that have staked early
*/
struct StakingPool {
mapping (address => Staker) stakers;
uint256 stakedMonaTotalForPool;
uint256 earlyStakedMonaTotalForPool;
uint256 lastUpdateTime;
uint256 rewardsPerTokenPoints;
uint256 bonusRewardsPerTokenPoints;
uint256 daysInCycle;
uint256 minimumStakeInMona;
uint256 maximumStakeInMona;
uint256 currentNumberOfStakersInPool;
uint256 maximumNumberOfStakersInPool;
uint256 maximumNumberOfEarlyRewardsUsers;
uint256 currentNumberOfEarlyRewardsUsers;
}
/*
* @notice mapping of Pool Id's to pools
*/
mapping (uint256 => StakingPool) pools;
uint256 public numberOfStakingPools = 0;
/*
* @notice the total mona staked over all pools
*/
uint256 public stakedMonaTotal;
uint256 public earlyStakedMonaTotal;
uint256 constant pointMultiplier = 10e32;
/*
* @notice sets the token to be claimable or not, cannot claim if it set to false
*/
bool public tokensClaimable = true;
/* ========== Events ========== */
event UpdateAccessControls(
address indexed accessControls
);
/*
* @notice event emitted when a pool is initialized
*/
event PoolInitialized(
uint256 poolId,
uint256 _daysInCycle,
uint256 _minimumStakeInMona,
uint256 _maximumStakeInMona,
uint256 _maximumNumberOfStakersInPool,
uint256 _maximumNumberOfEarlyRewardsUsers);
/*
* @notice event emitted when a user has staked a token
*/
event Staked(address indexed owner, uint256 amount);
/*
* @notice event emitted when a user has unstaked a token
*/
event Unstaked(address indexed owner, uint256 amount);
/*
* @notice event emitted when a user claims reward
*/
event MonaRevenueRewardPaid(address indexed user, uint256 reward);
event ClaimableStatusUpdated(bool status);
event EmergencyUnstake(address indexed user, uint256 amount);
event MonaTokenUpdated(address indexed oldMonaToken, address newMonaToken );
event RewardsTokenUpdated(address indexed oldRewardsToken, address newRewardsToken );
event ReclaimedERC20(address indexed token, uint256 amount);
constructor(address _monaToken, DigitalaxAccessControls _accessControls, address _trustedForwarder) public {
require(_monaToken != address(0), "DigitalaxMonaStaking: Invalid Mona Token");
require(address(_accessControls) != address(0), "DigitalaxMonaStaking: Invalid Access Controls");
monaToken = _monaToken;
accessControls = _accessControls;
trustedForwarder = _trustedForwarder;
}
receive() external payable {
require(
_msgSender() == address(rewardsContract),
"DigitalaxMonaStaking.receive: Sender must be rewards contract"
);
}
function setTrustedForwarder(address _trustedForwarder) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.setTrustedForwarder: Sender must be admin"
);
trustedForwarder = _trustedForwarder;
}
// This is to support Native meta transactions
// never use msg.sender directly, use _msgSender() instead
function _msgSender()
internal
view
returns (address payable sender)
{
return BaseRelayRecipient.msgSender();
}
/**
* Override this function.
* This version is to keep track of BaseRelayRecipient you are using
* in your contract.
*/
function versionRecipient() external view override returns (string memory) {
return "1";
}
/*
* @notice Lets admin set the Rewards Token
*/
function setRewardsContract(
address _addr
)
external
{
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.setRewardsContract: Sender must be admin"
);
require(_addr != address(0));
address oldAddr = address(rewardsContract);
rewardsContract = IDigitalaxRewards(_addr);
emit RewardsTokenUpdated(oldAddr, _addr);
}
/*
* @notice Lets admin set the max number of staking pools
*/
function setMaxNumberOfPools(
uint256 _max
)
external
{
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.setMaxNumberOfPools: Sender must be admin"
);
require(_max >= numberOfStakingPools);
MAX_NUMBER_OF_POOLS = _max;
}
/**
* @dev Single gateway to intialize the staking contract pools after deploying
* @dev Sets the contract with the MONA token
*/
function initMonaStakingPool(
uint256 _daysInCycle,
uint256 _minimumStakeInMona,
uint256 _maximumStakeInMona,
uint256 _maximumNumberOfStakersInPool,
uint256 _maximumNumberOfEarlyRewardsUsers)
external
{
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.initMonaStakingPool: Sender must be admin"
);
require(
numberOfStakingPools < MAX_NUMBER_OF_POOLS,
"DigitalaxMonaStaking.initMonaStakingPool: Contract already reached max number of supported pools"
);
require(
_daysInCycle > 0,
"DigitalaxMonaStaking.initMonaStakingPool: Must be more then one day in the cycle"
);
require(
_minimumStakeInMona > 0,
"DigitalaxMonaStaking.initMonaStakingPool: The minimum stake in Mona must be greater than zero"
);
require(
_maximumStakeInMona >= _minimumStakeInMona,
"DigitalaxMonaStaking.initMonaStakingPool: The maximum stake in Mona must be greater than or equal to the minimum stake"
);
StakingPool storage stakingPool = pools[numberOfStakingPools];
stakingPool.daysInCycle = _daysInCycle;
stakingPool.minimumStakeInMona = _minimumStakeInMona;
stakingPool.maximumStakeInMona = _maximumStakeInMona;
stakingPool.currentNumberOfStakersInPool = 0;
stakingPool.maximumNumberOfStakersInPool = _maximumNumberOfStakersInPool;
stakingPool.currentNumberOfEarlyRewardsUsers = 0;
stakingPool.maximumNumberOfStakersInPool = _maximumNumberOfStakersInPool;
stakingPool.maximumNumberOfEarlyRewardsUsers = _maximumNumberOfEarlyRewardsUsers;
stakingPool.lastUpdateTime = _getNow();
// Emit event with this pools id index, and increment the number of staking pools that exist
emit PoolInitialized(numberOfStakingPools, _daysInCycle, _minimumStakeInMona, _maximumStakeInMona, _maximumNumberOfStakersInPool, _maximumNumberOfEarlyRewardsUsers);
numberOfStakingPools = numberOfStakingPools.add(1);
}
/*
* @notice Lets admin set the Mona Token
*/
function setMonaToken(
address _addr
)
external
{
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.setMonaToken: Sender must be admin"
);
require(_addr != address(0), "DigitalaxMonaStaking.setMonaToken: Invalid Mona Token");
address oldAddr = monaToken;
monaToken = _addr;
emit MonaTokenUpdated(oldAddr, _addr);
}
/*
* @notice Lets admin set when tokens are claimable
*/
function setTokensClaimable(
bool _enabled
)
external
{
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.setTokensClaimable: Sender must be admin"
);
tokensClaimable = _enabled;
emit ClaimableStatusUpdated(_enabled);
}
/**
@notice Method for updating the access controls contract used by the NFT
@dev Only admin
@param _accessControls Address of the new access controls contract (Cannot be zero address)
*/
function updateAccessControls(DigitalaxAccessControls _accessControls) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.updateAccessControls: Sender must be admin"
);
require(address(_accessControls) != address(0), "DigitalaxMonaStaking.updateAccessControls: Zero Address");
accessControls = _accessControls;
emit UpdateAccessControls(address(_accessControls));
}
/* @notice Getter functions for Staking contract
* @dev Get the tokens staked by a user
*/
function getStakedBalance(
uint256 _poolId,
address _user
)
external
view
returns (uint256 balance)
{
return pools[_poolId].stakers[_user].balance;
}
/*
* @dev Get the total ETH staked (all pools)
*/
function stakedMonaInPool(uint256 _poolId)
external
view
returns (uint256)
{
return pools[_poolId].stakedMonaTotalForPool;
}
/*
* @dev Get the total ETH staked (all pools early stakers)
*/
function earlyStakedMonaInPool(uint256 _poolId)
external
view
returns (uint256)
{
return pools[_poolId].earlyStakedMonaTotalForPool;
}
/*
* @dev Get the total ETH staked (all pools)
*/
function stakedEthTotal()
external
view
returns (uint256)
{
uint256 monaPerEth = getMonaTokenPerEthUnit(1e18);
return stakedMonaTotal.mul(1e18).div(monaPerEth);
}
/*
* @dev Get the total early ETH staked (all pools)
*/
function earlyStakedEthTotal()
external
view
returns (uint256)
{
uint256 monaPerEth = getMonaTokenPerEthUnit(1e18);
return earlyStakedMonaTotal.mul(1e18).div(monaPerEth);
}
/*
* @dev Get the total ETH staked (all pools)
*/
function stakedEthTotalByPool(uint256 _poolId)
external
view
returns (uint256)
{
uint256 monaPerEth = getMonaTokenPerEthUnit(1e18);
return pools[_poolId].stakedMonaTotalForPool.mul(1e18).div(monaPerEth);
}
/*
* @dev Get the total ETH staked (all pools)
*/
function earlyStakedEthTotalByPool(uint256 _poolId)
external
view
returns (uint256)
{
uint256 monaPerEth = getMonaTokenPerEthUnit(1e18);
return pools[_poolId].earlyStakedMonaTotalForPool.mul(1e18).div(monaPerEth);
}
/*
* @notice Stake MONA Tokens and earn rewards.
*/
function stake(
uint256 _poolId,
uint256 _amount
)
external
{
_stake(_poolId, _msgSender(), _amount);
}
/*
* @notice Stake All MONA Tokens in your wallet and earn rewards.
*/
function stakeAll(uint256 _poolId)
external
{
uint256 balance = IERC20(monaToken).balanceOf(_msgSender());
_stake(_poolId, _msgSender(), balance);
}
/**
* @dev All the staking goes through this function
* @dev Rewards to be given out is calculated
* @dev Balance of stakers are updated as they stake the nfts based on ether price
*/
function _stake(
uint256 _poolId,
address _user,
uint256 _amount
)
internal
{
require(
_amount > 0 ,
"DigitalaxMonaStaking._stake: Staked amount must be greater than 0"
);
StakingPool storage stakingPool = pools[_poolId];
Staker storage staker = stakingPool.stakers[_user];
require(
staker.balance.add(_amount) >= stakingPool.minimumStakeInMona,
"DigitalaxMonaStaking._stake: Staked amount must be greater than or equal to minimum stake"
);
require(
staker.balance.add(_amount) <= stakingPool.maximumStakeInMona,
"DigitalaxMonaStaking._stake: Staked amount must be less than or equal to maximum stake"
);
// Check if a new user
if(staker.lastRewardUpdateTime == 0 && staker.balance == 0) {
require(
stakingPool.currentNumberOfStakersInPool < stakingPool.maximumNumberOfStakersInPool,
"DigitalaxMonaStaking._stake: This pool is already full"
);
stakingPool.currentNumberOfStakersInPool = stakingPool.currentNumberOfStakersInPool.add(1);
// Check if an early staker
if(stakingPool.currentNumberOfEarlyRewardsUsers < stakingPool.maximumNumberOfEarlyRewardsUsers){
stakingPool.currentNumberOfEarlyRewardsUsers = stakingPool.currentNumberOfEarlyRewardsUsers.add(1);
staker.isEarlyRewardsStaker = true;
} else {
staker.isEarlyRewardsStaker = false;
}
}
if(staker.balance == 0) {
staker.cycleStartTimestamp = _getNow();
if (staker.lastRewardPoints == 0 ) {
staker.lastRewardPoints = stakingPool.rewardsPerTokenPoints;
}
if(staker.isEarlyRewardsStaker && (staker.lastBonusRewardPoints == 0)){
staker.lastBonusRewardPoints = stakingPool.bonusRewardsPerTokenPoints;
}
}
updateReward(_poolId, _user);
staker.balance = staker.balance.add(_amount);
stakedMonaTotal = stakedMonaTotal.add(_amount);
stakingPool.stakedMonaTotalForPool = stakingPool.stakedMonaTotalForPool.add(_amount);
if(staker.isEarlyRewardsStaker){
earlyStakedMonaTotal = earlyStakedMonaTotal.add(_amount);
stakingPool.earlyStakedMonaTotalForPool = stakingPool.earlyStakedMonaTotalForPool.add(_amount);
}
IERC20(monaToken).safeTransferFrom(
address(_user),
address(this),
_amount
);
emit Staked(_user, _amount);
}
/*
* @notice Unstake MONA Tokens.
*/
function unstake(
uint256 _poolId,
uint256 _amount
)
external
{
_unstake(_poolId, _msgSender(), _amount);
}
/**
* @dev All the unstaking goes through this function
* @dev Rewards to be given out is calculated
* @dev Balance of stakers are updated as they unstake the nfts based on ether price
*/
function _unstake(
uint256 _poolId,
address _user,
uint256 _amount
)
internal
{
require(
pools[_poolId].stakers[_user].balance >= _amount,
"DigitalaxMonaStaking._unstake: Sender must have staked tokens"
);
_claimReward(_poolId, _user);
Staker storage staker = pools[_poolId].stakers[_user];
staker.balance = staker.balance.sub(_amount);
stakedMonaTotal = stakedMonaTotal.sub(_amount);
pools[_poolId].stakedMonaTotalForPool = pools[_poolId].stakedMonaTotalForPool.sub(_amount);
if(staker.isEarlyRewardsStaker){
earlyStakedMonaTotal = earlyStakedMonaTotal.sub(_amount);
pools[_poolId].earlyStakedMonaTotalForPool = pools[_poolId].earlyStakedMonaTotalForPool.sub(_amount);
}
if (staker.balance == 0) {
delete pools[_poolId].stakers[_user]; // TODO figure out if this is still valid
}
uint256 tokenBal = IERC20(monaToken).balanceOf(address(this));
if (_amount > tokenBal) {
IERC20(monaToken).safeTransfer(address(_user), tokenBal);
} else {
IERC20(monaToken).safeTransfer(address(_user), _amount);
}
emit Unstaked(_user, _amount);
}
/*
* @notice Unstake without caring about rewards. EMERGENCY ONLY.
*/
function emergencyUnstake(uint256 _poolId)
external
{
uint256 amount = pools[_poolId].stakers[_msgSender()].balance;
pools[_poolId].stakers[_msgSender()].balance = 0;
pools[_poolId].stakers[_msgSender()].monaRevenueRewardsEarned = 0;
IERC20(monaToken).safeTransfer(address(_msgSender()), amount);
emit EmergencyUnstake(_msgSender(), amount);
}
/*
* @dev Updates the amount of rewards owed for each user before any tokens are moved
*/
function updateReward(
uint256 _poolId,
address _user
)
public
{
StakingPool storage stakingPool = pools[_poolId];
require(stakingPool.daysInCycle > 0, "DigitalaxMonaStaking.updateRewards: This pool has not been instantiated");
// 1 Updates the amount of rewards, transfer MONA to this contract so there is some balance
rewardsContract.updateRewards(_poolId);
// 2 Calculates the overall amount of mona revenue that has increased since the last time someone called this method
uint256 monaRewards = rewardsContract.MonaRevenueRewards(_poolId, stakingPool.lastUpdateTime,
_getNow());
// Continue if there is mona in this pool
if (stakingPool.stakedMonaTotalForPool > 0) {
// 3 Update the overall rewards per token points with the new mona rewards
stakingPool.rewardsPerTokenPoints = stakingPool.rewardsPerTokenPoints.add(monaRewards
.mul(1e18)
.mul(pointMultiplier)
.div(stakingPool.stakedMonaTotalForPool));
}
// 2 Calculates the bonus overall amount of mona revenue that has increased since the last time someone called this method
uint256 bonusMonaRewards = rewardsContract.BonusMonaRevenueRewards(_poolId, stakingPool.lastUpdateTime, _getNow());
// Continue if there is mona in this pool
if (stakingPool.earlyStakedMonaTotalForPool > 0) {
// 3 Update the overall rewards per token points with the new mona rewards
stakingPool.bonusRewardsPerTokenPoints = stakingPool.bonusRewardsPerTokenPoints.add(bonusMonaRewards
.mul(1e18)
.mul(pointMultiplier)
.div(stakingPool.earlyStakedMonaTotalForPool));
}
// 4 Update the last update time for this pool, calculating overall rewards
stakingPool.lastUpdateTime = _getNow();
// 5 Calculate the rewards owing overall for this user
uint256 rewards = rewardsOwing(_poolId, _user);
// There are 2 states.
// 1. We are in the same cycle and need to add pending rewards,
// 2. If we are in a new cycle, all pending rewards get added to monaRevenueRewardsEarned
// If we are in a new cycle, we will add subtract from the last cycle start until now
// to see what is new pending rewards and what is monaRevenueRewardsEarned
Staker storage staker = stakingPool.stakers[_user];
uint256 bonusRewards = 0;
if(staker.isEarlyRewardsStaker){
bonusRewards = bonusRewardsOwing(_poolId, _user);
}
uint256 secondsInCycle = stakingPool.daysInCycle.mul(SECONDS_IN_A_DAY);
uint256 timeElapsedSinceStakingFromZero = _getNow().sub(staker.cycleStartTimestamp);
uint256 startOfCurrentCycle = _getNow().sub(timeElapsedSinceStakingFromZero.mod(secondsInCycle));
if (_user != address(0)) {
// Check what state we are in TODO check this next line closely for accuracy of when cycle starts
if(startOfCurrentCycle > staker.lastRewardUpdateTime) {
// We are in a new cycle
// Bring over the pending rewards, they have been earned
rewards = rewards.add(staker.monaRevenueRewardsPending);
bonusRewards = bonusRewards.add(staker.bonusMonaRevenueRewardsPending);
uint256 monaPendingRewardsTotal = rewardsContract.MonaRevenueRewards(_poolId, startOfCurrentCycle,
_getNow()).mul(1e18);
uint256 pendingRewardsThisCycle = staker.balance.mul(monaPendingRewardsTotal);
pendingRewardsThisCycle = pendingRewardsThisCycle.div(stakingPool.stakedMonaTotalForPool);
// In case it overflows
pendingRewardsThisCycle = pendingRewardsThisCycle.div(1e18);
staker.monaRevenueRewardsPending = pendingRewardsThisCycle;
rewards = rewards.sub(pendingRewardsThisCycle);
// Set rewards (This includes old pending rewards and does not include new pending rewards)
staker.monaRevenueRewardsEarned = staker.monaRevenueRewardsEarned.add(rewards);
// Early staker
if(staker.isEarlyRewardsStaker){
uint256 bonusMonaPendingRewardsTotal = rewardsContract.BonusMonaRevenueRewards(_poolId, startOfCurrentCycle,
_getNow());
bonusMonaPendingRewardsTotal = bonusMonaPendingRewardsTotal.mul(1e18);
uint256 bonusPendingRewardsThisCycle = staker.balance.mul(bonusMonaPendingRewardsTotal);
bonusPendingRewardsThisCycle = bonusPendingRewardsThisCycle.div(stakingPool.earlyStakedMonaTotalForPool);
bonusPendingRewardsThisCycle = bonusPendingRewardsThisCycle.div(1e18);
staker.bonusMonaRevenueRewardsPending = bonusPendingRewardsThisCycle;
bonusRewards = bonusRewards.sub(bonusPendingRewardsThisCycle);
staker.monaRevenueRewardsEarned = staker.monaRevenueRewardsEarned.add(bonusRewards);
}
staker.lastRewardPoints = stakingPool.rewardsPerTokenPoints;
staker.lastRewardUpdateTime = _getNow();
} else {
// We are still in the same cycle as the last reward update, add rewards then bonus rewards
staker.monaRevenueRewardsPending = staker.monaRevenueRewardsPending.add(rewards);
if(staker.isEarlyRewardsStaker){
staker.bonusMonaRevenueRewardsPending = staker.monaRevenueRewardsPending.add(bonusRewards);
staker.lastBonusRewardPoints = stakingPool.bonusRewardsPerTokenPoints;
}
staker.lastRewardPoints = stakingPool.rewardsPerTokenPoints;
staker.lastRewardUpdateTime = _getNow();
}
}
}
/*
* @dev The rewards are dynamic and normalised from the other pools
* @dev This gets the rewards from each of the periods as one multiplier
*/
function rewardsOwing(
uint256 _poolId,
address _user
)
public
view
returns(uint256)
{
uint256 newRewardPerToken = pools[_poolId].rewardsPerTokenPoints.sub(pools[_poolId].stakers[_user].lastRewardPoints);
uint256 rewards = pools[_poolId].stakers[_user].balance.mul(newRewardPerToken)
.div(1e18)
.div(pointMultiplier);
return rewards;
}
/*
* @dev The bonus rewards are dynamic and normalised from the other pools
* @dev This gets the rewards from each of the periods as one multiplier
*/
function bonusRewardsOwing(
uint256 _poolId,
address _user
)
public
view
returns(uint256)
{
uint256 newRewardPerToken = pools[_poolId].bonusRewardsPerTokenPoints.sub(pools[_poolId].stakers[_user].lastBonusRewardPoints);
uint256 bonusRewards = pools[_poolId].stakers[_user].balance.mul(newRewardPerToken)
.div(1e18)
.div(pointMultiplier);
return bonusRewards;
}
/*
* @notice Returns the about of rewards yet to be claimed (this currently includes pending and awarded together
* @param _poolId the id of the pool we are interested in
* @param _user the user we are interested in
* @dev returns the claimable rewards and pending rewards
*/
// TODO stack too deep
function unclaimedRewards(
uint256 _poolId,
address _user
)
public
view
returns(uint256 claimableRewards, uint256 pendingRewards)
{
StakingPool storage stakingPool = pools[_poolId];
if (stakingPool.stakedMonaTotalForPool == 0) {
return (0,0);
}
Staker storage staker = stakingPool.stakers[_user];
uint256 monaRewards = rewardsContract.MonaRevenueRewards(_poolId, stakingPool.lastUpdateTime,
_getNow());
uint256 newRewardPerToken = stakingPool.rewardsPerTokenPoints.add(monaRewards
.mul(1e18)
.mul(pointMultiplier)
.div(stakingPool.stakedMonaTotalForPool))
.sub(staker.lastRewardPoints);
uint256 newRewards = staker.balance.mul(newRewardPerToken)
.div(1e18)
.div(pointMultiplier);
// Figure out how much rewards are still pending
uint256 secondsInCycle = stakingPool.daysInCycle.mul(SECONDS_IN_A_DAY);
uint256 timeElapsedSinceStakingFromZero = _getNow().sub(staker.cycleStartTimestamp);
uint256 startOfCurrentCycle = _getNow().sub(timeElapsedSinceStakingFromZero.mod(secondsInCycle));
if(startOfCurrentCycle > staker.lastRewardUpdateTime) {
// We are in a new cycle
// Bring over the pending rewards, they have been earned
newRewards = newRewards.add(staker.monaRevenueRewardsEarned);
newRewards = newRewards.sub(staker.monaRevenueRewardsReleased);
// New cycle, the pending rewards from before move over
newRewards = newRewards.add(staker.monaRevenueRewardsPending);
uint256 monaPendingRewardsTotal = rewardsContract.MonaRevenueRewards(_poolId, startOfCurrentCycle,
_getNow());
monaPendingRewardsTotal = monaPendingRewardsTotal.mul(1e18);
pendingRewards = staker.balance.mul(monaPendingRewardsTotal);
pendingRewards = pendingRewards.div(stakingPool.stakedMonaTotalForPool);
// The pending rewards are now just what is in this cycle (calculation in case it overflows)
pendingRewards = pendingRewards.div(1e18);
claimableRewards = newRewards.sub(pendingRewards);
} else {
// We are in the same cycle, these new rewards calculated above are pending rewards. So no change to claimable rewards
claimableRewards = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased);
// The new rewards we calculated earlier are in the same cycle
pendingRewards = newRewards.add(staker.monaRevenueRewardsPending);
}
}
/*
* @notice Returns the about of rewards yet to be claimed for bonuses (this currently includes pending and awarded together)
* @param _poolId the id of the pool we are interested in
* @param _user the user we are interested in
* @dev returns the claimable rewards and pending rewards
*/
// TODO stack too deep
function unclaimedBonusRewards(
uint256 _poolId,
address _user
)
public
view
returns(uint256 claimableRewards, uint256 pendingRewards)
{
StakingPool storage stakingPool = pools[_poolId];
Staker storage staker = stakingPool.stakers[_user];
if (stakingPool.stakedMonaTotalForPool == 0 || !staker.isEarlyRewardsStaker) {
return (0,0);
}
uint256 monaBonusRewards = rewardsContract.BonusMonaRevenueRewards(_poolId, stakingPool.lastUpdateTime, _getNow());
uint256 newBonusRewardPerToken = stakingPool.bonusRewardsPerTokenPoints;
newBonusRewardPerToken = newBonusRewardPerToken.add(monaBonusRewards.mul(1e18).mul(pointMultiplier).div(stakingPool.earlyStakedMonaTotalForPool));
newBonusRewardPerToken = newBonusRewardPerToken.sub(staker.lastBonusRewardPoints);
uint256 newBonusRewards = staker.balance.mul(newBonusRewardPerToken);
newBonusRewards = newBonusRewards.div(1e18);
newBonusRewards = newBonusRewards.div(pointMultiplier);
// Figure out how much rewards are still pending
uint256 secondsInCycle = stakingPool.daysInCycle.mul(SECONDS_IN_A_DAY);
uint256 timeElapsedSinceStakingFromZero = _getNow().sub(staker.cycleStartTimestamp);
uint256 startOfCurrentCycle = _getNow().sub(timeElapsedSinceStakingFromZero.mod(secondsInCycle));
if(startOfCurrentCycle > staker.lastRewardUpdateTime) {
// We are in a new cycle
// Bring over the pending rewards, they have been earned
newBonusRewards = newBonusRewards.add(staker.bonusMonaRevenueRewardsPending);
uint256 bonusMonaPendingRewardsTotal = 0;
bonusMonaPendingRewardsTotal = rewardsContract.BonusMonaRevenueRewards(_poolId, startOfCurrentCycle, _getNow());
bonusMonaPendingRewardsTotal = bonusMonaPendingRewardsTotal.mul(1e18);
uint256 bonusPendingRewards = staker.balance.mul(bonusMonaPendingRewardsTotal);
bonusPendingRewards = bonusPendingRewards.div(stakingPool.earlyStakedMonaTotalForPool);
// The pending rewards are now just what is in this cycle (calculation in case it overflows)
bonusPendingRewards = bonusPendingRewards.div(1e18);
uint256 bonusClaimable = newBonusRewards.sub(bonusPendingRewards);
pendingRewards = bonusPendingRewards;
claimableRewards = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased);
claimableRewards = claimableRewards.add(bonusClaimable);
} else {
// We are in the same cycle, these new rewards calculated above are pending rewards. So no change to claimable rewards
claimableRewards = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased);
// The new rewards we calculated earlier are in the same cycle
pendingRewards = newBonusRewards.add(staker.bonusMonaRevenueRewardsPending);
}
}
/*
* @notice Lets a user with rewards owing to claim tokens
*/
function claimReward(uint256 _poolId) external {
_claimReward(_poolId, _msgSender());
}
/**
@notice Internal method for claimReward.
*/
function _claimReward(
uint256 _poolId,
address _user
) internal {
require(
tokensClaimable == true,
"Tokens cannnot be claimed yet"
);
updateReward(_poolId, _user);
Staker storage staker = pools[_poolId].stakers[_user];
uint256 payableAmount = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased);
staker.monaRevenueRewardsReleased = staker.monaRevenueRewardsReleased.add(payableAmount);
/// @dev accounts for dust
uint256 rewardBal = IERC20(monaToken).balanceOf(address(this));
if (payableAmount > rewardBal) {
payableAmount = rewardBal;
}
IERC20(monaToken).transfer(_user, payableAmount);
emit MonaRevenueRewardPaid(_user, payableAmount);
}
function getMonaTokenPerEthUnit(uint ethAmt) public view returns (uint liquidity){
return rewardsContract.getMonaPerEth(1e18);
}
function min(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a <= b ? a : b;
}
function _getNow() internal virtual view returns (uint256) {
return block.timestamp;
}
/* ========== Recover ERC20 ========== */
/*
* @notice allows for the recovery of incorrect ERC20 tokens sent to contract
*/
function reclaimERC20(
address _tokenAddress,
uint256 _tokenAmount
)
external
{
// Cannot recover the staking token or the rewards token
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.reclaimERC20: Sender must be admin"
);
require(
_tokenAddress != address(monaToken),
"DigitalaxMonaStaking.reclaimERC20: Cannot withdraw the rewards token"
);
IERC20(_tokenAddress).transfer(_msgSender(), _tokenAmount);
emit ReclaimedERC20(_tokenAddress, _tokenAmount);
}
/**
* @notice EMERGENCY Recovers ETH, drains all ETH sitting on the smart contract
* @dev Only access controls admin can access
*/
function reclaimETH(uint256 _amount) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.reclaimETH: Sender must be admin"
);
_msgSender().transfer(address(this).balance);
}
}
|
Lets admin set the Mona Token/
|
function setMonaToken(
address _addr
)
external
{
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMonaStaking.setMonaToken: Sender must be admin"
);
require(_addr != address(0), "DigitalaxMonaStaking.setMonaToken: Invalid Mona Token");
address oldAddr = monaToken;
monaToken = _addr;
emit MonaTokenUpdated(oldAddr, _addr);
}
| 12,801,886 |
./full_match/4/0xB4b58210DC03c1A29021B296D80E17aD46427393/sources/contracts/base/ERC721.sol
|
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');
}
| 769,871 |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
interface DharmaTradeReserveV5Interface {
event ROLEMODIFIED441(Role indexed role, address account); //inject NONSTANDARD NAMING
event ROLEPAUSED231(Role indexed role); //inject NONSTANDARD NAMING
event ROLEUNPAUSED960(Role indexed role); //inject NONSTANDARD NAMING
event ETHERRECEIVED44(address sender, uint256 amount); //inject NONSTANDARD NAMING
enum Role { // #
DEPOSIT_MANAGER, // 0
ADJUSTER, // 1
WITHDRAWAL_MANAGER, // 2
RESERVE_TRADER, // 3
PAUSER // 4
}
struct RoleStatus {
address account;
bool paused;
}
function TRADEDAIFORETHER831( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAI150( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function TRADEDAIFORTOKEN796( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAI354( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought);
function TRADEDAIFORETHERUSINGRESERVES632( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI477( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADEDAIFORTOKENUSINGRESERVES160( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI443( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function FINALIZEETHERDEPOSIT112( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external;
function FINALIZEDAIDEPOSIT982( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external;
function FINALIZEDHARMADAIDEPOSIT983( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external;
function MINT439(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function REDEEM267(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC791( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount, uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function TRADEUSDCFORDDAI490( //inject NONSTANDARD NAMING
uint256 usdcAmount, uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function WITHDRAWUSDC225(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAI871(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDHARMADAI182(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWUSDCTOPRIMARYRECIPIENT429(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAITOPRIMARYRECIPIENT980(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWETHER987( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external;
function WITHDRAW561( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external returns (bool success);
function CALLANY447( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external returns (bool ok, bytes memory returnData);
function SETDAILIMIT819(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETETHERLIMIT192(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETPRIMARYUSDCRECIPIENT853(address recipient) external; //inject NONSTANDARD NAMING
function SETPRIMARYDAIRECIPIENT291(address recipient) external; //inject NONSTANDARD NAMING
function SETROLE200(Role role, address account) external; //inject NONSTANDARD NAMING
function REMOVEROLE179(Role role) external; //inject NONSTANDARD NAMING
function PAUSE944(Role role) external; //inject NONSTANDARD NAMING
function UNPAUSE758(Role role) external; //inject NONSTANDARD NAMING
function ISPAUSED720(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING
function ISROLE342(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING
function ISDHARMASMARTWALLET39( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet);
function GETDEPOSITMANAGER376() external view returns (address depositManager); //inject NONSTANDARD NAMING
function GETADJUSTER193() external view returns (address adjuster); //inject NONSTANDARD NAMING
function GETRESERVETRADER467() external view returns (address reserveTrader); //inject NONSTANDARD NAMING
function GETWITHDRAWALMANAGER690() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING
function GETPAUSER338() external view returns (address pauser); //inject NONSTANDARD NAMING
function GETRESERVES367() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
);
function GETDAILIMIT285() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
);
function GETETHERLIMIT400() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING
function GETPRIMARYUSDCRECIPIENT588() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETPRIMARYDAIRECIPIENT262() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETIMPLEMENTATION10() external view returns (address implementation); //inject NONSTANDARD NAMING
function GETVERSION332() external view returns (uint256 version); //inject NONSTANDARD NAMING
}
interface ERC20Interface {
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE776(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE300(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER681(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM400(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING
}
interface DTokenInterface {
function MINT439(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
function REDEEM267(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING590(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING496(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER681(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE776(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function EXCHANGERATECURRENT187() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface TradeHelperInterface {
function TRADEUSDCFORDDAI490(uint256 amountUSDC, uint256 quotedDaiEquivalentAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC791(uint256 amountDai, uint256 quotedUSDCAmount) external returns (uint256 usdcReceived); //inject NONSTANDARD NAMING
function GETEXPECTEDDAI516(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING
function GETEXPECTEDUSDC789(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING
}
interface UniswapV1Interface {
function ETHTOTOKENSWAPINPUT868( //inject NONSTANDARD NAMING
uint256 minTokens, uint256 deadline
) external payable returns (uint256 tokensBought);
function TOKENTOETHTRANSFEROUTPUT757( //inject NONSTANDARD NAMING
uint256 ethBought, uint256 maxTokens, uint256 deadline, address recipient
) external returns (uint256 tokensSold);
}
interface UniswapV2Interface {
function SWAPTOKENSFOREXACTTOKENS12( //inject NONSTANDARD NAMING
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPEXACTTOKENSFORTOKENS249( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface EtherReceiverInterface {
function SETTLEETHER953() external; //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD482(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function MUL891(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 DIV332(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
contract TwoStepOwnable {
event OWNERSHIPTRANSFERRED446( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
function TRANSFEROWNERSHIP849(address newOwner) external ONLYOWNER739 { //inject NONSTANDARD NAMING
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
function CANCELOWNERSHIPTRANSFER3() external ONLYOWNER739 { //inject NONSTANDARD NAMING
delete _newPotentialOwner;
}
function ACCEPTOWNERSHIP151() external { //inject NONSTANDARD NAMING
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OWNERSHIPTRANSFERRED446(_owner, msg.sender);
_owner = msg.sender;
}
function OWNER633() external view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
function ISOWNER526() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
modifier ONLYOWNER739() { //inject NONSTANDARD NAMING
require(ISOWNER526(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
contract DharmaTradeReserveV5ImplementationStaging is DharmaTradeReserveV5Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a "primary recipient" the withdrawal manager can transfer Dai to.
address private _primaryDaiRecipient;
// Maintain a "primary recipient" the withdrawal manager can transfer USDC to.
address private _primaryUSDCRecipient;
// Maintain a maximum allowable transfer size (in Dai) for the deposit manager.
uint256 private _daiLimit;
// Maintain a maximum allowable transfer size (in Ether) for the deposit manager.
uint256 private _etherLimit;
bool private _originatesFromReserveTrader; // unused, don't change storage layout
uint256 private constant _version870 = 5; //inject NONSTANDARD NAMING
// This contract interacts with USDC, Dai, and Dharma Dai.
ERC20Interface internal constant _usdc497 = ERC20Interface( //inject NONSTANDARD NAMING
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ERC20Interface internal constant _dai122 = ERC20Interface( //inject NONSTANDARD NAMING
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
DTokenInterface internal constant _ddai891 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000001876eB1444c986fD502e618c587430
);
TradeHelperInterface internal constant _trade_helper741 = TradeHelperInterface( //inject NONSTANDARD NAMING
0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d
);
UniswapV1Interface internal constant _uniswap_dai582 = UniswapV1Interface( //inject NONSTANDARD NAMING
0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667
);
UniswapV2Interface internal constant _uniswap_router975 = UniswapV2Interface( //inject NONSTANDARD NAMING
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
EtherReceiverInterface internal constant _eth_receiver919 = EtherReceiverInterface( //inject NONSTANDARD NAMING
0xaf84687D21736F5E06f738c6F065e88890465E7c
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _create2_header355 = bytes21( //inject NONSTANDARD NAMING
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _wallet_creation_code_header592 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING
bytes28 internal constant _wallet_creation_code_footer939 = bytes28( //inject NONSTANDARD NAMING
0x00000000000000000000000000000000000000000000000000000000
);
// Include a payable fallback so that the contract can receive Ether payments.
function () external payable {
emit ETHERRECEIVED44(msg.sender, msg.value);
}
function INITIALIZE936() external { //inject NONSTANDARD NAMING
// Approve Uniswap router to transfer Dai on behalf of this contract.
if (_dai122.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) {
bool ok = _dai122.APPROVE776(address(_uniswap_router975), uint256(-1));
require(ok, "Dai approval for Uniswap router failed.");
}
}
function TRADEDAIFORETHER831( //inject NONSTANDARD NAMING
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
bool ok = (_dai122.TRANSFERFROM400(msg.sender, address(this), daiAmount));
require(ok, "Dai transfer in failed.");
// Trade the Dai for the quoted Ether amount on Uniswap and send to caller.
totalDaiSold = _uniswap_dai582.TOKENTOETHTRANSFEROUTPUT757(
quotedEtherAmount, daiAmount, deadline, msg.sender
);
}
function TRADEDAIFORTOKEN796( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
bool ok = (_dai122.TRANSFERFROM400(msg.sender, address(this), daiAmount));
require(ok, "Dai transfer in failed.");
// Establish a direct path (for now) between Dai and the target token.
address[] memory path = new address[](2);
path[0] = address(_dai122);
path[1] = token;
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12(
quotedTokenAmount, daiAmount, path, msg.sender, deadline
);
totalDaiSold = amounts[0];
}
function TRADEDAIFORETHERUSINGRESERVES632( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai122.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai891.REDEEMUNDERLYING590(additionalDaiRequired);
}
// Trade the Dai for the quoted Ether amount on Uniswap.
totalDaiSold = _uniswap_dai582.TOKENTOETHTRANSFEROUTPUT757(
quotedEtherAmount,
daiAmountFromReserves,
deadline,
address(_eth_receiver919)
);
// Move the Ether from the receiver to this contract (gas workaround).
_eth_receiver919.SETTLEETHER953();
}
function TRADEETHERFORDAI150( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai582.ETHTOTOKENSWAPINPUT868.value(msg.value)(
quotedDaiAmount, deadline
);
// Transfer the Dai to the caller and revert on failure.
bool ok = (_dai122.TRANSFER681(msg.sender, quotedDaiAmount));
require(ok, "Dai transfer out failed.");
}
function TRADETOKENFORDAI354( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought) {
// Transfer the token from the caller and revert on failure.
bool ok = (token.TRANSFERFROM400(msg.sender, address(this), tokenAmount));
require(ok, "Token transfer in failed.");
// Approve Uniswap router to transfer tokens on behalf of this contract.
if (token.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) {
ok = token.APPROVE776(address(_uniswap_router975), uint256(-1));
require(ok, "Token approval for Uniswap router failed.");
}
// Establish a direct path (for now) between the target token and Dai.
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(_dai122);
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPEXACTTOKENSFORTOKENS249(
tokenAmount, quotedDaiAmount, path, msg.sender, deadline
);
totalDaiBought = amounts[1];
// Transfer the Dai to the caller and revert on failure.
ok = (_dai122.TRANSFER681(msg.sender, quotedDaiAmount));
require(ok, "Dai transfer out failed.");
}
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI477( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai582.ETHTOTOKENSWAPINPUT868.value(
etherAmountFromReserves
)(
quotedDaiAmount, deadline
);
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai891.MINT439(totalDaiBought);
}
function TRADEDAIFORTOKENUSINGRESERVES160( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai122.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai891.REDEEMUNDERLYING590(additionalDaiRequired);
}
// Establish a direct path (for now) between Dai and the target token.
address[] memory path = new address[](2);
path[0] = address(_dai122);
path[1] = token;
// Trade the Dai for the quoted token amount on Uniswap.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12(
quotedTokenAmount, daiAmountFromReserves, path, address(this), deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI443( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
if (token.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) {
bool ok = token.APPROVE776(address(_uniswap_router975), uint256(-1));
require(ok, "Token approval for Uniswap router failed.");
}
// Establish a direct path (for now) between the target token and Dai.
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(_dai122);
// Trade the Dai for the quoted token amount on Uniswap.
uint256[] memory amounts = new uint256[](2);
amounts = _uniswap_router975.SWAPEXACTTOKENSFORTOKENS249(
tokenAmountFromReserves, quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai891.MINT439(totalDaiBought);
}
function FINALIZEDAIDEPOSIT982( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_ISSMARTWALLET802(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the Dai to the specified smart wallet.
require(_dai122.TRANSFER681(smartWallet, daiAmount), "Dai transfer failed.");
}
function FINALIZEDHARMADAIDEPOSIT983( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_ISSMARTWALLET802(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Get the current dDai exchange rate.
uint256 exchangeRate = _ddai891.EXCHANGERATECURRENT187();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Could not retrieve dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.MUL891(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the dDai to the specified smart wallet.
require(_ddai891.TRANSFER681(smartWallet, dDaiAmount), "dDai transfer failed.");
}
function FINALIZEETHERDEPOSIT112( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_ISSMARTWALLET802(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Ensure that the amount to transfer is lower than the limit.
require(etherAmount < _etherLimit, "Transfer size exceeds the limit.");
// Transfer the Ether to the specified smart wallet.
bool ok;
(ok, ) = smartWallet.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function MINT439( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _ddai891.MINT439(daiAmount);
}
function REDEEM267( //inject NONSTANDARD NAMING
uint256 dDaiAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 daiReceived) {
// Redeem the specified amount of dDai for Dai.
daiReceived = _ddai891.REDEEM267(dDaiAmount);
}
function TRADEUSDCFORDDAI490( //inject NONSTANDARD NAMING
uint256 usdcAmount,
uint256 quotedDaiEquivalentAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 dDaiMinted) {
dDaiMinted = _trade_helper741.TRADEUSDCFORDDAI490(
usdcAmount, quotedDaiEquivalentAmount
);
}
function TRADEDDAIFORUSDC791( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount,
uint256 quotedUSDCAmount
) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 usdcReceived) {
usdcReceived = _trade_helper741.TRADEDDAIFORUSDC791(
daiEquivalentAmount, quotedUSDCAmount
);
}
function WITHDRAWUSDCTOPRIMARYRECIPIENT429( //inject NONSTANDARD NAMING
uint256 usdcAmount
) external ONLYOWNEROR153(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryUSDCRecipient;
require(
primaryRecipient != address(0), "No USDC primary recipient currently set."
);
// Transfer the supplied USDC amount to the primary recipient.
bool ok = _usdc497.TRANSFER681(primaryRecipient, usdcAmount);
require(ok, "USDC transfer failed.");
}
function WITHDRAWDAITOPRIMARYRECIPIENT980( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR153(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryDaiRecipient;
require(
primaryRecipient != address(0), "No Dai primary recipient currently set."
);
// Transfer the supplied Dai amount to the primary recipient.
bool ok = _dai122.TRANSFER681(primaryRecipient, daiAmount);
require(ok, "Dai transfer failed.");
}
function WITHDRAWUSDC225( //inject NONSTANDARD NAMING
address recipient, uint256 usdcAmount
) external ONLYOWNER739 {
// Transfer the USDC to the specified recipient.
require(_usdc497.TRANSFER681(recipient, usdcAmount), "USDC transfer failed.");
}
function WITHDRAWDAI871( //inject NONSTANDARD NAMING
address recipient, uint256 daiAmount
) external ONLYOWNER739 {
// Transfer the Dai to the specified recipient.
require(_dai122.TRANSFER681(recipient, daiAmount), "Dai transfer failed.");
}
function WITHDRAWDHARMADAI182( //inject NONSTANDARD NAMING
address recipient, uint256 dDaiAmount
) external ONLYOWNER739 {
// Transfer the dDai to the specified recipient.
require(_ddai891.TRANSFER681(recipient, dDaiAmount), "dDai transfer failed.");
}
function WITHDRAWETHER987( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external ONLYOWNER739 {
bool ok;
// Transfer the Ether to the specified recipient.
(ok, ) = recipient.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function WITHDRAW561( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external ONLYOWNER739 returns (bool success) {
// Transfer the token to the specified recipient.
success = token.TRANSFER681(recipient, amount);
}
function CALLANY447( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external ONLYOWNER739 returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
function SETDAILIMIT819(uint256 daiAmount) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new limit.
_daiLimit = daiAmount;
}
function SETETHERLIMIT192(uint256 etherAmount) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new limit.
_etherLimit = etherAmount;
}
function SETPRIMARYUSDCRECIPIENT853(address recipient) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryUSDCRecipient = recipient;
}
function SETPRIMARYDAIRECIPIENT291(address recipient) external ONLYOWNER739 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryDaiRecipient = recipient;
}
function PAUSE944(Role role) external ONLYOWNEROR153(Role.PAUSER) { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role in question is already paused.");
storedRoleStatus.paused = true;
emit ROLEPAUSED231(role);
}
function UNPAUSE758(Role role) external ONLYOWNER739 { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role in question is already unpaused.");
storedRoleStatus.paused = false;
emit ROLEUNPAUSED960(role);
}
function SETROLE200(Role role, address account) external ONLYOWNER739 { //inject NONSTANDARD NAMING
require(account != address(0), "Must supply an account.");
_SETROLE808(role, account);
}
function REMOVEROLE179(Role role) external ONLYOWNER739 { //inject NONSTANDARD NAMING
_SETROLE808(role, address(0));
}
function ISPAUSED720(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _ISPAUSED545(role);
}
function ISROLE342(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = _ISROLE373(role);
}
function ISDHARMASMARTWALLET39( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _ISSMARTWALLET802(smartWallet, initialUserSigningKey);
}
function GETDEPOSITMANAGER376() external view returns (address depositManager) { //inject NONSTANDARD NAMING
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
function GETADJUSTER193() external view returns (address adjuster) { //inject NONSTANDARD NAMING
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
function GETRESERVETRADER467() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING
reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account;
}
function GETWITHDRAWALMANAGER690() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING
withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account;
}
function GETPAUSER338() external view returns (address pauser) { //inject NONSTANDARD NAMING
pauser = _roles[uint256(Role.PAUSER)].account;
}
function GETRESERVES367() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _dai122.BALANCEOF395(address(this));
dDai = _ddai891.BALANCEOF395(address(this));
dDaiUnderlying = _ddai891.BALANCEOFUNDERLYING496(address(this));
}
function GETDAILIMIT285() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _daiLimit;
dDaiAmount = (daiAmount.MUL891(1e18)).DIV332(_ddai891.EXCHANGERATECURRENT187());
}
function GETETHERLIMIT400() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING
etherAmount = _etherLimit;
}
function GETPRIMARYUSDCRECIPIENT588() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryUSDCRecipient;
}
function GETPRIMARYDAIRECIPIENT262() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryDaiRecipient;
}
function GETIMPLEMENTATION10() external view returns ( //inject NONSTANDARD NAMING
address implementation
) {
(bool ok, bytes memory returnData) = address(
0x481B1a16E6675D33f8BBb3a6A58F5a9678649718
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
function GETVERSION332() external view returns (uint256 version) { //inject NONSTANDARD NAMING
version = _version870;
}
function _SETROLE808(Role role, address account) internal { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit ROLEMODIFIED441(role, account);
}
}
function _ISROLE373(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = msg.sender == _roles[uint256(role)].account;
}
function _ISPAUSED545(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _roles[uint256(role)].paused;
}
function _ISSMARTWALLET802( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) internal pure returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_wallet_creation_code_header592,
initialUserSigningKey,
_wallet_creation_code_footer939
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_create2_header355, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
modifier ONLYOWNEROR153(Role role) { //inject NONSTANDARD NAMING
if (!ISOWNER526()) {
require(_ISROLE373(role), "Caller does not have a required role.");
require(!_ISPAUSED545(role), "Role in question is currently paused.");
}
_;
}
}
|
inject NONSTANDARD NAMING
|
function MINT439(uint256 daiAmount) external returns (uint256 dDaiMinted);
| 6,408,624 |
pragma solidity ^0.4.23;
/**
* The ENS registry contract.
*/
contract ENS {
struct Record {
address owner;
address resolver;
}
mapping(bytes32=>Record) records;
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the owner of a node changes the resolver for that node.
event NewResolver(bytes32 indexed node, address resolver);
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if(records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar, with the provided address as the owner of the root node.
*/
function ENS(address owner) {
records[0].owner = owner;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) constant returns (address) {
return records[node].resolver;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode sha3(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) {
var subnode = sha3(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
}
contract Resolver {
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 content);
event NameChanged(bytes32 indexed node, string name);
function setName(bytes32 node, string name) public;
function has(bytes32 node, bytes32 kind) returns (bool);
function addr(bytes32 node) constant returns (address ret);
}
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is Resolver {
ENS ens;
struct Reverse {
uint256 contentType;
bytes data;
}
mapping(bytes32=>address) addresses;
mapping(bytes32=>bytes32) contents;
mapping(bytes32=>string) names;
mapping(bytes32=>Reverse) reverses;
modifier only_owner(bytes32 node) {
if(ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(address ensAddr) {
ens = ENS(ensAddr);
}
/**
* Fallback function.
*/
function() {
throw;
}
/**
* Returns true if the specified node has the specified record type.
* @param node The ENS node to query.
* @param kind The record type name, as specified in EIP137.
* @return True if this resolver has a record of the provided type on the
* provided node.
*/
function has(bytes32 node, bytes32 kind) returns (bool) {
return kind == "addr" && addresses[node] != 0;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) constant returns (address ret) {
ret = addresses[node];
if(ret == 0)
throw;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) {
addresses[node] = addr;
AddrChanged(node, addr);
}
function content(bytes32 node) constant returns (bytes32 ret) {
ret = contents[node];
if(ret == 0)
throw;
}
function setContent(bytes32 node, bytes32 content) only_owner(node) {
contents[node] = content;
ContentChanged(node, content);
}
/**
* Returns the name associated with an ENS node.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) constant returns (string ret) {
ret = names[node];
if(bytes(ret).length == 0)
throw;
return ret;
}
/**
* Sets the name associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) only_owner(node) {
names[node] = name;
NameChanged(node, name);
}
function ABI(bytes32 node, uint256 contentType) constant returns (uint256, bytes) {
var record = reverses[node];
if((record.contentType & contentType) == 0)
return (0, "");
return (record.contentType, record.data);
}
function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) {
reverses[node] = Reverse(contentType, data);
}
}
contract ReverseRegistrar {
ENS public ens;
bytes32 public rootNode;
Resolver public defaultResolver;
/**
* @dev Constructor
* @param ensAddr The address of the ENS registry.
* @param node The node hash that this registrar governs.
*/
function ReverseRegistrar(ENS ensAddr, bytes32 node, Resolver resolverAddr ) {
ens = ensAddr;
rootNode = node;
defaultResolver = resolverAddr;
}
/**
* @dev Transfers ownership of the reverse ENS record associated with the
* calling account.
* @param owner The address to set as the owner of the reverse record in ENS.
* @return The ENS node hash of the reverse record.
*/
function claim(address owner) public returns (bytes32) {
return claimWithResolver(owner, 0);
}
/**
* @dev Transfers ownership of the reverse ENS record associated with the
* calling account.
* @param owner The address to set as the owner of the reverse record in ENS.
* @param resolver The address of the resolver to set; 0 to leave unchanged.
* @return The ENS node hash of the reverse record.
*/
function claimWithResolver(address owner, address resolver) public returns (bytes32) {
var label = sha3HexAddress(msg.sender);
bytes32 node = keccak256(rootNode, label);
var currentOwner = ens.owner(node);
// Update the resolver if required
if (resolver != 0 && resolver != ens.resolver(node)) {
// Transfer the name to us first if it's not already
if (currentOwner != address(this)) {
ens.setSubnodeOwner(rootNode, label, this);
currentOwner = address(this);
}
ens.setResolver(node, resolver);
}
// Update the owner if required
if (currentOwner != owner) {
ens.setSubnodeOwner(rootNode, label, owner);
}
return node;
}
/**
* @dev Sets the `name()` record for the reverse ENS record associated with
* the calling account. First updates the resolver to the default reverse
* resolver if necessary.
* @param name The name to set for this address.
* @return The ENS node hash of the reverse record.
*/
function setName(string name) public returns (bytes32) {
bytes32 node = claimWithResolver(this, defaultResolver);
defaultResolver.setName(node, name);
return node;
}
/**
* @dev Returns the node hash for a given account's reverse records.
* @param addr The address to hash
* @return The ENS node hash.
*/
function node(address addr) constant returns (bytes32 ret) {
return sha3(rootNode, sha3HexAddress(addr));
}
/**
* @dev An optimised function to compute the sha3 of the lower-case
* hexadecimal representation of an Ethereum address.
* @param addr The address to hash
* @return The SHA3 hash of the lower-case hexadecimal encoding of the
* input address.
*/
function sha3HexAddress(address addr) private returns (bytes32 ret) {
addr; ret; // Stop warning us about unused variables
assembly {
let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000
let i := 40
loop:
i := sub(i, 1)
mstore8(i, byte(and(addr, 0xf), lookup))
addr := div(addr, 0x10)
i := sub(i, 1)
mstore8(i, byte(and(addr, 0xf), lookup))
addr := div(addr, 0x10)
jumpi(loop, i)
ret := keccak256(0, 40)
}
}
}
contract DeployENS {
ENS public ens;
ReverseRegistrar public reverseregistrar;
Resolver public publicresolver;
constructor() public {
var tld = sha3('eth');
var tldnode = sha3(bytes32(0), tld);
ens = new ENS(this);
var resolver = new PublicResolver(ens);
publicresolver = resolver;
// Set addr.reverse up with the reverse registrar
var reversenode = sha3(bytes32(0), sha3('reverse'));
bytes32 ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
//var addrReverseNode = sha3(reversenode, sha3('addr'));
reverseregistrar = new ReverseRegistrar(ens, ADDR_REVERSE_NODE , resolver);
ens.setSubnodeOwner(0, sha3('reverse'), this);
ens.setSubnodeOwner(reversenode, sha3('addr'), reverseregistrar);
// Set up the reverse record for ourselves
var ournode = reverseregistrar.claim(address(this));
ens.setResolver(ournode, resolver);
resolver.setName(ournode, "deployer.eth");
resolver.setABI(ournode, 2, hex"789c754e390ac33010fccbd4aa0249a1af98141b2183c0590969b630c27f8f6c12838b74c3dc5347c8da284a78568b0e498bb1c14f4f079577840763231cb2f12bf59f3258ae65479694b7fb03db881559e5b50c7696a5c5d3329b06a6acd85cbfccfcf11fcfaa05e63a6a3f5f113a4a");
// Set foo.eth up with a resolver, ABI, and addr record
ens.setSubnodeOwner(0, tld, this);
ens.setSubnodeOwner(tldnode, sha3('foo'), this);
var fooDotEth = sha3(tldnode, sha3('foo'));
ens.setResolver(fooDotEth, resolver);
resolver.setAddr(fooDotEth, msg.sender);
resolver.setContent(fooDotEth, '123456789');
resolver.setABI(fooDotEth, 1, '[{"constant":true,"inputs":[],"name":"test2","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]');
ens.setSubnodeOwner(fooDotEth, sha3('1'), this);
var OneDotFootDotEth = sha3(fooDotEth, sha3('1'));
ens.setResolver(OneDotFootDotEth, resolver);
resolver.setAddr(OneDotFootDotEth, msg.sender);
resolver.setContent(OneDotFootDotEth, 'hello');
ens.setSubnodeOwner(fooDotEth, sha3('2'), msg.sender);
ens.setSubnodeOwner(fooDotEth, sha3('3'), msg.sender);
// Set bar.eth up with a resolver but no addr record, owned by the sender
ens.setSubnodeOwner(tldnode, sha3('bar'), this);
var barDotEth = sha3(tldnode, sha3('bar'));
ens.setResolver(barDotEth, resolver);
ens.setOwner(barDotEth, msg.sender);
// Set up baz.eth with a resolver and addr record
ens.setSubnodeOwner(tldnode, sha3('baz'), this);
var bazDotEth = sha3(tldnode, sha3('baz'));
ens.setResolver(bazDotEth, resolver);
resolver.setAddr(bazDotEth, this);
// Set up foobar.eth without a resolver, owned by the sender
ens.setSubnodeOwner(tldnode, sha3('foobar'), this);
var fooBarDotEth = sha3(tldnode, sha3('foobar'));
ens.setOwner(fooBarDotEth, msg.sender);
// Set up givethisaway.eth without a resolver, owned by the sender
ens.setSubnodeOwner(tldnode, sha3('givethisaway'), this);
var giveThisAwayDotEth = sha3(tldnode, sha3('givethisaway'));
ens.setOwner(giveThisAwayDotEth, msg.sender);
// Set up givesub.eth, owner by send to give away subdomains
ens.setSubnodeOwner(tldnode, sha3('givesub'), this);
var giveSubDotEth = sha3(tldnode, sha3('givesub'));
ens.setOwner(giveSubDotEth, msg.sender);
}
}
|
Returns true if the specified node has the specified record type. node The ENS node to query. kind The record type name, as specified in EIP137. return True if this resolver has a record of the provided type on the provided node./
|
function has(bytes32 node, bytes32 kind) returns (bool) {
return kind == "addr" && addresses[node] != 0;
}
| 1,066,430 |
./full_match/7700/0x6a0fCBe49A75ceD08d4c7791DeCDBE015C30c2c6/sources/contracts/ERC721Testjunk.sol
|
See {IERC721-approve}./
|
function approve(address to, uint256 tokenId) public override {
address owner = ERC721Testjunk.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);
}
| 4,662,524 |
pragma solidity 0.4.20;
// we use solidity solidity 0.4.20 to work with oraclize (http://www.oraclize.it)
// solidity versions > 0.4.20 are not supported by oraclize
/*
Lucky Strike smart contracts version: 2.0
*/
/*
This smart contract is intended for entertainment purposes only. Cryptocurrency gambling is illegal in many jurisdictions and users should consult their legal counsel regarding the legal status of cryptocurrency gambling in their jurisdictions.
Since developers of this smart contract are unable to determine which jurisdiction you reside in, you must check current laws including your local and state laws to find out if cryptocurrency gambling is legal in your area.
If you reside in a location where cryptocurrency gambling is illegal, please do not interact with this smart contract in any way and leave it immediately.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* source: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// ORACLIZE_API
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize 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.
*/
//pragma solidity >=0.4.1 <=0.4.20;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns (bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
/*
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 constant {
if (capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private constant {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private constant returns (uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Reverts if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal constant returns (buffer memory) {
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 {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
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. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal constant {
if (buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal constant returns (buffer memory) {
if (len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function shl8(uint8 x, uint8 y) private constant returns (uint8) {
return x * (2 ** y);
}
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant {
if (value <= 23) {
buf.append(uint8(shl8(major, 5) | value));
} else if (value <= 0xFF) {
buf.append(uint8(shl8(major, 5) | 24));
buf.appendInt(value, 1);
} else if (value <= 0xFFFF) {
buf.append(uint8(shl8(major, 5) | 25));
buf.appendInt(value, 2);
} else if (value <= 0xFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 26));
buf.appendInt(value, 4);
} else if (value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant {
buf.append(uint8(shl8(major, 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal constant {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal constant {
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 value) internal constant {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal constant {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
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_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if ((address(OAR) == 0) || (getCodeSize(address(OAR)) == 0))
oraclize_setNetwork(networkID_auto);
if (address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns (bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) {//mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) {//ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) {//kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) {//rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) {//ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) {//ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) {//browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice * 200000) return 0;
// unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice * gaslimit) return 0;
// unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI 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 oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI 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 oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
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(tmp[i]);
b2 = uint160(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 _a, string _b) internal returns (int) {
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 _haystack, string _needle) internal returns (int) {
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 _a, string _b, string _c, string _d, string _e) internal returns (string) {
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;
for (uint 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 strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((bresult[i] >= 48) && (bresult[i] <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10 ** _b;
return mint;
}
function uint2str(uint i) internal returns (string){
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(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal constant returns (bytes) {
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[] arr) internal constant returns (bytes) {
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;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0) || (_nbytes > 32)) throw;
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
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 = oraclize_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))
}
oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32 => bytes32) oraclize_randomDS_args;
mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset + (uint(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(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(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] = 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 == false) return false;
// 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(proof[3 + 65 + 1]) + 2);
copyBytes(proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
for (uint256 i = 0; i < n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3 + 65 + (uint(proof[3 + 65 + 1]) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1]) + 2);
copyBytes(proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// 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(proof[ledgerProofLength + 32 + 8]))) return false;
// Step 4: commitment match verification, sha3(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 (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)) {//unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// 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 (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false) {
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_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 from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw;
// Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
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, address) {
// 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)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
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 sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 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, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// end of ORACLIZE_API
// =============== Lucky Strike ========================================================================================
contract LuckyStrikeTokens {
function totalSupply() constant returns (uint256);
function balanceOf(address _owner) constant returns (uint256);
function mint(address to, uint256 value, uint256 _invest) public returns (bool);
function tokenSaleIsRunning() public returns (bool);
}
contract LuckyStrike is usingOraclize {
/* --- see: https://github.com/oraclize/ethereum-examples/blob/master/solidity/random-datasource/randomExample.sol */
// see: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol
using SafeMath for uint256;
using SafeMath for uint16;
address public owner;
address admin;
//
uint256 public ticketPriceInWei = 20000000000000000; // 0.02 ETH
uint256 public tokenPriceInWei = 150000000000000; // 0.00015 ETH
uint16 public maxTicketsToBuyInOneTransaction = 333; //
//
uint256 public eventsCounter;
//
mapping(uint256 => address) public theLotteryTicket;
uint256 public ticketsTotal;
//
address public kingOfTheHill;
uint256 public kingOfTheHillTicketsNumber;
mapping(address => uint256) public reward;
event rewardPaid(uint256 indexed eventsCounter, address indexed to, uint256 sum); //
function getReward() public {
require(reward[msg.sender] > 0);
msg.sender.transfer(reward[msg.sender]);
eventsCounter = eventsCounter + 1;
rewardPaid(eventsCounter, msg.sender, reward[msg.sender]);
sum[affiliateRewards] = sum[affiliateRewards].sub(reward[msg.sender]);
reward[msg.sender] = 0;
}
// gas for oraclize_query:
uint256 public oraclizeCallbackGas = 230000; // amount of gas we want Oraclize to set for the callback function
// > to be able to read it from browser after updating
uint256 public currentOraclizeGasPrice; //
function oraclizeGetPrice() public returns (uint256){
currentOraclizeGasPrice = oraclize_getPrice("random", oraclizeCallbackGas);
return currentOraclizeGasPrice;
}
function getContractsWeiBalance() public view returns (uint256) {
return this.balance;
}
// mapping to keep sums on accounts (including 'income'):
mapping(uint8 => uint256) public sum;
uint8 public instantGame = 0;
uint8 public dailyJackpot = 1;
uint8 public weeklyJackpot = 2;
uint8 public monthlyJackpot = 3;
uint8 public yearlyJackpot = 4;
uint8 public income = 5;
uint8 public marketingFund = 6;
uint8 public affiliateRewards = 7; //
uint8 public playersBets = 8;
mapping(uint8 => uint256) public period; // in seconds
event withdrawalFromMarketingFund(uint256 indexed eventsCounter, uint256 sum); //
function withdrawFromMarketingFund() public {
require(msg.sender == owner);
owner.transfer(sum[marketingFund]);
eventsCounter = eventsCounter + 1;
withdrawalFromMarketingFund(eventsCounter, sum[marketingFund]);
sum[marketingFund] = 0;
}
mapping(uint8 => bool) public jackpotPlayIsRunning; //
// allocation:
mapping(uint8 => uint16) public rate;
// JackpotCounters (starts with 0):
mapping(uint8 => uint256) jackpotCounter;
mapping(uint8 => uint256) public lastJackpotTime; // unix time
// uint256 public lastDividendsPaymentTime; // unix time, for 'income' only
address public luckyStrikeTokensContractAddress;
LuckyStrikeTokens public luckyStrikeTokens;
/* --- constructor */
// (!) requires acces to Oraclize contract
// will fail on JavaScript VM
function LuckyStrike() public {
admin = msg.sender;
// sets the Ledger authenticity proof in the constructor
oraclize_setProof(proofType_Ledger);
}
function init(address _luckyStrikeTokensContractAddress) public payable {
require(ticketsTotal == 0);
require(msg.sender == admin);
owner = 0x0bBAb60c495413c870F8cABF09436BeE9fe3542F;
require(msg.value / ticketPriceInWei >= 1);
luckyStrikeTokensContractAddress = _luckyStrikeTokensContractAddress;
// should be updated every time we use it
// now we just get value to show in webapp
oraclizeGetPrice();
kingOfTheHill = msg.sender;
ticketsTotal = kingOfTheHillTicketsNumber = 1;
theLotteryTicket[1] = kingOfTheHill;
// initialize jackpot periods
// see: https://solidity.readthedocs.io/en/v0.4.20/units-and-global-variables.html#time-units
period[dailyJackpot] = 1 days;
period[weeklyJackpot] = 1 weeks;
period[monthlyJackpot] = 30 days;
period[yearlyJackpot] = 1 years;
// for testing:
// period[dailyJackpot] = 60 * 1;
// period[weeklyJackpot] = 60 * 3;
// period[monthlyJackpot] = 60 * 5;
// period[yearlyJackpot] = 60 * 7;
// set last block numbers and timestamps for jackpots:
for (uint8 i = dailyJackpot; i <= yearlyJackpot; i++) {
lastJackpotTime[i] = block.timestamp;
}
rate[instantGame] = 8500;
rate[dailyJackpot] = 500;
rate[weeklyJackpot] = 300;
rate[monthlyJackpot] = 100;
rate[yearlyJackpot] = 100;
rate[income] = 500;
luckyStrikeTokens = LuckyStrikeTokens(luckyStrikeTokensContractAddress);
}
/* --- Tokens contract information */
function tokensTotalSupply() public view returns (uint256) {
return luckyStrikeTokens.totalSupply();
}
function tokensBalanceOf(address acc) public view returns (uint256){
return luckyStrikeTokens.balanceOf(acc);
}
function weiInTokensContract() public view returns (uint256){
return luckyStrikeTokens.balance;
}
function tokenSaleIsRunning() public view returns (bool) {
return luckyStrikeTokens.tokenSaleIsRunning();
}
event AllocationAdjusted(
uint256 indexed eventsCounter,
address by,
uint16 instantGame,
uint16 dailyJackpot,
uint16 weeklyJackpot,
uint16 monthlyJackpot,
uint16 yearlyJackpot,
uint16 income);
function adjustAllocation(
uint16 _instantGame,
uint16 _dailyJackpot,
uint16 _weeklyJackpot,
uint16 _monthlyJackpot,
uint16 _yearlyJackpot,
uint16 _income) public {
// only owner !!!
require(msg.sender == owner);
rate[instantGame] = _instantGame;
rate[dailyJackpot] = _dailyJackpot;
rate[weeklyJackpot] = _weeklyJackpot;
rate[monthlyJackpot] = _monthlyJackpot;
rate[yearlyJackpot] = _yearlyJackpot;
rate[income] = _income;
// check if provided %% amount to 10,000
uint16 _sum = 0;
for (uint8 i = instantGame; i <= income; i++) {
_sum = _sum + rate[i];
}
require(_sum == 10000);
eventsCounter = eventsCounter + 1;
AllocationAdjusted(
eventsCounter,
msg.sender,
rate[instantGame],
rate[dailyJackpot],
rate[weeklyJackpot],
rate[monthlyJackpot],
rate[yearlyJackpot],
rate[income]
);
} // end of adjustAllocation
// this function calculates jackpots/income allocation and returns prize for the instant game
uint256 sumAllocatedInWeiCounter;
event SumAllocatedInWei(
uint256 indexed eventsCounter,
uint256 indexed sumAllocatedInWeiCounter,
address betOf,
uint256 bet, // 0
uint256 dailyJackpot, // 1
uint256 weeklyJackpot, // 2;
uint256 monthlyJackpot, // 3;
uint256 yearlyJackpot, // 4;
uint256 income,
uint256 affiliateRewards,
uint256 payToWinner
);
function allocateSum(uint256 _sum, address loser) private returns (uint256) {
// for event
// https://solidity.readthedocs.io/en/v0.4.24/types.html#allocating-memory-arrays
uint256[] memory jackpotsSumAllocation = new uint256[](5);
// jackpots:
for (uint8 i = dailyJackpot; i <= yearlyJackpot; i++) {
uint256 sumToAdd = _sum * rate[i] / 10000;
sum[i] = sum[i].add(sumToAdd);
// for event:
jackpotsSumAllocation[i] = sumToAdd;
}
// income before affiliate reward subtraction:
uint256 incomeSum = (_sum * rate[income]) / 10000;
// referrer reward:
uint256 refSum = 0;
if (referrer[loser] != address(0)) {
address referrerAddress = referrer[loser];
refSum = incomeSum / 2;
incomeSum = incomeSum.sub(refSum);
reward[referrerAddress] = reward[referrerAddress].add(refSum);
sum[affiliateRewards] = sum[affiliateRewards].add(refSum);
}
sum[income] = sum[income].add(incomeSum);
uint256 payToWinner = _sum * rate[instantGame] / 10000;
eventsCounter = eventsCounter + 1;
sumAllocatedInWeiCounter = sumAllocatedInWeiCounter + 1;
SumAllocatedInWei(
eventsCounter,
sumAllocatedInWeiCounter,
loser,
_sum,
jackpotsSumAllocation[1], // dailyJackpot
jackpotsSumAllocation[2], // weeklyJackpot
jackpotsSumAllocation[3], // monthlyJackpot
jackpotsSumAllocation[4], // yearlyJackpot
incomeSum,
refSum,
payToWinner
);
return payToWinner;
}
/* -------------- GAME: --------------*/
/* --- Instant Game ------- */
uint256 public instantGameCounter; // id's of the instant games
//
// to allow only one game for the given address simultaneously:
mapping(address => bool) public instantGameIsRunning;
//
mapping(address => uint256) public lastInstantGameBlockNumber; // for address
mapping(address => uint256) public lastInstantGameTicketsNumber; // for address
// first step for player is to make a bet:
uint256 public betCounter;
event BetPlaced(
uint256 indexed eventsCounter,
uint256 indexed betCounter,
address indexed player,
uint256 betInWei,
uint256 ticketsBefore,
uint256 newTickets
);
function placeABetInternal(uint value) private {
require(msg.sender != kingOfTheHill);
// only one game allowed for the address at the given moment:
require(!instantGameIsRunning[msg.sender]);
// number of new tickets to create;
uint256 newTickets = value / ticketPriceInWei;
eventsCounter = eventsCounter + 1;
betCounter = betCounter + 1;
BetPlaced(eventsCounter, betCounter, msg.sender, value, ticketsTotal, newTickets);
uint256 playerBetToPlace = newTickets.mul(ticketPriceInWei);
sum[playersBets] = sum[playersBets].add(playerBetToPlace);
require(newTickets > 0 && newTickets <= maxTicketsToBuyInOneTransaction);
uint256 newTicketsTotal = ticketsTotal.add(newTickets);
// new tickets included in jackpot games instantly:
for (uint256 i = ticketsTotal + 1; i <= newTicketsTotal; i++) {
theLotteryTicket[i] = msg.sender;
}
ticketsTotal = newTicketsTotal;
lastInstantGameTicketsNumber[msg.sender] = newTickets;
instantGameIsRunning[msg.sender] = true;
lastInstantGameBlockNumber[msg.sender] = block.number;
}
function placeABet() public payable {
placeABetInternal(msg.value);
}
mapping(address => address) public referrer;
function placeABetWithReferrer(address _referrer) public payable {
/* referrer: */
if (referrer[msg.sender] == 0x0000000000000000000000000000000000000000) {
referrer[msg.sender] = _referrer;
}
placeABetInternal(msg.value);
}
event Investment(
uint256 indexed eventsCounter, //.1
address indexed by, //............2
uint256 sum, //...................3
uint256 sumToMarketingFund, //....4
uint256 bet, //...................5
uint256 tokens //.................6
); //
function investAndPlay() public payable {
// require( luckyStrikeTokens.tokenSaleIsRunning());
// < we will check this in luckyStrikeTokens.mint method
uint256 sumToMarketingFund = msg.value / 5;
sum[marketingFund] = sum[marketingFund].add(sumToMarketingFund);
uint256 bet = msg.value.sub(sumToMarketingFund);
placeABetInternal(bet);
// uint256 tokensToMint = msg.value / ticketPriceInWei;
// uint256 tokensToMint = bet / tokenPriceInWei;
uint256 tokensToMint = sumToMarketingFund / tokenPriceInWei;
// require(bet / ticketPriceInWei > 0); // > makes more complicated
luckyStrikeTokens.mint(msg.sender, tokensToMint, sumToMarketingFund);
eventsCounter = eventsCounter + 1;
Investment(
eventsCounter, //......1
msg.sender, //.........2
msg.value, //..........3
sumToMarketingFund, //.4
bet, //................5
tokensToMint //........6
);
}
function investAndPlayWithReferrer(address _referrer) public payable {
if (referrer[msg.sender] == 0x0000000000000000000000000000000000000000) {
referrer[msg.sender] = _referrer;
}
investAndPlay();
}
/*
function invest() public payable {
// require(luckyStrikeTokens.tokenSaleIsRunning());
// < we will check this in luckyStrikeTokens.mint method
sum[marketingFund] = sum[marketingFund].add(msg.value);
uint256 tokensToMint = msg.value / ticketPriceInWei;
// uint256 bonus = (tokensToMint / 100).mul(75);
uint256 bonus1part = tokensToMint / 2;
uint256 bonus2part = tokensToMint / 4;
uint256 bonus = bonus1part.add(bonus2part);
tokensToMint = tokensToMint.add(bonus);
// require(bet / ticketPriceInWei > 0); // > makes more complicated
luckyStrikeTokens.mint(
msg.sender,
tokensToMint,
msg.value // all sum > investment
);
eventsCounter = eventsCounter + 1;
Investment(
eventsCounter, //..1
msg.sender, //.....2
msg.value, //......3
msg.value, //......4
0, //..............5 (bet)
tokensToMint //....6
);
}
function investWithReferrer(address _referrer) public payable {
if (referrer[msg.sender] == 0x0000000000000000000000000000000000000000) {
referrer[msg.sender] = _referrer;
}
invest();
}
*/
// second step in instant game:
event InstantGameResult (
uint256 indexed eventsCounter, //...0
uint256 gameId, // .................1
bool theBetPlayed, //...............2
address indexed challenger, //......3
address indexed king, //............4
uint256 kingsTicketsNumber, //......5
address winner, //..................6
uint256 prize, //...................7
uint256 ticketsInTheInstantGame, //.8
uint256 randomNumber, //............9
address triggeredBy //..............10
);
function play(address player) public {
require(instantGameIsRunning[player]);
require(lastInstantGameBlockNumber[player] < block.number);
// block number with the bet must be no more than 255 blocks before the current block
// or we get 0 as blockhash
instantGameCounter = instantGameCounter + 1;
uint256 playerBet = lastInstantGameTicketsNumber[player].mul(ticketPriceInWei);
// in any case playerBet should be subtracted sum[playerBets]
sum[playersBets] = sum[playersBets].sub(playerBet);
// TODO: recheck this >
if (block.number - lastInstantGameBlockNumber[player] > 250) {
eventsCounter = eventsCounter + 1;
InstantGameResult(
eventsCounter,
instantGameCounter,
false,
player,
address(0), // kingOfTheHill, // oldKingOfTheHill,
0,
address(0), // winner,
0, // prize,
0, // lastInstantGameTicketsNumber[player], // ticketsInTheInstantGame,
0, // randomNumber,
msg.sender // triggeredBy
);
// player.transfer(playerBet);
sum[income] = sum[income].add(playerBet);
lastInstantGameTicketsNumber[player] = 0;
instantGameIsRunning[player] = false;
return;
}
address oldKingOfTheHill = kingOfTheHill;
uint256 oldKingOfTheHillTicketsNumber = kingOfTheHillTicketsNumber;
uint256 ticketsInTheInstantGame = kingOfTheHillTicketsNumber.add(lastInstantGameTicketsNumber[player]);
// TODO: recheck this
bytes32 seed = keccak256(
block.blockhash(lastInstantGameBlockNumber[player]) // bytes32
);
uint256 seedToNumber = uint256(seed);
uint256 randomNumber = seedToNumber % ticketsInTheInstantGame;
// 0 never plays, and ticketsInTheInstantGame can not be returned by the function above
if (randomNumber == 0) {
randomNumber = ticketsInTheInstantGame;
}
uint256 prize;
address winner;
address loser;
if (randomNumber > kingOfTheHillTicketsNumber) {// challenger ('player') wins
winner = player;
loser = kingOfTheHill;
// new kingOfTheHill:
kingOfTheHill = player;
kingOfTheHillTicketsNumber = lastInstantGameTicketsNumber[player];
} else {// kingOfTheHill wins
winner = kingOfTheHill;
loser = player;
}
// prize = allocateSum(playerBet, loser, winner);
prize = allocateSum(playerBet, loser);
instantGameIsRunning[player] = false;
// pay prize to the winner
winner.transfer(prize);
eventsCounter = eventsCounter + 1;
InstantGameResult(
eventsCounter,
instantGameCounter,
true,
player,
oldKingOfTheHill,
oldKingOfTheHillTicketsNumber,
winner,
// playerBet,
prize,
ticketsInTheInstantGame,
randomNumber,
msg.sender
);
}
// convenience function;
function playMyInstantGame() public {
play(msg.sender);
}
/* ----------- Jackpots: ------------ */
function requestRandomFromOraclize() private returns (bytes32 oraclizeQueryId) {
require(msg.value >= oraclizeGetPrice());
// < to pay to oraclize
// call Oraclize
// uint N :
// number nRandomBytes between 1 and 32, which is the number of random bytes to be returned to the application.
// see: http://www.oraclize.it/papers/random_datasource-rev1.pdf
uint256 N = 32;
// number of seconds to wait before the execution takes place
uint delay = 0;
// this function internally generates the correct oraclize_query and returns its queryId
oraclizeQueryId = oraclize_newRandomDSQuery(delay, N, oraclizeCallbackGas);
// playJackpotEvent(msg.sender, msg.value, tx.gasprice, oraclizeQueryId);
return oraclizeQueryId;
}
// reminder (this defined above):
// mapping(uint8 => uint256) public period; // in seconds
// mapping(uint8 => uint256) public lastJackpotTime; // unix time
mapping(bytes32 => uint8) public jackpot;
event JackpotPlayStarted(
uint256 indexed eventsCounter,
uint8 indexed jackpotType,
address startedBy,
bytes32 oraclizeQueryId
);//
// uint8 jackpotType
function startJackpotPlay(uint8 jackpotType) public payable {
require(msg.value >= oraclizeGetPrice());
require(jackpotType >= 1 && jackpotType <= 4);
require(!jackpotPlayIsRunning[jackpotType]);
require(
// block.timestamp (uint): current block timestamp as seconds since unix epoch
block.timestamp >= lastJackpotTime[jackpotType].add(period[jackpotType])
);
bytes32 oraclizeQueryId = requestRandomFromOraclize();
jackpot[oraclizeQueryId] = jackpotType;
jackpotPlayIsRunning[jackpotType] = true;
eventsCounter = eventsCounter + 1;
JackpotPlayStarted(eventsCounter, jackpotType, msg.sender, oraclizeQueryId);
}
uint256 public allJackpotsCounter;
event JackpotResult(
uint256 indexed eventsCounter,
uint256 allJackpotsCounter,
uint8 indexed jackpotType,
uint256 jackpotIdNumber,
uint256 prize,
address indexed winner,
uint256 randomNumberSeed,
uint256 randomNumber,
uint256 ticketsTotal
);
// the callback function is called by Oraclize when the result is ready
// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:
// the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) public {
require(msg.sender == oraclize_cbAddress());
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
// the proof verification has failed, do we need to take any action here? (depends on the use case)
revert();
} else {
// find jackpot for this _queryId:
uint8 jackpotType = jackpot[_queryId];
require(jackpotPlayIsRunning[jackpotType]);
jackpotCounter[jackpotType] = jackpotCounter[jackpotType] + 1;
// select jackpot winner:
bytes32 hashOfTheRandomString = keccak256(_result);
uint256 randomNumberSeed = uint256(hashOfTheRandomString);
uint256 randomNumber = randomNumberSeed % ticketsTotal;
// there is no ticket # 0, and above function can not return number equivalent to 'ticketsTotal'
if (randomNumber == 0) {
randomNumber = ticketsTotal;
}
address winner = theLotteryTicket[randomNumber];
// transfer jackpot sum to the winner
winner.transfer(sum[jackpotType]);
// emit event:
eventsCounter = eventsCounter + 1;
allJackpotsCounter = allJackpotsCounter + 1;
JackpotResult(
eventsCounter,
allJackpotsCounter,
jackpotType,
jackpotCounter[jackpotType],
sum[jackpotType],
winner,
randomNumberSeed,
randomNumber,
ticketsTotal
);
// update information for this jackpot:
sum[jackpotType] = 0;
lastJackpotTime[jackpotType] = block.timestamp;
jackpotPlayIsRunning[jackpotType] = false;
}
} // end of function __callback
event DividendsSentToTokensContract(uint256 indexed eventsCounter, uint256 sum, address indexed triggeredBy);
// can be called by any address:
function payDividends() public returns (bool success){
luckyStrikeTokensContractAddress.transfer(sum[income]);
eventsCounter = eventsCounter + 1;
DividendsSentToTokensContract(eventsCounter, sum[income], msg.sender);
sum[income] = 0;
return true;
}
}
|
Appends a byte array to the end of the buffer. Reverts if doing so would exceed the capacity of the buffer. buf The buffer to append to. data The data to append. return The original buffer./ Memory address of the buffer data Length of existing buffer data Start address = buffer address + buffer length + sizeof(buffer length) Update buffer length Copy word-length chunks while possible
|
function append(buffer memory buf, bytes data) internal constant returns (buffer memory) {
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)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
| 2,531,127 |
./full_match/10/0x371405Aea16D5916703C74580247196BA9EA531F/sources/home/sol-op/chef/contracts/CthulhuChef.sol
|
Update the given pool's SUSHI allocation point. Can only be called by the owner.
|
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, uint256 _withdrawFee, IVault _vault) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].withdrawFee = _withdrawFee;
poolInfo[_pid].vault = _vault;
}
| 3,784,010 |
./full_match/5/0x378a23c0FA0c6E4F9680ae93caC368B5111BfC6F/sources/project_/contracts/managementContract.sol
|
Set the {nonWhitelistedDepositLimit}. It can be set to 0 to prevent deposits to non-whitelisted users. Requirements: - the caller must have the `DEFAULT_ADMIN_ROLE`./
|
function setNonWhitelistedDepositLimit(uint256 _nonWhitelistedDepositLimit) external virtual onlyAdmin {
nonWhitelistedDepositLimit = _nonWhitelistedDepositLimit;
}
| 1,960,319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.