file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
// 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
}
}
|
is contract support interface _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);
}
| 12,763,206
|
./full_match/1/0xca470209117FAAE06e3A9113CAb684febC8788ff/sources/contracts/Distributor.sol
|
Sets the token used as a caution during disputes
|
function setDisputeToken(IERC20 _disputeToken) external onlyGovernorOrGuardian {
if (disputer != address(0)) revert UnresolvedDispute();
disputeToken = _disputeToken;
emit DisputeTokenUpdated(address(_disputeToken));
}
| 3,081,485
|
pragma solidity ^0.4.24;
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;
}
}
// ERC20
contract ERC20 {
function transfer(address to, uint value) public returns (bool success);
function transferFrom(address from, address to, uint value) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint value);
}
// contract owned
contract Owned {
address public owner;
constructor () internal {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
//CIPToken
contract CIPToken is ERC20, Owned {
using SafeMath for uint256;
//metadata
string public name="CIP Token";
string public symbol="CIP";
uint256 public decimals = 18;
string public version = "1.0";
uint public totalSupply = 4500000000 * 10 ** uint(decimals);
mapping(address => uint) public balanceOf;
mapping(address => uint256) public lockValues;
mapping(address => mapping(address => uint)) public allowance;
//event
event FreezeIn(address[] indexed from, bool value);
event FreezeOut(address[] indexed from, bool value);
//constructor
constructor () public {
balanceOf[msg.sender] = totalSupply;
}
function internalTransfer(address from, address toaddr, uint value) internal {
require(toaddr!=0);
require(balanceOf[from]>=value);
balanceOf[from]= balanceOf[from].sub(value);// safeSubtract(balanceOf[from], value);
balanceOf[toaddr]= balanceOf[toaddr].add(value);//safeAdd(balanceOf[toaddr], value);
emit Transfer(from, toaddr, value);
}
//
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balanceOf[msg.sender]);
uint256 transBlalance = balanceOf[msg.sender].sub(lockValues[msg.sender]);
require(_value <= transBlalance);
// SafeMath.sub will throw if there is not enough balance.
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
//transfer from
function transferFrom(address from, address toaddr, uint value) public returns (bool) {
require(allowance[from][msg.sender]>=value);
allowance[from][msg.sender]=allowance[from][msg.sender].sub(value);// safeSubtract(allowance[from][msg.sender], value);
internalTransfer(from, toaddr, value);
return true;
}
// reset name and symbol
function setNameSymbol(string newName, string newSymbol) public onlyOwner {
name=newName;
symbol=newSymbol;
}
function addLockValue(address addr,uint256 _value) public onlyOwner{
require(addr != address(0));
lockValues[addr] = lockValues[addr].add(_value);
}
function subLockValue(address addr,uint256 _value) public onlyOwner{
require(addr != address(0));
require(_value <= lockValues[addr]);
lockValues[addr] = lockValues[addr].sub(_value);
}
// buy token
function () public payable {
}
}
|
reset name and symbol
|
function setNameSymbol(string newName, string newSymbol) public onlyOwner {
name=newName;
symbol=newSymbol;
}
| 964,171
|
./full_match/8453/0x3b5B74E56755a43682CAdE9a0FaD609fFC1601eA/sources/contracts/StableSwapTwoPool.sol
|
x in the input is converted to the same price/precision Equality with the precision of 1
|
function get_y(uint256 i, uint256 j, uint256 x, uint256[N_COINS] memory xp_) internal view returns (uint256) {
require((i != j) && (i < N_COINS) && (j < N_COINS), "Illegal parameter");
uint256 amp = get_A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_;
uint256 Ann = amp * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k == i) {
_x = x;
_x = xp_[k];
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 y_prev;
uint256 y = D;
for (uint256 m = 0; m < 255; m++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
| 11,557,511
|
//Address: 0xadb797366e36697dc9742a8c820d3dda931668d2
//Contract name: minter
//Balance: 3.229862423516881406 Ether
//Verification Date: 10/23/2017
//Transacion Count: 6
// CODE STARTS HERE
pragma solidity ^0.4.16;
/** @title owned. */
contract owned {
address owner;
function owned() {
owner = msg.sender;
}
function changeOwner(address newOwner) onlyOwner {
owner = newOwner;
}
modifier onlyOwner() {
require(msg.sender==owner);
_;
}
}
/** @title mortal. */
contract mortal is owned() {
function kill() onlyOwner {
if (msg.sender == owner) selfdestruct(owner);
}
}
/** @title DSMath. */
contract DSMath {
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
// /*
// uint128 functions (h is for half)
// */
function hmore(uint128 x, uint128 y) constant internal returns (bool) {
return x>y;
}
function hless(uint128 x, uint128 y) constant internal returns (bool) {
return x<y;
}
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
require((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
require((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
require(y == 0 ||(z = x * y)/ y == x);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
// /*
// int256 functions
// */
/*
WAD math
*/
uint64 constant WAD_Dec=18;
uint128 constant WAD = 10 ** 18;
function wmore(uint128 x, uint128 y) constant internal returns (bool) {
return hmore(x, y);
}
function wless(uint128 x, uint128 y) constant internal returns (bool) {
return hless(x, y);
}
function wadd(uint128 x, uint128 y) constant returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
/** @title I_minter. */
contract I_minter {
event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventBankrupt();
function Leverage() constant returns (uint128) {}
function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) constant returns (uint128 price) {}
function RiskPrice(uint128 _currentPrice) constant returns (uint128 price) {}
function PriceReturn(uint _TransID,uint128 _Price) {}
function NewStatic() external payable returns (uint _TransID) {}
function NewStaticAdr(address _Risk) external payable returns (uint _TransID) {}
function NewRisk() external payable returns (uint _TransID) {}
function NewRiskAdr(address _Risk) external payable returns (uint _TransID) {}
function RetRisk(uint128 _Quantity) external payable returns (uint _TransID) {}
function RetStatic(uint128 _Quantity) external payable returns (uint _TransID) {}
function Strike() constant returns (uint128) {}
}
/** @title I_Pricer. */
contract I_Pricer {
uint128 public lastPrice;
I_minter public mint;
string public sURL;
mapping (bytes32 => uint) RevTransaction;
function __callback(bytes32 myid, string result) {}
function queryCost() constant returns (uint128 _value) {}
function QuickPrice() payable {}
function requestPrice(uint _actionID) payable returns (uint _TrasID) {}
function collectFee() returns(bool) {}
function () {
//if ether is sent to this address, send it back.
revert();
}
}
/** @title I_coin. */
contract I_coin is mortal {
event EventClear();
I_minter public mint;
string public name; //fancy name: eg Simon Bucks
uint8 public decimals=18; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = ''; //human 0.1 standard. Just an arbitrary versioning scheme.
function mintCoin(address target, uint256 mintedAmount) returns (bool success) {}
function meltCoin(address target, uint256 meltedAmount) returns (bool success) {}
function approveAndCall(address _spender, uint256 _value, bytes _extraData){}
function setMinter(address _minter) {}
function increaseApproval (address _spender, uint256 _addedValue) returns (bool success) {}
function decreaseApproval (address _spender, uint256 _subtractedValue) returns (bool success) {}
// @param _owner The address from which the balance will be retrieved
// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
// @notice send `_value` token to `_to` from `msg.sender`
// @param _to The address of the recipient
// @param _value The amount of token to be transferred
// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
// @param _from The address of the sender
// @param _to The address of the recipient
// @param _value The amount of token to be transferred
// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
// @notice `msg.sender` approves `_addr` to spend `_value` tokens
// @param _spender The address of the account able to transfer the tokens
// @param _value The amount of wei to be approved for transfer
// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// @param _owner The address of the account owning tokens
// @param _spender The address of the account able to transfer the tokens
// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
// @return total amount of tokens
uint256 public totalSupply;
}
/** @title DSBaseActor. */
contract DSBaseActor {
/*
Copyright 2016 Nexus Development, LLC
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.
*/
bool _ds_mutex;
modifier mutex() {
assert(!_ds_mutex);
_ds_mutex = true;
_;
_ds_mutex = false;
}
function tryExec( address target, bytes calldata, uint256 value)
mutex()
internal
returns (bool call_ret)
{
/** @dev Requests new StatiCoins be made for a given address
* @param target where the ETH is sent to.
* @param calldata
* @param value
* @return True if ETH is transfered
*/
return target.call.value(value)(calldata);
}
function exec( address target, bytes calldata, uint256 value)
internal
{
assert(tryExec(target, calldata, value));
}
}
/** @title canFreeze. */
contract canFreeze is owned {
//Copyright (c) 2017 GenkiFS
//Basically a "break glass in case of emergency"
bool public frozen=false;
modifier LockIfFrozen() {
if (!frozen){
_;
}
}
function Freeze() onlyOwner {
// fixes the price and allows everyone to redeem their coins at the current value
// only becomes false when all ETH has been claimed or the pricer contract is changed
frozen=true;
}
}
/** @title oneWrite. */
contract oneWrite {
// Adds modifies that allow one function to be called only once
//Copyright (c) 2017 GenkiFS
bool written = false;
function oneWrite() {
/** @dev Constuctor, make sure written=false initally
*/
written = false;
}
modifier LockIfUnwritten() {
if (written){
_;
}
}
modifier writeOnce() {
if (!written){
written=true;
_;
}
}
}
/** @title pricerControl. */
contract pricerControl is canFreeze {
// Copyright (c) 2017 GenkiFS
// Controls the Pricer contract for minter. Allows updates to be made in the future by swapping the pricer contract
// Although this is not expected, web addresses, API's, new oracles could require adjusments to the pricer contract
// A delay of 2 days is implemented to allow coinholders to redeem their coins if they do not agree with the new contract
// A new pricer contract unfreezes the minter (allowing a live price to be used)
I_Pricer public pricer;
address public future;
uint256 public releaseTime;
uint public PRICER_DELAY = 2; // days updated when coins are set
event EventAddressChange(address indexed _from, address indexed _to, uint _timeChange);
function setPricer(address newAddress) onlyOwner {
/** @dev Changes the Pricer contract, after a certain delay
* @param newAddress Allows coins to be created and sent to other people
* @return transaction ID which can be viewed in the pending mapping
*/
releaseTime = now + PRICER_DELAY;
future = newAddress;
EventAddressChange(pricer, future, releaseTime);
}
modifier updates() {
if (now > releaseTime && pricer != future){
update();
//log0('Updating');
}
_;
}
modifier onlyPricer() {
require(msg.sender==address(pricer));
_;
}
function update() internal {
pricer = I_Pricer(future);
frozen = false;
}
}
/** @title minter. */
contract minter is I_minter, DSBaseActor, oneWrite, pricerControl, DSMath{ //
// Copyright (c) 2017 GenkiFS
// This contract is the controller for the StatiCoin contracts.
// Users have 4(+2) functions they can call to mint/melt Static/Risk coins which then calls the Pricer contract
// after a delay the Pricer contract will call back to the PriceReturn() function
// this will then call one of the functions ActionNewStatic, ActionNewRisk, ActionRetStatic, ActionRetRisk
// which will then call the Static or Risk ERC20 contracts to mint/melt new tokens
// Transfer of tokens is handled by the ERC20 contracts, ETH is stored here.
enum Action {NewStatic, RetStatic, NewRisk, RetRisk} // Enum of what users can do
struct Trans { // Struct
uint128 amount; // Amount sent by the user (Can be either ETH or number of returned coins)
address holder; // Address of the user
Action action; // Type of action requested (mint/melt a Risk/StatiCoin)
bytes32 pricerID; // ID for the pricer function
}
uint128 public lastPrice; //Storage of the last price returned by the Pricer contract
uint128 public PendingETH; //Amount of eth to be added to the contract
uint public TransID=0; // An increasing counter to keep track of transactions requested
uint public TransCompleted; // Last transaction removed
string public Currency; // Name of underlying base currency
I_coin public Static; // ERC20 token interface for the StatiCoin
I_coin public Risk; // ERC20 token interface for the Risk coin
uint128 public Multiplier;//=15*10**(17); // default ratio for Risk price
uint128 public levToll=5*10**(18-1);//0.5 // this plus the multiplier defines the maximum leverage
uint128 public mintFee = 2*10**(18-3); //0.002 Used to pay oricalize and for marketing contract which is in both parties interest.
mapping (uint => Trans[]) public pending; // A mapping of pending transactions
event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price);
event EventBankrupt(); //Called when no more ETH is in the contract and everything needs to be manually reset.
function minter(string _currency, uint128 _Multiplier) { //,uint8 _DecimalPlaces
// CONSTRUCTOR
Currency=_currency;
Multiplier = _Multiplier;
// can't add new contracts here as it gives out of gas messages. Too much code.
}
function () {
//if ETH is just sent to this address then we cannot determine if it's for StatiCoins or RiskCoins, so send it back.
revert();
}
function Bailout()
external
payable
{
/** @dev Allows extra ETH to be added to the benefit of both types of coin holders
* @return nothing
*/
}
function NewStatic()
external
payable
returns (uint _TransID) {
/** @dev Requests new StatiCoins be made for the sender.
* This cannot be called by a contract. Only a simple wallet (with 0 codesize).
* Contracts must use the Approve, transferFrom pattern and move coins from wallets
* @return transaction ID which can be viewed in the pending mapping
*/
_TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewStatic);
//log0('NewStatic');
}
function NewStaticAdr(address _user)
external
payable
returns (uint _TransID) {
/** @dev Requests new StatiCoins be made for a given address.
* The address cannot be a contract, only a simple wallet (with 0 codesize).
* Contracts must use the Approve, transferFrom pattern and move coins from wallets
* @param _user Allows coins to be created and sent to other people
* @return transaction ID which can be viewed in the pending mapping
*/
_TransID=NewCoinInternal(_user,cast(msg.value),Action.NewStatic);
//log0('NewStatic');
}
function NewRisk()
external
payable
returns (uint _TransID) {
/** @dev Requests new Riskcoins be made for the sender.
* This cannot be called by a contract, only a simple wallet (with 0 codesize).
* Contracts must use the Approve, transferFrom pattern and move coins from wallets
* @return transaction ID which can be viewed in the pending mapping
*/
_TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewRisk);
//log0('NewRisk');
}
function NewRiskAdr(address _user)
external
payable
returns (uint _TransID) {
/** @dev Requests new Riskcoins be made for a given address.
* The address cannot be a contract, only a simple wallet (with 0 codesize).
* Contracts must use the Approve, transferFrom pattern and move coins from wallets
* @param _user Allows coins to be created and sent to other people
* @return transaction ID which can be viewed in the pending mapping
*/
_TransID=NewCoinInternal(_user,cast(msg.value),Action.NewRisk);
//log0('NewRisk');
}
function RetRisk(uint128 _Quantity)
external
payable
LockIfUnwritten
returns (uint _TransID) {
/** @dev Returns Riskcoins. Needs a bit of eth sent to pay the pricer contract and the excess is returned.
* The address cannot be a contract, only a simple wallet (with 0 codesize).
* @param _Quantity Amount of coins being returned
* @return transaction ID which can be viewed in the pending mapping
*/
if(frozen){
//Skip the pricer contract
TransID++;
ActionRetRisk(Trans(_Quantity,msg.sender,Action.RetRisk,0),TransID,lastPrice);
_TransID=TransID;
} else {
//Only returned when Risk price is positive
_TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetRisk);
}
//log0('RetRisk');
}
function RetStatic(uint128 _Quantity)
external
payable
LockIfUnwritten
returns (uint _TransID) {
/** @dev Returns StatiCoins, Needs a bit of eth sent to pay the pricer contract
* @param _Quantity Amount of coins being returned
* @return transaction ID which can be viewed in the pending mapping
*/
if(frozen){
//Skip the pricer contract
TransID++;
ActionRetStatic(Trans(_Quantity,msg.sender,Action.RetStatic,0),TransID,lastPrice);
_TransID=TransID;
} else {
//Static can be returned at any time
_TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetStatic);
}
//log0('RetStatic');
}
//****************************//
// Constant functions (Ones that don't write to the blockchain)
function StaticEthAvailable()
constant
returns (uint128) {
/** @dev Returns the total amount of eth that can be sent to buy StatiCoins
* @return amount of Eth
*/
return StaticEthAvailable(cast(Risk.totalSupply()), cast(this.balance));
}
function StaticEthAvailable(uint128 _RiskTotal, uint128 _TotalETH)
constant
returns (uint128) {
/** @dev Returns the total amount of eth that can be sent to buy StatiCoins allows users to test arbitrary amounts of RiskTotal and ETH contained in the contract
* @param _RiskTotal Quantity of riskcoins
* @param _TotalETH Total value of ETH in the contract
* @return amount of Eth
*/
// (Multiplier+levToll)*_RiskTotal - _TotalETH
uint128 temp = wmul(wadd(Multiplier,levToll),_RiskTotal);
if(wless(_TotalETH,temp)){
return wsub(temp ,_TotalETH);
} else {
return 0;
}
}
function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal)
constant
returns (uint128 price) {
/** @dev Allows users to query various hypothetical prices of RiskCoins in terms of base currency
* @param _currentPrice Current price of ETH in Base currency.
* @param _StaticTotal Total quantity of StatiCoins issued.
* @param _RiskTotal Total quantity of invetor coins issued.
* @param _ETHTotal Total quantity of ETH in the contract.
* @return price of RiskCoins
*/
if(_ETHTotal == 0 || _RiskTotal==0){
//Return the default price of _currentPrice * Multiplier
return wmul( _currentPrice , Multiplier);
} else {
if(hmore( wmul(_ETHTotal , _currentPrice),_StaticTotal)){ //_ETHTotal*_currentPrice>_StaticTotal
//Risk price is positive
return wdiv(wsub(wmul(_ETHTotal , _currentPrice) , _StaticTotal) , _RiskTotal); // (_ETHTotal * _currentPrice) - _StaticTotal) / _RiskTotal
} else {
//RiskPrice is negative
return 0;
}
}
}
function RiskPrice(uint128 _currentPrice)
constant
returns (uint128 price) {
/** @dev Allows users to query price of RiskCoins in terms of base currency, using current quantities of coins
* @param _currentPrice Current price of ETH in Base currency.
* @return price of RiskCoins
*/
return RiskPrice(_currentPrice,cast(Static.totalSupply()),cast(Risk.totalSupply()),wsub(cast(this.balance),PendingETH));
}
function LastRiskPrice()
constant
returns (uint128 price) {
/** @dev Allows users to query the last price of RiskCoins in terms of base currency
* @return price of RiskCoins
*/
return RiskPrice(lastPrice);
}
function Leverage() public
constant
returns (uint128) {
/** @dev Returns the ratio at which Riskcoin grows in value for the equivalent growth in ETH price
* @return ratio
*/
if(Risk.totalSupply()>0){
return wdiv(cast(this.balance) , cast(Risk.totalSupply())); // this.balance/Risk.totalSupply
}else{
return 0;
}
}
function Strike() public
constant
returns (uint128) {
/** @dev Returns the current price at which the Risk price goes negative
* @return Risk price in underlying per ETH
*/
if(this.balance>0){
return wdiv(cast(Static.totalSupply()) , cast(this.balance)); //Static.totalSupply / this.balance
}else{
return 0;
}
}
//****************************//
// Only owner can access the following functions
function setFee(uint128 _newFee)
onlyOwner {
/** @dev Allows the minting fee to be changed, only owner can modify
* @param _newFee Size of new fee
* return nothing
*/
mintFee=_newFee;
}
function setCoins(address newRisk,address newStatic)
updates
onlyOwner
writeOnce {
/** @dev Allows the minting fee to be reduced, only owner can modify once, Triggers the pricer to be updated
* @param newRisk Address of Riskcoin contract
* @param newStatic Address of StatiCoin contract
* return nothing
*/
Risk=I_coin(newRisk);
Static=I_coin(newStatic);
PRICER_DELAY = 2 days;
}
//****************************//
// Only Pricer can access the following function
function PriceReturn(uint _TransID,uint128 _Price)
onlyPricer {
/** @dev Return function for the Pricer contract only. Controls melting and minting of new coins.
* @param _TransID Tranasction ID issued by the minter.
* @param _Price Quantity of Base currency per ETH delivered by the Pricer contract
* Nothing returned. One of 4 functions is implemented
*/
Trans memory details=pending[_TransID][0];//Get the details for this transaction.
if(0==_Price||frozen){ //If there is an error in pricing or contract is frozen, use the old price
_Price=lastPrice;
} else {
if(Static.totalSupply()>0 && Risk.totalSupply()>0) {// dont update if there are coins missing
lastPrice=_Price; // otherwise update the last price
}
}
//Mint some new StatiCoins
if(Action.NewStatic==details.action){
ActionNewStatic(details,_TransID, _Price);
}
//Melt some old StatiCoins
if(Action.RetStatic==details.action){
ActionRetStatic(details,_TransID, _Price);
}
//Mint some new Risk coins
if(Action.NewRisk==details.action){
ActionNewRisk(details,_TransID, _Price);
}
//Melt some old Risk coin
if(Action.RetRisk==details.action){
ActionRetRisk(details,_TransID, _Price);
}
//Remove the transaction from the blockchain (saving some gas)
TransCompleted=_TransID;
delete pending[_TransID];
}
//****************************//
// Only internal functions now
function ActionNewStatic(Trans _details, uint _TransID, uint128 _Price)
internal {
/** @dev Internal function to create new StatiCoins based on transaction data in the Pending queue. If not enough spare StatiCoins are available then ETH is refunded.
* @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request.
* @param _TransID ID of the transaction (as stored in this contract).
* @param _Price Current 24 hour average price as returned by the oracle in the pricer contract.
* @return function returns nothing, but adds StatiCoins to the users address and events are created
*/
//log0('NewStatic');
//if(Action.NewStatic<>_details.action){revert();} //already checked
uint128 CurRiskPrice=RiskPrice(_Price);
uint128 AmountReturn;
uint128 AmountMint;
//Calculates the amount of ETH that can be added to create StatiCoins (excluding the amount already sent and stored in the contract)
uint128 StaticAvail = StaticEthAvailable(cast(Risk.totalSupply()), wsub(cast(this.balance),PendingETH));
// If the amount sent is less than the Static amount available, everything is fine. Nothing needs to be returned.
if (wless(_details.amount,StaticAvail)) {
// restrictions do not hamper the creation of a StatiCoin
AmountMint = _details.amount;
AmountReturn = 0;
} else {
// Amount of Static is less than amount requested.
// Take all the StatiCoins available.
// Maybe there is zero Static available, so all will be returned.
AmountMint = StaticAvail;
AmountReturn = wsub(_details.amount , StaticAvail) ;
}
if(0 == CurRiskPrice){
// return all the ETH
AmountReturn = _details.amount;
//AmountMint = 0; //not required as Risk price = 0
}
//Static can be added when Risk price is positive and leverage is below the limit
if(CurRiskPrice > 0 && StaticAvail>0 ){
// Dont create if CurRiskPrice is 0 or there is no Static available (leverage is too high)
//log0('leverageOK');
Static.mintCoin(_details.holder, uint256(wmul(AmountMint , _Price))); //request coins from the Static creator contract
EventCreateStatic(_details.holder, wmul(AmountMint , _Price), _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price
PendingETH=wsub(PendingETH,AmountMint);
}
if (AmountReturn>0) {
// return some money because not enough StatiCoins are available
bytes memory calldata; // define a blank `bytes`
exec(_details.holder,calldata, AmountReturn); //Refund ETH from this contract
PendingETH=wsub(PendingETH,AmountReturn);
}
}
function ActionNewRisk(Trans _details, uint _TransID,uint128 _Price)
internal {
/** @dev Internal function to create new Risk coins based on transaction data in the Pending queue. Risk coins can only be created if the price is above zero
* @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request.
* @param _TransID ID of the transaction (as stored in this contract).
* @param _Price Current 24 hour average price as returned by the oracle in the pricer contract.
* @return function returns nothing, but adds Riskcoins to the users address and events are created
*/
//log0('NewRisk');
//if(Action.NewRisk<>_details.action){revert();} //already checked
// Get the Risk price using the amount of ETH in the contract before this transaction existed
uint128 CurRiskPrice;
if(wless(cast(this.balance),PendingETH)){
CurRiskPrice=0;
} else {
CurRiskPrice=RiskPrice(_Price,cast(Static.totalSupply()),cast(Risk.totalSupply()),wsub(cast(this.balance),PendingETH));
}
if(CurRiskPrice>0){
uint128 quantity=wdiv(wmul(_details.amount , _Price),CurRiskPrice); // No of Riskcoins = _details.amount * _Price / CurRiskPrice
Risk.mintCoin(_details.holder, uint256(quantity) ); //request coins from the Riskcoin creator contract
EventCreateRisk(_details.holder, quantity, _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price
} else {
// Don't create if CurRiskPrice is 0, Return all the ETH originally sent
bytes memory calldata; // define a blank `bytes`
exec(_details.holder,calldata, _details.amount);
}
PendingETH=wsub(PendingETH,_details.amount);
}
function ActionRetStatic(Trans _details, uint _TransID,uint128 _Price)
internal {
/** @dev Internal function to Return StatiCoins based on transaction data in the Pending queue. Static can be returned at any time.
* @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request.
* @param _TransID ID of the transaction (as stored in this contract).
* @param _Price Current 24 hour average price as returned by the oracle in the pricer contract.
* @return function returns nothing, but removes StatiCoins from the user's address, sends ETH and events are created
*/
//if(Action.RetStatic<>_details.action){revert();} //already checked
//log0('RetStatic');
uint128 _ETHReturned;
if(0==Risk.totalSupply()){_Price=lastPrice;} //No Risk coins for balance so use fixed price
_ETHReturned = wdiv(_details.amount , _Price); //_details.amount / _Price
if (Static.meltCoin(_details.holder,_details.amount)){
// deducted first, will add back if Returning ETH goes wrong.
EventRedeemStatic(_details.holder,_details.amount ,_TransID, _Price);
if (wless(cast(this.balance),_ETHReturned)) {
_ETHReturned=cast(this.balance);//Not enough ETH available. Return all Eth in the contract
}
bytes memory calldata; // define a blank `bytes`
if (tryExec(_details.holder, calldata, _ETHReturned)) {
//ETH returned successfully
} else {
// there was an error, so add back the amount previously deducted
Static.mintCoin(_details.holder,_details.amount); //Add back the amount requested
EventCreateStatic(_details.holder,_details.amount ,_TransID, _Price); //redo the creation event
}
if ( 0==this.balance) {
Bankrupt();
}
}
}
function ActionRetRisk(Trans _details, uint _TransID,uint128 _Price)
internal {
/** @dev Internal function to Return Riskcoins based on transaction data in the Pending queue. Riskcoins can be returned so long as the Risk price is greater than 0.
* @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request.
* @param _TransID ID of the transaction (as stored in this contract).
* @param _Price Current 24 hour average price as returned by the oracle in the Pricer contract.
* @return function returns nothing, but removes StatiCoins from the users address, sends ETH and events are created
*/
//if(Action.RetRisk<>_details.action){revert();} //already checked
//log0('RetRisk');
uint128 _ETHReturned;
uint128 CurRiskPrice;
//if(0==Static.totalSupply()){_Price=lastPrice};// no StatiCoins, so all Risk coins are worth the same. // _ETHReturned = _details.amount / _RiskTotal * _ETHTotal
CurRiskPrice=RiskPrice(_Price);
if(CurRiskPrice>0){
_ETHReturned = wdiv( wmul(_details.amount , CurRiskPrice) , _Price); // _details.amount * CurRiskPrice / _Price
if (Risk.meltCoin(_details.holder,_details.amount )){
// Coins are deducted first, will add back if returning ETH goes wrong.
EventRedeemRisk(_details.holder,_details.amount ,_TransID, _Price);
if ( wless(cast(this.balance),_ETHReturned)) { // should never happen, but just in case
_ETHReturned=cast(this.balance);
}
bytes memory calldata; // define a blank `bytes`
if (tryExec(_details.holder, calldata, _ETHReturned)) {
//Returning ETH went ok.
} else {
// there was an error, so add back the amount previously deducted from the Riskcoin contract
Risk.mintCoin(_details.holder,_details.amount);
EventCreateRisk(_details.holder,_details.amount ,_TransID, _Price);
}
}
} else {
// Risk price is zero so can't do anything. Call back and delete the transaction from the contract
}
}
function IsWallet(address _address)
internal
returns(bool){
/**
* @dev checks that _address is not a contract.
* @param _address to check
* @return True if not a contract,
*/
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_address)
}
return(0==codeLength);
}
function RetCoinInternal(uint128 _Quantity, uint128 _AmountETH, address _user, Action _action)
internal
updates
returns (uint _TransID) {
/** @dev Requests coins be melted and ETH returned
* @param _Quantity of Static or Risk coins to be melted0
* @param _AmountETH Amount of eth sent to this contract to cover oracle fee. Excess is returned.
* @param _user Address to whom the returned ETH will be sent.
* @param _action Allows Static or Risk coins to be returned
* @return transaction ID which can be viewed in the Pending mapping
*/
require(IsWallet(_user));
uint128 refund;
uint128 Fee=pricer.queryCost(); //Get the cost of querying the pricer contract
if(wless(_AmountETH,Fee)){
revert(); //log0('Not enough ETH to mint');
} else {
refund=wsub(_AmountETH,Fee);//Returning coins has had too much ETH sent, so return it.
}
if(0==_Quantity){revert();}// quantity has to be non zero
TransID++;
uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to get the price. The Fee also cover calling the function PriceReturn at a later time.
pending[TransID].push(Trans(_Quantity,_user,_action,bytes32(PricerID))); //Add a transaction to the Pending queue.
_TransID=TransID; //return the transaction ID to the user
_user.transfer(uint256(refund)); //Return ETH if too much has been sent to cover the pricer
}
function NewCoinInternal(address _user, uint128 _amount, Action _action)
internal
updates
LockIfUnwritten
LockIfFrozen
returns (uint _TransID) {
/** @dev Requests new coins be made
* @param _user Address for whom the coins are to be created
* @param _amount Amount of eth sent to this contract
* @param _action Allows Static or Risk coins to be minted
* @return transaction ID which can be viewed in the pending mapping
*/
require(IsWallet(_user));
uint128 toCredit;
uint128 Fee=wmax(wmul(_amount,mintFee),pricer.queryCost()); // fee is the maxium of the pricer query cost and a mintFee% of value sent
if(wless(_amount,Fee)) revert(); //log0('Not enough ETH to mint');
TransID++;
uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to return the price
toCredit=wsub(_amount,Fee);
pending[TransID].push(Trans(toCredit,_user,_action,bytes32(PricerID))); //Store the transaction ID and data ready for later recall
PendingETH=wadd(PendingETH,toCredit);
_TransID=TransID;//return the transaction ID for this contract to the user
}
function Bankrupt()
internal {
EventBankrupt();
// Reset the contract
Static.kill(); //delete all current Static tokens
Risk.kill(); //delete all current Risk tokens
//need to create new coins externally, too much gas is used if done here.
frozen=false;
written=false; // Reset the writeOnce and LockIfUnwritten modifiers
}
}
|
checks that _address is not a contract. _address to check return True if not a contract,/ Retrieve the size of the code on target address, this needs assembly .
|
function IsWallet(address _address)
internal
assembly {
codeLength := extcodesize(_address)
}
return(0==codeLength);
| 13,108,954
|
./full_match/80001/0x297b11cea5573deE65C587e53de7C1d699d2D128/sources/contracts/3_Ballot.sol
|
Only Owner Functions
|
function setRevealMode() public onlyOwner {
RevealMode = true;
}
| 9,458,502
|
pragma solidity ^0.4.15;
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
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;
}
}
contract StandardToken is ERC20, SafeMath {
/* Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
/* Actual balances of token holders */
mapping(address => uint) balances;
/* approve() allowances */
mapping (address => mapping (address => uint)) allowed;
/* Interface declaration */
function isToken() public constant returns (bool weAre) {
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
// 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
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract QVT is StandardToken {
string public name = "QVT";
string public symbol = "QVT";
uint public decimals = 18;
uint public multiplier = 1000000000000000000; // two decimals to the left
/**
* Boolean contract states
*/
bool public halted = false; //the founder address can set this to true to halt the crowdsale due to emergency
bool public freeze = true; //Freeze state
uint public roundCount = 1; //Round state
bool public isDayFirst = false; //Pre-ico state
bool public isDaySecond = false; //Pre-ico state
bool public isDayThird = false; //Pre-ico state
bool public isPreSale = false; // Pre-sale bonus
/**
* Initial founder address (set in constructor)
* All deposited ETH will be forwarded to this address.
* Address is a multisig wallet.
*/
address public founder = 0x0;
address public owner = 0x0;
/**
* Token count
*/
uint public totalTokens = 21600000;
uint public team = 3420000;
uint public bounty = 180000 * multiplier; // Bounty count
uint public preIcoSold = 0;
/**
* Ico and pre-ico cap
*/
uint public icoCap = 18000000; // Max amount raised during crowdsale 18000 ether
/**
* Statistic values
*/
uint public presaleTokenSupply = 0; // This will keep track of the token supply created during the crowdsale
uint public presaleEtherRaised = 0; // This will keep track of the Ether raised during the crowdsale
event Buy(address indexed sender, uint eth, uint fbt);
/* This generates a public event on the blockchain that will notify clients */
event TokensSent(address indexed to, uint256 value);
event ContributionReceived(address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function QVT(address _founder) payable {
owner = msg.sender;
founder = _founder;
team = safeMul(team, multiplier);
// Total supply is 18000000
totalSupply = safeMul(totalTokens, multiplier);
balances[owner] = safeSub(totalSupply, team);
// Move team token pool to founder balance
balances[founder] = team;
TokensSent(founder, team);
Transfer(owner, founder, team);
}
/**
* 1 QVT = 1 FINNEY
* Rrice is 1000 Qvolta for 1 ETH
*/
function price() constant returns (uint){
return 1 finney;
}
/**
* The basic entry point to participate the crowdsale process.
*
* Pay for funding, get invested tokens back in the sender address.
*/
function buy() public payable returns(bool) {
processBuy(msg.sender, msg.value);
return true;
}
function processBuy(address _to, uint256 _value) internal returns(bool) {
// Buy allowed if contract is not on halt
require(!halted);
// Amount of wei should be more that 0
require(_value>0);
// Count expected tokens price
uint tokens = _value / price();
// Total tokens should be more than user want's to buy
require(balances[owner]>safeMul(tokens, multiplier));
// Gave pre-sale bonus
if (isPreSale) {
tokens = tokens + (tokens / 2);
}
// Gave +30% of tokents on first day
if (isDayFirst) {
tokens = tokens + safeMul(safeDiv(tokens, 10), 3);
}
// Gave +20% of tokents on second day
if (isDaySecond) {
tokens = tokens + safeDiv(tokens, 5);
}
// Gave +10% of tokents on third day
if (isDayThird) {
tokens = tokens + safeDiv(tokens, 10);
}
// Check that required tokens count are less than tokens already sold on ico sub pre-ico
require(safeAdd(presaleTokenSupply, tokens) < icoCap);
// Send wei to founder address
founder.transfer(_value);
// Add tokens to user balance and remove from totalSupply
balances[_to] = safeAdd(balances[_to], safeMul(tokens, multiplier));
// Remove sold tokens from total supply count
balances[owner] = safeSub(balances[owner], safeMul(tokens, multiplier));
presaleTokenSupply = safeAdd(presaleTokenSupply, tokens);
presaleEtherRaised = safeAdd(presaleEtherRaised, _value);
// /* Emit log events */
Buy(_to, _value, safeMul(tokens, multiplier));
TokensSent(_to, safeMul(tokens, multiplier));
ContributionReceived(_to, _value);
Transfer(owner, _to, safeMul(tokens, multiplier));
return true;
}
/**
* Emit log events
*/
function sendEvents(address to, uint256 value, uint tokens) internal {
// Send buy Qvolta token action
Buy(to, value, safeMul(tokens, multiplier));
TokensSent(to, safeMul(tokens, multiplier));
ContributionReceived(to, value);
Transfer(owner, to, safeMul(tokens, multiplier));
}
/**
* Run mass transfers with pre-ico *2 bonus
*/
function proceedPreIcoTransactions(address[] toArray, uint[] valueArray) onlyOwner() {
uint tokens = 0;
address to = 0x0;
uint value = 0;
for (uint i = 0; i < toArray.length; i++) {
to = toArray[i];
value = valueArray[i];
tokens = value / price();
tokens = tokens + tokens;
balances[to] = safeAdd(balances[to], safeMul(tokens, multiplier));
balances[owner] = safeSub(balances[owner], safeMul(tokens, multiplier));
preIcoSold = safeAdd(preIcoSold, tokens);
sendEvents(to, value, tokens);
}
}
/**
* Emergency Stop ICO.
*/
function halt() onlyOwner() {
halted = true;
}
function unHalt() onlyOwner() {
halted = false;
}
/**
* Transfer team tokens to target address
*/
function sendBounty(address _to, uint256 _value) onlyOwner() {
require(bounty > _value);
bounty = safeSub(bounty, _value);
balances[_to] = safeAdd(balances[_to], safeMul(_value, multiplier));
// /* Emit log events */
TokensSent(_to, safeMul(_value, multiplier));
Transfer(owner, _to, safeMul(_value, multiplier));
}
/**
* Transfer bounty to target address from bounty pool
*/
function sendSupplyTokens(address _to, uint256 _value) onlyOwner() {
balances[owner] = safeSub(balances[owner], safeMul(_value, multiplier));
balances[_to] = safeAdd(balances[_to], safeMul(_value, multiplier));
// /* Emit log events */
TokensSent(_to, safeMul(_value, multiplier));
Transfer(owner, _to, safeMul(_value, multiplier));
}
/**
* ERC 20 Standard Token interface transfer function
*
* Prevent transfers until halt period is over.
*/
function transfer(address _to, uint256 _value) isAvailable() returns (bool success) {
return super.transfer(_to, _value);
}
/**
* ERC 20 Standard Token interface transfer function
*
* Prevent transfers until halt period is over.
*/
function transferFrom(address _from, address _to, uint256 _value) isAvailable() returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
/**
* Burn all tokens from a balance.
*/
function burnRemainingTokens() isAvailable() onlyOwner() {
Burn(owner, balances[owner]);
balances[owner] = 0;
}
/**
* Set day first bonus
*/
function setDayFirst() onlyOwner() {
isDayFirst = true;
isDaySecond = false;
isDayThird = false;
}
/**
* Set day second bonus
*/
function setDaySecond() onlyOwner() {
isDayFirst = false;
isDaySecond = true;
isDayThird = false;
}
/**
* Set day first bonus
*/
function setDayThird() onlyOwner() {
isDayFirst = false;
isDaySecond = false;
isDayThird = true;
}
/**
* Set day first bonus
*/
function setBonusOff() onlyOwner() {
isDayFirst = false;
isDaySecond = false;
isDayThird = false;
}
/**
* Set pre-sale bonus
*/
function setPreSaleOn() onlyOwner() {
isPreSale = true;
}
/**
* Set pre-sale bonus off
*/
function setPreSaleOff() onlyOwner() {
isPreSale = false;
}
/**
* Start new investment round
*/
function startNewRound() onlyOwner() {
require(roundCount < 5);
roundCount = roundCount + 1;
balances[owner] = safeAdd(balances[owner], safeMul(icoCap, multiplier));
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier isAvailable() {
require(!halted && !freeze);
_;
}
/**
* Just being sent some cash? Let's buy tokens
*/
function() payable {
buy();
}
/**
* Freeze and unfreeze ICO.
*/
function freeze() onlyOwner() {
freeze = true;
}
function unFreeze() onlyOwner() {
freeze = false;
}
/**
* Replaces an owner
*/
function changeOwner(address _to) onlyOwner() {
balances[_to] = balances[owner];
balances[owner] = 0;
owner = _to;
}
/**
* Replaces a founder, transfer team pool to new founder balance
*/
function changeFounder(address _to) onlyOwner() {
balances[_to] = balances[founder];
balances[founder] = 0;
founder = _to;
}
}
|
Buy allowed if contract is not on halt Amount of wei should be more that 0 Count expected tokens price Total tokens should be more than user want&39;s to buy Gave pre-sale bonus Gave +30% of tokents on first day Gave +20% of tokents on second day Gave +10% of tokents on third day
|
function processBuy(address _to, uint256 _value) internal returns(bool) {
require(!halted);
require(_value>0);
uint tokens = _value / price();
require(balances[owner]>safeMul(tokens, multiplier));
if (isPreSale) {
tokens = tokens + (tokens / 2);
}
if (isDayFirst) {
tokens = tokens + safeMul(safeDiv(tokens, 10), 3);
}
if (isDaySecond) {
tokens = tokens + safeDiv(tokens, 5);
}
if (isDayThird) {
tokens = tokens + safeDiv(tokens, 10);
}
presaleTokenSupply = safeAdd(presaleTokenSupply, tokens);
presaleEtherRaised = safeAdd(presaleEtherRaised, _value);
TokensSent(_to, safeMul(tokens, multiplier));
ContributionReceived(_to, _value);
Transfer(owner, _to, safeMul(tokens, multiplier));
return true;
}
| 7,929,275
|
pragma solidity ^0.5.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './CTokenInterface.sol';
import './ComptrollerInterface.sol';
contract MyDeFiProject {
IERC20 dai;
CTokenInterface cDai;
IERC20 bat;
CTokenInterface cBat;
ComptrollerInterface comptroller;
constructor(
address _dai,
address _cDai,
address _bat,
address _cBat,
address _comptroller) public {
dai = IERC20(_dai);
cDai = CTokenInterface(_cDai);
bat = IERC20(_bat);
cBat = CTokenInterface(_cBat);
comptroller = ComptrollerInterface(_comptroller);
}
function invest() external {
dai.approve(address(cDai), 10000);
cDai.mint(10000);
}
function cashOut() external {
uint balance = cDai.balanceOf(address(this));
cDai.redeem(balance);
}
function borrow() external {
//Create cDai
dai.approve(address(cDai), 10000);
cDai.mint(10000);
//Include cDai in compound collateral
address[] memory markets = new address[](1);
markets[0] = address(cDai);
comptroller.enterMarkets(markets);
//create loan
cBat.borrow(100);
}
function payBack() external {
bat.approve(address(cBat), 100);
cBat.repayBorrow(100);
//(optional, if you want to get back collateral)
uint balance = cDai.balanceOf(address(this));
cDai.redeem(balance);
}
}
|
Create cDaiInclude cDai in compound collateralcreate loan
|
function borrow() external {
dai.approve(address(cDai), 10000);
cDai.mint(10000);
address[] memory markets = new address[](1);
markets[0] = address(cDai);
comptroller.enterMarkets(markets);
cBat.borrow(100);
}
| 5,459,880
|
/* 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;
}
|
solhint-disable-next-line no-empty-blocks
|
function pauseAllPendingClaimsVoting() external pure {}
| 2,578,472
|
/**
*Submitted for verification at Etherscan.io on 2020-08-14
*/
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface ERC20 {
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns(bool);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ethrim is ERC20 {
using SafeMath for uint256;
address public owner;
//1 token = 0.01 eth
uint256 public tokenCost = 0.01 ether;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply = 1e9* 10**18;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
constructor () public {
symbol = "ETRM";
name = "Ethrim";
decimals = 18;
owner = msg.sender;
balances[owner] = totalSupply;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner");
_;
}
/**
* @dev To change burnt Address
* @param _newOwner New owner address
*/
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
require(_newOwner != address(0), "Invalid Address");
owner = _newOwner;
uint256 _value = balances[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_newOwner] = balances[_newOwner].add(_value);
//minting total supply tokens
return true;
}
function getAmountOfToken(uint256 amount) public view returns (uint256) {
uint256 tokenValue = (amount.mul(10 ** 18)).div(tokenCost);
return tokenValue;
}
/**
* @dev Check balance of the holder
* @param _owner Token holder address
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Transfer token to specified address
* @param _to Receiver address
* @param _value Amount of the tokens
*/
function transfer(address _to, uint256 _value) public override returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from The holder address
* @param _to The Receiver address
* @param _value the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool){
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve respective tokens for spender
* @param _spender Spender address
* @param _value Amount of tokens to be allowed
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev To view approved balance
* @param _owner Holder address
* @param _spender Spender address
*/
function allowance(address _owner, address _spender) public override view returns (uint256) {
return allowed[_owner][_spender];
}
function mint(uint256 _tokens) public returns (bool) {
balances[owner] = balances[owner].add(_tokens);
totalSupply = totalSupply.add(_tokens);
return true;
}
}
contract Referral {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid = 0;
//token variable
Ethrim public ETRM;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
}
contract ProjectEthrim {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//levelInecntives
struct incentiveStruct {
uint256 directNumerator;
uint256 inDirectNumerator;
}
//owner who deploys contracts
address public owner;
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid;
//time limit for each level
uint256 public PERIOD_LENGTH = 60 days;
//no of users in each level
uint256 REFERRALS_LIMIT = 5;
//maximum level from 0 to 7
uint256 MAX_LEVEL = 7;
//precenateg denominator- 100= 10000
uint256 public percentageDenominator = 10000;
//token per level i.e, for L1-> 1*25, L2-> 2*25
uint256 tokenPerLevel = 25;
//token variable
Ethrim public ETRM;
//Referral contract address
Referral public OldEthrimObj;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
//maps level incentive by level
mapping(uint256 => incentiveStruct) public LEVEL_INCENTIVE;
//check if user not registered previously
modifier userRegistered() {
require(users[msg.sender].isExist == true, "User is not registered");
_;
}
//check if referrer id is invalid or not
modifier validReferrerID(uint256 _referrerID) {
require( _referrerID > 0 && _referrerID <= last_uid, "Invalid referrer ID");
_;
}
//check if user is already registerd
modifier userNotRegistered() {
require(users[msg.sender].isExist == false, "User is already registered");
_;
}
//check if selected level is valid or not
modifier validLevel(uint256 _level) {
require(_level > 0 && _level <= MAX_LEVEL, "Invalid level entered");
_;
}
event RegisterUserEvent(address indexed user, address indexed referrer, uint256 time);
event BuyLevelEvent(address indexed user, uint256 indexed level, uint256 time);
constructor(address payable _ownerAddress1, address payable _ownerAddress2, address _tokenAddr, address payable _oldEthrimAddr) public {
require(_ownerAddress1 != address(0), "Invalid owner address 1");
require(_ownerAddress2 != address(0), "Invalid owner address 2");
require(_tokenAddr != address(0), "Invalid token address");
owner = msg.sender;
ownerAddress1 = _ownerAddress1;
ownerAddress2 = _ownerAddress2;
ETRM = Ethrim(_tokenAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
last_uid = OldEthrimObj.last_uid();
//20% = 2000
LEVEL_INCENTIVE[1].directNumerator = 2000;
//10% =1000
LEVEL_INCENTIVE[1].inDirectNumerator = 1000;
//10% = 1000
LEVEL_INCENTIVE[2].directNumerator = 1000;
//5% = 500
LEVEL_INCENTIVE[2].inDirectNumerator = 500;
//6.67% = 667
LEVEL_INCENTIVE[3].directNumerator = 667;
//3.34% = 334
LEVEL_INCENTIVE[3].inDirectNumerator = 334;
//5% = 500
LEVEL_INCENTIVE[4].directNumerator = 500;
//2.5% = 1000
LEVEL_INCENTIVE[4].inDirectNumerator = 250;
//4% = 400
LEVEL_INCENTIVE[5].directNumerator = 400;
//2% = 200
LEVEL_INCENTIVE[5].inDirectNumerator = 200;
//3.34% = 334
LEVEL_INCENTIVE[6].directNumerator = 334;
//1.7% = 170
LEVEL_INCENTIVE[6].inDirectNumerator = 170;
//2.86% = 286
LEVEL_INCENTIVE[7].directNumerator = 286;
//1.43% = 143
LEVEL_INCENTIVE[7].inDirectNumerator = 143;
}
/**
* @dev User registration
*/
function registerUser(uint256 _referrerUniqueID) public payable userNotRegistered() validReferrerID(_referrerUniqueID) {
require(msg.value > 0, "ether value is 0");
uint256 referrerUniqueID = _referrerUniqueID;
if (users[userAddresses[referrerUniqueID]].referral.length >= REFERRALS_LIMIT) {
referrerUniqueID = users[findFreeReferrer(userAddresses[referrerUniqueID])].id;
}
last_uid = last_uid + 1;
users[msg.sender] = UserStruct({
isExist: true,
id: last_uid,
referrerID: referrerUniqueID,
currentLevel: 1,
totalEarningEth: 0,
referral: new address[](0),
levelExpiresAt: now.add(PERIOD_LENGTH)
});
userAddresses[last_uid] = msg.sender;
users[userAddresses[referrerUniqueID]].referral.push(msg.sender);
uint256 tokenAmount = getTokenAmountByLevel(1);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline level
address userUpline = userAddresses[referrerUniqueID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, 1);
emit RegisterUserEvent(msg.sender, userAddresses[referrerUniqueID], now);
}
/**
* @dev View free Referrer Address
*/
function findFreeReferrer(address _userAddress) public view returns (address) {
if (users[_userAddress].referral.length < REFERRALS_LIMIT){
return _userAddress;
}
address[] memory referrals = new address[](254);
referrals[0] = users[_userAddress].referral[0];
referrals[1] = users[_userAddress].referral[1];
referrals[2] = users[_userAddress].referral[2];
referrals[3] = users[_userAddress].referral[3];
referrals[4] = users[_userAddress].referral[4];
address referrer;
for (uint256 i = 0; i < 1048576; i++) {
if (users[referrals[i]].referral.length < REFERRALS_LIMIT) {
referrer = referrals[i];
break;
}
if (i >= 8191) {
continue;
}
//adding pyramid trees
referrals[((i.add(1).mul(5))).add(i.add(0))] = users[referrals[i]].referral[0];
referrals[((i.add(1).mul(5))).add(i.add(1))] = users[referrals[i]].referral[1];
referrals[((i.add(1).mul(5))).add(i.add(2))] = users[referrals[i]].referral[2];
referrals[((i.add(1).mul(5))).add(i.add(3))] = users[referrals[i]].referral[3];
referrals[((i.add(1).mul(5))).add(i.add(4))] = users[referrals[i]].referral[4];
}
require(referrer != address(0), 'Referrer not found');
return referrer;
}
function transferLevelPayment(address _userUpline, uint256 _levelForIncentive) internal {
//ether value
uint256 etherValue = msg.value;
address uplineAddress = _userUpline;
//current upline to be sent money
uint256 uplineLevel = users[uplineAddress].currentLevel;
//upline user level expiry time
uint256 uplineUserLevelExpiry = users[uplineAddress].levelExpiresAt;
//uid
uint256 uplineUID = users[uplineAddress].id;
//incentive amount total
uint256 amountSentAsIncetives = 0;
uint256 count = 1;
while(uplineUID > 0 && count <= 7) {
address payable receiver = payable(uplineAddress);
if(count == 1) {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].directNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
} else {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].inDirectNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
}
//get upline level
uint256 uplineReferrerId = users[uplineAddress].referrerID;
uplineAddress = userAddresses[uplineReferrerId];
//level of upline for user
uplineLevel = users[uplineAddress].currentLevel;
uplineUID = users[uplineAddress].id;
count++;
}
uint256 remAmount = msg.value.sub(amountSentAsIncetives);
transferToOwner(remAmount);
}
function buyLevel(uint256 _level) public payable userRegistered() validLevel(_level){
require(msg.value > 0, "ether value is 0");
uint256 userCurrentLevel = users[msg.sender].currentLevel;
require((_level == userCurrentLevel.add(1)) || (userCurrentLevel == 7 && _level == 7), "Invalid level upgrade value");
users[msg.sender].levelExpiresAt = now.add(PERIOD_LENGTH);
users[msg.sender].currentLevel = _level;
uint256 tokenAmount = getTokenAmountByLevel(_level);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline user address
address userUpline = userAddresses[users[msg.sender].referrerID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, _level);
emit BuyLevelEvent(msg.sender, _level, now);
}
/**
* @dev Contract balance withdraw
*/
function failSafe() public returns (bool) {
require(msg.sender == owner, "only Owner Wallet");
require(address(this).balance > 0, "Insufficient balance");
transferToOwner(address(this).balance);
return true;
}
function transferToOwner(uint256 _amount) internal{
uint256 amount = _amount.div(2);
(ownerAddress1).transfer(amount);
(ownerAddress2).transfer(amount);
}
/**
* @dev Total earned ETH
*/
function getTotalEarnedEther() public view returns (uint256) {
uint256 totalEth;
for (uint256 i = 1; i <= last_uid; i++) {
totalEth = totalEth.add(users[userAddresses[i]].totalEarningEth);
}
return totalEth;
}
/**
* @dev get token amount by level i.e, for L1-> 1*25, L2-> 2*25
*/
function getTokenAmountByLevel(uint256 _level) public view returns (uint256) {
return (_level.mul(tokenPerLevel)).mul(10**18);
}
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
/**
* @dev View level expired time
*/
function viewUserLevelExpired(address _userAddress) external view returns (uint256) {
return users[_userAddress].levelExpiresAt;
}
/**
* @dev Update old contract data
*/
function oldEthrimSync(uint256 limit) public {
require(address(OldEthrimObj) != address(0), "Initialize closed");
require(msg.sender == owner, "Access denied");
uint256 oldUserId = 0;
for (uint256 i = 0; i <= limit; i++) {
UserStruct memory oldUserStruct;
address oldUser = OldEthrimObj.userAddresses(oldUserId);
(oldUserStruct.isExist,
oldUserStruct.id,
oldUserStruct.referrerID,
oldUserStruct.currentLevel,
oldUserStruct.totalEarningEth,
oldUserStruct.levelExpiresAt) = OldEthrimObj.users(oldUser);
users[oldUser].isExist = oldUserStruct.isExist;
users[oldUser].id = oldUserId;
users[oldUser].referrerID = oldUserStruct.referrerID;
users[oldUser].levelExpiresAt = oldUserStruct.levelExpiresAt;
users[oldUser].currentLevel = oldUserStruct.currentLevel;
users[oldUser].totalEarningEth = oldUserStruct.totalEarningEth;
users[oldUser].referral = OldEthrimObj.viewUserReferral(oldUser);
userAddresses[oldUserId] = oldUser;
oldUserId++;
}
}
// fallback
fallback() external payable {
revert("Invalid Transaction");
}
// receive
receive() external payable {
revert("Invalid Transaction");
}
}
|
Transfer tokens from one address to another _from The holder address _to The Receiver address _value the amount of tokens to be transferred/
|
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool){
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 7,659,489
|
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.
*/
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;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/* Controls state and access rights for contract functions
* @title Operational Control
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
* Inspired and adapted from contract created by OpenZeppelin
* Ref: https://github.com/OpenZeppelin/zeppelin-solidity/
*/
contract OperationalControl {
// Facilitates access & control for the game.
// Roles:
// -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw)
// -The Banker: The Bank can withdraw funds and adjust fees / prices.
// -otherManagers: Contracts that need access to functions for gameplay
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public managerPrimary;
address public managerSecondary;
address public bankManager;
// Contracts that require access for gameplay
mapping(address => uint8) public otherManagers;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
// @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed
bool public error = false;
/// @dev Operation modifiers for limiting access
modifier onlyManager() {
require(msg.sender == managerPrimary || msg.sender == managerSecondary);
_;
}
modifier onlyBanker() {
require(msg.sender == bankManager);
_;
}
modifier onlyOtherManagers() {
require(otherManagers[msg.sender] == 1);
_;
}
modifier anyOperator() {
require(
msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
_;
}
/// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled)
function setOtherManager(address _newOp, uint8 _state) external onlyManager {
require(_newOp != address(0));
otherManagers[_newOp] = _state;
}
/// @dev Assigns a new address to act as the Primary Manager.
function setPrimaryManager(address _newGM) external onlyManager {
require(_newGM != address(0));
managerPrimary = _newGM;
}
/// @dev Assigns a new address to act as the Secondary Manager.
function setSecondaryManager(address _newGM) external onlyManager {
require(_newGM != address(0));
managerSecondary = _newGM;
}
/// @dev Assigns a new address to act as the Banker.
function setBanker(address _newBK) external onlyManager {
require(_newBK != address(0));
bankManager = _newBK;
}
/*** 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 Modifier to allow actions only when the contract has Error
modifier whenError {
require(error);
_;
}
/// @dev Called by any Operator role to pause the contract.
/// Used only if a bug or exploit is discovered (Here to limit losses / damage)
function pause() external onlyManager whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the Game Master
/// @notice This is public rather than external so it can be called by derived contracts.
function unpause() public onlyManager whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
/// @dev Unpauses the smart contract. Can only be called by the Game Master
/// @notice This is public rather than external so it can be called by derived contracts.
function hasError() public onlyManager whenPaused {
error = true;
}
/// @dev Unpauses the smart contract. Can only be called by the Game Master
/// @notice This is public rather than external so it can be called by derived contracts.
function noError() public onlyManager whenPaused {
error = false;
}
}
/**
* @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;
}
/**
* @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 {
}
/**
* @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 existence 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 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);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
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);
}
}
/**
* @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);
}
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
/**
* @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;
// Base Server Address for Token MetaData URI
string internal tokenURIBase;
/**
* @dev Returns an URI for a given token ID. Only returns the based location, you will have to appending a token ID to this
* @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 tokenURIBase;
}
/**
* @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 _uri string URI to assign
*/
function _setTokenURIBase(string _uri) internal {
tokenURIBase = _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 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 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);
// 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;
}
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
/*
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('tokenByIndex(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
/*
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
/*
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('getApproved(uint256)')) ^
bytes4(keccak256('setApprovalForAll(address,bool)')) ^
bytes4(keccak256('isApprovedForAll(address,address)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'));
*/
bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79;
/*
bytes4(keccak256('exists(uint256)'));
*/
/**
* @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
* @dev Returns true for any standardized interfaces implemented by this contract.
* @param _interfaceID bytes4 the interface to check for
* @return true for any standardized interfaces implemented by this contract.
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165)
|| (_interfaceID == InterfaceSignature_ERC721)
|| (_interfaceID == InterfaceSignature_ERC721Enumerable)
|| (_interfaceID == InterfaceSignature_ERC721Metadata));
}
function implementsERC721() public pure returns (bool) {
return true;
}
}
contract CCNFTFactory is ERC721Token, OperationalControl {
/*** EVENTS ***/
/// @dev The Created event is fired whenever a new asset comes into existence.
event AssetCreated(address owner, uint256 assetId, uint256 assetType, uint256 sequenceId, uint256 creationTime);
event DetachRequest(address owner, uint256 assetId, uint256 timestamp);
event NFTDetached(address requester, uint256 assetId);
event NFTAttached(address requester, uint256 assetId);
// Mapping from assetId to uint encoded data for NFT
mapping(uint256 => uint256) internal nftDataA;
mapping(uint256 => uint128) internal nftDataB;
// Mapping from Asset Types to count of that type in exsistance
mapping(uint32 => uint64) internal assetTypeTotalCount;
mapping(uint32 => uint64) internal assetTypeBurnedCount;
// Mapping from index of a Asset Type to get AssetID
mapping(uint256 => mapping(uint32 => uint64) ) internal sequenceIDToTypeForID;
// Mapping from Asset Type to string name of type
mapping(uint256 => string) internal assetTypeName;
// Mapping from assetType to creation limit
mapping(uint256 => uint32) internal assetTypeCreationLimit;
// Indicates if attached system is Active (Transfers will be blocked if attached and active)
bool public attachedSystemActive;
// Is Asset Burning Active
bool public canBurn;
// Time LS Oracle has to respond to detach requests
uint32 public detachmentTime = 300;
/**
* @dev Constructor function
*/
constructor() public {
require(msg.sender != address(0));
paused = true;
error = false;
canBurn = false;
managerPrimary = msg.sender;
managerSecondary = msg.sender;
bankManager = msg.sender;
name_ = "CCNFTFactory";
symbol_ = "CCNFT";
}
/**
* @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) {
uint256 isAttached = getIsNFTAttached(_tokenId);
if(isAttached == 2) {
//One-Time Auth for Physical Card Transfers
require(msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
updateIsAttached(_tokenId, 1);
} else if(attachedSystemActive == true && isAttached >= 1) {
require(msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
}
else {
require(isApprovedOrOwner(msg.sender, _tokenId));
}
_;
}
/** Public Functions */
// Returns the AssetID for the Nth assetID for a specific type
function getAssetIDForTypeSequenceID(uint256 _seqId, uint256 _type) public view returns (uint256 _assetID) {
return sequenceIDToTypeForID[_seqId][uint32(_type)];
}
function getAssetDetails(uint256 _assetId) public view returns(
uint256 assetId,
uint256 ownersIndex,
uint256 assetTypeSeqId,
uint256 assetType,
uint256 createdTimestamp,
uint256 isAttached,
address creator,
address owner
) {
require(exists(_assetId));
uint256 nftData = nftDataA[_assetId];
uint256 nftDataBLocal = nftDataB[_assetId];
assetId = _assetId;
ownersIndex = ownedTokensIndex[_assetId];
createdTimestamp = uint256(uint48(nftData>>160));
assetType = uint256(uint32(nftData>>208));
assetTypeSeqId = uint256(uint64(nftDataBLocal));
isAttached = uint256(uint48(nftDataBLocal>>64));
creator = address(nftData);
owner = ownerOf(_assetId);
}
function totalSupplyOfType(uint256 _type) public view returns (uint256 _totalOfType) {
return assetTypeTotalCount[uint32(_type)] - assetTypeBurnedCount[uint32(_type)];
}
function totalCreatedOfType(uint256 _type) public view returns (uint256 _totalOfType) {
return assetTypeTotalCount[uint32(_type)];
}
function totalBurnedOfType(uint256 _type) public view returns (uint256 _totalOfType) {
return assetTypeBurnedCount[uint32(_type)];
}
function getAssetRawMeta(uint256 _assetId) public view returns(
uint256 dataA,
uint128 dataB
) {
require(exists(_assetId));
dataA = nftDataA[_assetId];
dataB = nftDataB[_assetId];
}
function getAssetIdItemType(uint256 _assetId) public view returns(
uint256 assetType
) {
require(exists(_assetId));
uint256 dataA = nftDataA[_assetId];
assetType = uint256(uint32(dataA>>208));
}
function getAssetIdTypeSequenceId(uint256 _assetId) public view returns(
uint256 assetTypeSequenceId
) {
require(exists(_assetId));
uint256 dataB = nftDataB[_assetId];
assetTypeSequenceId = uint256(uint64(dataB));
}
function getIsNFTAttached( uint256 _assetId)
public view returns(
uint256 isAttached
) {
uint256 nftData = nftDataB[_assetId];
isAttached = uint256(uint48(nftData>>64));
}
function getAssetIdCreator(uint256 _assetId) public view returns(
address creator
) {
require(exists(_assetId));
uint256 dataA = nftDataA[_assetId];
creator = address(dataA);
}
function isAssetIdOwnerOrApproved(address requesterAddress, uint256 _assetId) public view returns(
bool
) {
return isApprovedOrOwner(requesterAddress, _assetId);
}
function getAssetIdOwner(uint256 _assetId) public view returns(
address owner
) {
require(exists(_assetId));
owner = ownerOf(_assetId);
}
function getAssetIdOwnerIndex(uint256 _assetId) public view returns(
uint256 ownerIndex
) {
require(exists(_assetId));
ownerIndex = ownedTokensIndex[_assetId];
}
/// @param _owner The owner whose ships tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire NFT owners array looking for NFT belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 resultIndex = 0;
// We count on the fact that all Asset have IDs starting at 0 and increasing
// sequentially up to the total count.
uint256 _itemIndex;
for (_itemIndex = 0; _itemIndex < tokenCount; _itemIndex++) {
result[resultIndex] = tokenOfOwnerByIndex(_owner,_itemIndex);
resultIndex++;
}
return result;
}
}
// Get the name of the Asset type
function getTypeName (uint32 _type) public returns(string) {
return assetTypeName[_type];
}
/**
* @dev Transfers the ownership of a given token ID to another address, modified to prevent transfer if attached and system is active
*/
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);
}
function multiBatchTransferFrom(
uint256[] _assetIds,
address[] _fromB,
address[] _toB)
public
{
uint256 _id;
address _to;
address _from;
for (uint256 i = 0; i < _assetIds.length; ++i) {
_id = _assetIds[i];
_to = _toB[i];
_from = _fromB[i];
require(isApprovedOrOwner(msg.sender, _id));
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _id);
removeTokenFrom(_from, _id);
addTokenTo(_to, _id);
emit Transfer(_from, _to, _id);
}
}
function batchTransferFrom(uint256[] _assetIds, address _from, address _to)
public
{
uint256 _id;
for (uint256 i = 0; i < _assetIds.length; ++i) {
_id = _assetIds[i];
require(isApprovedOrOwner(msg.sender, _id));
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _id);
removeTokenFrom(_from, _id);
addTokenTo(_to, _id);
emit Transfer(_from, _to, _id);
}
}
function multiBatchSafeTransferFrom(
uint256[] _assetIds,
address[] _fromB,
address[] _toB
)
public
{
uint256 _id;
address _to;
address _from;
for (uint256 i = 0; i < _assetIds.length; ++i) {
_id = _assetIds[i];
_to = _toB[i];
_from = _fromB[i];
safeTransferFrom(_from, _to, _id);
}
}
function batchSafeTransferFrom(
uint256[] _assetIds,
address _from,
address _to
)
public
{
uint256 _id;
for (uint256 i = 0; i < _assetIds.length; ++i) {
_id = _assetIds[i];
safeTransferFrom(_from, _to, _id);
}
}
function batchApprove(
uint256[] _assetIds,
address _spender
)
public
{
uint256 _id;
for (uint256 i = 0; i < _assetIds.length; ++i) {
_id = _assetIds[i];
approve(_spender, _id);
}
}
function batchSetApprovalForAll(
address[] _spenders,
bool _approved
)
public
{
address _spender;
for (uint256 i = 0; i < _spenders.length; ++i) {
_spender = _spenders[i];
setApprovalForAll(_spender, _approved);
}
}
function requestDetachment(
uint256 _tokenId
)
public
{
//Request can only be made by owner or approved address
require(isApprovedOrOwner(msg.sender, _tokenId));
uint256 isAttached = getIsNFTAttached(_tokenId);
require(isAttached >= 1);
if(attachedSystemActive == true) {
//Checks to see if request was made and if time elapsed
if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) {
isAttached = 0;
} else if(isAttached > 1) {
//Fail if time is already set for attachment
require(isAttached == 1);
} else {
//Is attached, set detachment time and make request to detach
emit DetachRequest(msg.sender, _tokenId, block.timestamp);
isAttached = block.timestamp;
}
} else {
isAttached = 0;
}
if(isAttached == 0) {
emit NFTDetached(msg.sender, _tokenId);
}
updateIsAttached(_tokenId, isAttached);
}
function attachAsset(
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
uint256 isAttached = getIsNFTAttached(_tokenId);
require(isAttached == 0);
isAttached = 1;
updateIsAttached(_tokenId, isAttached);
emit NFTAttached(msg.sender, _tokenId);
}
function batchAttachAssets(uint256[] _ids) public {
for(uint i = 0; i < _ids.length; i++) {
attachAsset(_ids[i]);
}
}
function batchDetachAssets(uint256[] _ids) public {
for(uint i = 0; i < _ids.length; i++) {
requestDetachment(_ids[i]);
}
}
function requestDetachmentOnPause (uint256 _tokenId) public
whenPaused {
//Request can only be made by owner or approved address
require(isApprovedOrOwner(msg.sender, _tokenId));
updateIsAttached(_tokenId, 0);
}
function batchBurnAssets(uint256[] _assetIDs) public {
uint256 _id;
for(uint i = 0; i < _assetIDs.length; i++) {
_id = _assetIDs[i];
burnAsset(_id);
}
}
function burnAsset(uint256 _assetID) public {
// Is Burn Enabled
require(canBurn == true);
// Deny Action if Attached
require(getIsNFTAttached(_assetID) == 0);
require(isApprovedOrOwner(msg.sender, _assetID) == true);
//Updates Type Total Count
uint256 _assetType = getAssetIdItemType(_assetID);
assetTypeBurnedCount[uint32(_assetType)] += 1;
_burn(msg.sender, _assetID);
}
/** Dev Functions */
function setTokenURIBase (string _tokenURI) public onlyManager {
_setTokenURIBase(_tokenURI);
}
function setPermanentLimitForType (uint32 _type, uint256 _limit) public onlyManager {
//Only allows Limit to be set once
require(assetTypeCreationLimit[_type] == 0);
assetTypeCreationLimit[_type] = uint32(_limit);
}
function setTypeName (uint32 _type, string _name) public anyOperator {
assetTypeName[_type] = _name;
}
// Minting Function
function batchSpawnAsset(address _to, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator {
uint256 _id;
uint256 _assetType;
for(uint i = 0; i < _assetIds.length; i++) {
_id = _assetIds[i];
_assetType = _assetTypes[i];
_createAsset(_to, _assetType, _id, _isAttached, address(0));
}
}
function batchSpawnAsset(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator {
address _to;
uint256 _id;
uint256 _assetType;
for(uint i = 0; i < _assetIds.length; i++) {
_to = _toB[i];
_id = _assetIds[i];
_assetType = _assetTypes[i];
_createAsset(_to, _assetType, _id, _isAttached, address(0));
}
}
function batchSpawnAssetWithCreator(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256[] _isAttacheds, address[] _creators) public anyOperator {
address _to;
address _creator;
uint256 _id;
uint256 _assetType;
uint256 _isAttached;
for(uint i = 0; i < _assetIds.length; i++) {
_to = _toB[i];
_id = _assetIds[i];
_assetType = _assetTypes[i];
_creator = _creators[i];
_isAttached = _isAttacheds[i];
_createAsset(_to, _assetType, _id, _isAttached, _creator);
}
}
function spawnAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached) public anyOperator {
_createAsset(_to, _assetType, _assetID, _isAttached, address(0));
}
function spawnAssetWithCreator(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached, address _creator) public anyOperator {
_createAsset(_to, _assetType, _assetID, _isAttached, _creator);
}
/// @dev Remove all Ether from the contract, shouldn't have any but just incase.
function withdrawBalance() public onlyBanker {
// We are using this boolean method to make sure that even if one fails it will still work
bankManager.transfer(address(this).balance);
}
// Burn Functions
function setCanBurn(bool _state) public onlyManager {
canBurn = _state;
}
function burnAssetOperator(uint256 _assetID) public anyOperator {
require(getIsNFTAttached(_assetID) > 0);
//Updates Type Total Count
uint256 _assetType = getAssetIdItemType(_assetID);
assetTypeBurnedCount[uint32(_assetType)] += 1;
_burn(ownerOf(_assetID), _assetID);
}
function toggleAttachedEnforement (bool _state) public onlyManager {
attachedSystemActive = _state;
}
function setDetachmentTime (uint256 _time) public onlyManager {
//Detactment Time can not be set greater than 2 weeks.
require(_time <= 1209600);
detachmentTime = uint32(_time);
}
function setNFTDetached(uint256 _assetID) public anyOperator {
require(getIsNFTAttached(_assetID) > 0);
updateIsAttached(_assetID, 0);
emit NFTDetached(msg.sender, _assetID);
}
function setBatchDetachCollectibles(uint256[] _assetIds) public anyOperator {
uint256 _id;
for(uint i = 0; i < _assetIds.length; i++) {
_id = _assetIds[i];
setNFTDetached(_id);
}
}
/** Internal Functions */
// @dev For creating NFT Collectible
function _createAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _attachState, address _creator) internal returns(uint256) {
uint256 _sequenceId = uint256(assetTypeTotalCount[uint32(_assetType)]) + 1;
//Will not allow creation if over limit
require(assetTypeCreationLimit[uint32(_assetType)] == 0 || assetTypeCreationLimit[uint32(_assetType)] > _sequenceId);
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken.
require(_sequenceId == uint256(uint64(_sequenceId)));
//Creates NFT
_mint(_to, _assetID);
uint256 nftData = uint256(_creator); // 160 bit address of creator
nftData |= now<<160; // 48 bit creation timestamp
nftData |= _assetType<<208; // 32 bit item type
uint256 nftDataContinued = uint256(_sequenceId); // 64 bit sequence id of item
nftDataContinued |= _attachState<<64; // 48 bit state and/or timestamp for detachment
nftDataA[_assetID] = nftData;
nftDataB[_assetID] = uint128(nftDataContinued);
assetTypeTotalCount[uint32(_assetType)] += 1;
sequenceIDToTypeForID[_sequenceId][uint32(_assetType)] = uint64(_assetID);
// emit Created event
emit AssetCreated(_to, _assetID, _assetType, _sequenceId, now);
return _assetID;
}
function updateIsAttached(uint256 _assetID, uint256 _isAttached)
internal
{
uint256 nftData = nftDataB[_assetID];
uint256 assetTypeSeqId = uint256(uint64(nftData));
uint256 nftDataContinued = uint256(assetTypeSeqId); // 64 bit sequence id of item
nftDataContinued |= _isAttached<<64; // 48 bit state and/or timestamp for detachment
nftDataB[_assetID] = uint128(nftDataContinued);
}
}
|
_owner The owner whose ships tokens we are interested in. This method MUST NEVER be called by smart contract code. First, it&39;s fairly expensive (it walks the entire NFT owners array looking for NFT belonging to owner), but it also returns a dynamic array, which is only supported for web3 calls, and not contract-to-contract calls. Return an empty array We count on the fact that all Asset have IDs starting at 0 and increasing sequentially up to the total count.
|
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 resultIndex = 0;
uint256 _itemIndex;
for (_itemIndex = 0; _itemIndex < tokenCount; _itemIndex++) {
result[resultIndex] = tokenOfOwnerByIndex(_owner,_itemIndex);
resultIndex++;
}
return result;
}
}
| 2,379,381
|
./full_match/97/0xe00aedd1F593B82429ea304A29b947d1FdF8Daba/sources/project_/contracts/BakaCoin.sol
|
Set an address of the gameplay management contract./
|
function setSupport(address _manager) public onlyOwner {
_support = _manager;
}
| 3,268,289
|
pragma solidity 0.4.25;
/// @dev Genesis Oraganization interface
interface GenesisOrganization{
function existed(address caller) external returns (bool);
}
/// @title This is the smart contract to support the template review feature
/// It also saves all template bytecodes in Flow
contract TemplateWarehouse {
address constant delegateAddr = 0x630000000000000000000000000000000000000067;
/// @dev template status enumerations
enum Status { Submitted, Approved, NonExisted, Disabled }
bool private initialized;
/// struct to keep template information
struct Template {
/// file's key
bytes32 key;
/// template status
Status status;
/// approvors and rejecters for this specific template
address[] approvers;
address[] rejecters;
/// owner of the template
address owner;
/// template creation time
uint createTime;
/// whether the template exists
bool exist;
}
/// struct to keep category information
/// Note every template belongs to one category
struct Category {
/// templateName => Template
mapping (string => Template) templates;
/// all template names in this category
string[] names;
/// approved template names in this category
string[] approvedNames;
/// whether the category exists
bool exist;
}
// categoryId => Category
mapping (uint16 => Category) categories;
// Genesis Organization reference
GenesisOrganization genesisOrganization;
uint8 public constant THRESHOLD = 1;
uint8 public constant ALL_APPROVER = 1;
event ContractTemplateEvent(uint16 category, string name, address owner, bytes32 key, uint8 approvers, uint8 rejecters, uint8 allApprover, Status status);
function init() public {
require(!initialized, "it is not allowed to init more than once");
genesisOrganization = GenesisOrganization(0x630000000000000000000000000000000000000064);
initialized = true;
}
/// @dev submit a new template for review
/// @param _category template category
/// @param _name template name
/// @param _key template key
function create(uint16 _category, string _name, bytes32 _key) public {
require(_category > 0);
require(bytes(_name).length > 0 && bytes(_name).length <= 128, "invalid length of template name");
require(_key.length > 0);
Category storage c = categories[_category];
if (c.exist) {
require(!c.templates[_name].exist, "template name already exists");
} else {
/// create a new category if not existed
c.exist = true;
c.names = new string[](0);
c.approvedNames = new string[](0);
}
/// create the template
Template storage t = c.templates[_name];
t.key = _key;
t.status = Status.Submitted;
t.exist = true;
t.approvers = new address[](0);
t.rejecters = new address[](0);
t.owner = msg.sender;
t.createTime = block.timestamp;
c.names.push(_name);
c.templates[_name] = t;
/// in test environment, a template will be approved automatically after submission
/// @notice this should be commentted out in PROD environment
approveForTest(_category, _name);
}
/// @dev modifier to support permission control
modifier actionAuth(uint16 _category, string _name) {
require(genesisOrganization.existed(msg.sender), "not allowed");
require(categories[_category].exist, "category not existed");
require(categories[_category].templates[_name].exist, "template not existed");
_;
}
/// @dev approve for a template
/// @param _category template category
/// @param _name template name
function approve(uint16 _category, string _name) private actionAuth(_category, _name){
Category storage c = categories[_category];
Template storage t = c.templates[_name];
require(t.status == Status.Submitted, "wrong template status");
require(!addressExist(t.approvers, msg.sender), "not a qualified voter");
require(!addressExist(t.rejecters, msg.sender), "not a qualified voter");
require(t.approvers.length < 128);
t.approvers.push(msg.sender);
if (t.approvers.length >= THRESHOLD) {
t.status = Status.Approved;
c.approvedNames.push(_name);
deleteName(_category, _name);
}
emit ContractTemplateEvent(_category, _name, t.owner, t.key, uint8(t.approvers.length), uint8(t.rejecters.length), ALL_APPROVER, t.status);
}
/// @dev this function is used to support automatic approve in test environment
/// @param _category template category
/// @param _name template name
function approveForTest(uint16 _category, string _name) private {
Category storage c = categories[_category];
Template storage t = c.templates[_name];
require(t.status == Status.Submitted, "wrong template status");
require(!addressExist(t.approvers, msg.sender), "not a qualified voter");
require(!addressExist(t.rejecters, msg.sender), "not a qualified voter");
require(t.approvers.length < 128);
t.approvers.push(msg.sender);
if (t.approvers.length >= THRESHOLD) {
t.status = Status.Approved;
c.approvedNames.push(_name);
deleteName(_category, _name);
}
emit ContractTemplateEvent(_category, _name, t.owner, t.key, uint8(t.approvers.length), uint8(t.rejecters.length), ALL_APPROVER, t.status);
}
/// @dev reject a template
/// @param _category template category
/// @param _name template name
function reject(uint16 _category, string _name) private actionAuth(_category, _name){
Category storage c = categories[_category];
Template storage t = c.templates[_name];
require(t.status == Status.Submitted, "wrong template status");
require(!addressExist(t.approvers, msg.sender), "not a qualified voter");
require(!addressExist(t.rejecters, msg.sender), "not a qualified voter");
require(t.rejecters.length < 128);
t.rejecters.push(msg.sender);
if (t.rejecters.length > (ALL_APPROVER - THRESHOLD)) {
deleteTemplate(_category, _name);
}
}
/// @dev get total counts of submitted templates
/// @param _category template category
function getSubmittedTemplatesCount(uint16 _category) public view returns (uint256) {
Category memory c = categories[_category];
if (!c.exist) {
return 0;
}
return c.names.length;
}
/// @dev get a submitted template information by index
/// @param _category template category
/// @param index position of the template in the cateogry
function getSubmittedTemplate(uint16 _category, uint256 index) public view returns (string, bytes32, uint, uint8, uint8, uint8, Status) {
Category storage c = categories[_category];
if (!c.exist) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
if (c.names.length <= 0) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
string memory name = c.names[index];
if (!c.templates[name].exist) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
Template memory t = c.templates[name];
return (name, t.key, t.createTime, uint8(t.approvers.length), uint8(t.rejecters.length), ALL_APPROVER, t.status);
}
/// @dev get total counts of approved templates
/// @param _category template category
function getApprovedTemplatesCount(uint16 _category) public view returns (uint256) {
Category memory c = categories[_category];
if (!c.exist) {
return 0;
}
return c.approvedNames.length;
}
/// @dev get an approved template information by index
/// @param _category template category
/// @param index position of the template in the cateogry
function getApprovedTemplate(uint16 _category, uint256 index) public view returns (string, bytes32, uint, uint8, uint8, uint8, Status) {
Category storage c = categories[_category];
if (!c.exist) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
if (c.approvedNames.length <= 0) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
string memory name = c.approvedNames[index];
if (!c.templates[name].exist) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
Template memory t = c.templates[name];
return (name, t.key, t.createTime, uint8(t.approvers.length), uint8(t.rejecters.length), ALL_APPROVER, t.status);
}
/// @dev get an approved template information by name
/// @param _category template category
/// @param name template name
function getTemplate(uint16 _category, string name) public view returns (string, bytes32, uint, uint8, uint8, uint8, Status) {
Category storage c = categories[_category];
if (!c.exist) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
if (!c.templates[name].exist) {
return ("", "", 0, 0, 0, ALL_APPROVER, Status.NonExisted);
}
Template memory t = c.templates[name];
return (name, t.key, t.createTime, uint8(t.approvers.length), uint8(t.rejecters.length), ALL_APPROVER,t.status);
}
/// @dev disable a template
/// @param _category template category
/// @param _name template name
function disable(uint16 _category, string _name) public actionAuth(_category, _name){
Category storage c = categories[_category];
Template storage t = c.templates[_name];
t.status = Status.Disabled;
}
/// @dev enable a template
/// @param _category template category
/// @param _name template name
function enable(uint16 _category, string _name) public actionAuth(_category, _name){
Category storage c = categories[_category];
Template storage t = c.templates[_name];
t.status = Status.Approved;
}
/// @dev delete a template
/// @param _category template category
/// @param _name template name
function deleteTemplate(uint16 _category, string _name) internal {
Category storage c = categories[_category];
delete c.templates[_name];
deleteName(_category, _name);
}
/// @dev delete a template name in category
/// @param _category template category
/// @param _name template name
function deleteName(uint16 _category, string _name) internal {
Category storage c = categories[_category];
for(uint i = 0; i < c.names.length; i++) {
if (keccak256(c.names[i]) == keccak256(_name)) {
delete c.names[i];
}
}
}
/// @dev helper method, check whether an address is in the array
/// @param addresses the array of address
/// @param addr the address
function addressExist(address[] addresses, address addr) internal pure returns (bool) {
for(uint i = 0; i < addresses.length; i++) {
if (addresses[i] == addr) {
return true;
}
}
return false;
}
/// @dev check whether name is exist
/// @param _category category of template
/// @param _name name of template
function nameExist(uint16 _category, string _name) public view returns (bool) {
Category storage c = categories[_category];
return c.templates[_name].exist;
}
}
|
get total counts of approved templates _category template category
|
function getApprovedTemplatesCount(uint16 _category) public view returns (uint256) {
Category memory c = categories[_category];
if (!c.exist) {
return 0;
}
return c.approvedNames.length;
}
| 1,051,285
|
pragma solidity ^0.4.18;
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 max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract ERC20Basic {
uint256 public totalSupply;
bool public transfersEnabled;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 {
uint256 public totalSupply;
bool public transfersEnabled;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => uint256) balances;
/**
* Protection against short address attack
*/
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
/**
* @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 onlyPayloadSize(2) returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(transfersEnabled);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev 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 constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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 onlyPayloadSize(3) returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(transfersEnabled);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev 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 onlyPayloadSize(2) constant returns (uint256 remaining) {
return allowed[_owner][_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
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
}
else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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;
address public ownerTwo;
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner || msg.sender == ownerTwo);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function changeOwnerTwo(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
OwnerChanged(owner, _newOwner);
ownerTwo = _newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
string public constant name = "FOOOZ";
string public constant symbol = "FOOOZ";
uint8 public constant decimals = 18;
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount, address _owner) canMint internal returns (bool) {
balances[_to] = balances[_to].add(_amount);
balances[_owner] = balances[_owner].sub(_amount);
Mint(_to, _amount);
Transfer(_owner, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint internal returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* Peterson's Law Protection
* Claim tokens
*/
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
MintableToken token = MintableToken(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
Transfer(_token, owner, balance);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokenAllocated;
uint256 public hardWeiCap = 119000 * (10 ** 18);
function Crowdsale(
address _wallet
)
public
{
require(_wallet != address(0));
wallet = _wallet;
}
}
contract FooozCrowdsale is Ownable, Crowdsale, MintableToken {
using SafeMath for uint256;
enum State {Active, Closed}
State public state;
mapping (address => uint256) public deposited;
uint256 public constant INITIAL_SUPPLY = 613333328 * (10 ** uint256(decimals));
uint256 public fundForSale = 466133330 * (10 ** uint256(decimals));
address public addressFundDevelopers = 0x326B7740e5E806fc731200A3ea92f588a86568A3;
address public addressFundBounty = 0xE585b723bDc6324dD55cf614fa83f61A88D5b3D8;
address public addressFundBonus = 0x1f318fE745bEE511a72A8AB2b704a5F285587335;
address public addressFundInvestment = 0x80A0BE0Ab330E48dE8E37277b838b9eB0Bb3bb6f;
address public addressFundAdministration = 0xFe3905B9Bd7C0c4164873180dfE0ee85FbFe9F19;
uint256[] public discount = [50, 25, 20, 15, 10, 5];
uint256 public weiMinSalePreIco = 1190 * 10 ** 15;
uint256 public weiMinSaleIco = 29 * 10 ** 15;
uint256 priceToken = 3362; // $0.25 = 1 token => $1,000 = 1.19 ETH =>
//4,000 token = 1.19 ETH => 1 ETH = 4,000/1.19 = 3362 token
uint256 public countInvestor;
uint256 public currentAfterIcoPeriod;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken);
event HardCapReached();
event Finalized();
function FooozCrowdsale (address _owner, address _ownerTwo) public
Crowdsale(_owner)
{
require(_owner != address(0));
require(_ownerTwo != address(0));
owner = _owner;
ownerTwo = _ownerTwo;
//owner = msg.sender; //for test's
transfersEnabled = true;
mintingFinished = false;
state = State.Active;
totalSupply = INITIAL_SUPPLY;
mintForOwner(owner);
}
modifier inState(State _state) {
require(state == _state);
_;
}
// fallback function can be used to buy tokens
function() payable public {
buyTokens(msg.sender);
}
function setPriceToken(uint256 _newPrice) public onlyOwner {
require(_newPrice > 0);
priceToken = _newPrice;
}
// low level token purchase function
function buyTokens(address _investor) public inState(State.Active) payable returns (uint256){
require(_investor != address(0));
uint256 weiAmount = msg.value;
uint256 tokens = validPurchaseTokens(weiAmount);
if (tokens == 0) {revert();}
weiRaised = weiRaised.add(weiAmount);
tokenAllocated = tokenAllocated.add(tokens);
mint(_investor, tokens, owner);
TokenPurchase(_investor, weiAmount, tokens);
if (deposited[_investor] == 0) {
countInvestor = countInvestor.add(1);
}
deposit(_investor);
wallet.transfer(weiAmount);
return tokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) {
uint256 currentDate = now;
//currentDate = 1526342400; //for test's (Tue, 15 May 2018 00:00:00 GMT)
uint256 currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 6){
amountOfTokens = _weiAmount.mul(priceToken).mul(discount[currentPeriod] + 100).div(100);
}
if(currentPeriod == 0 && _weiAmount < weiMinSalePreIco){
amountOfTokens = 0;
}
if(0 < currentPeriod && currentPeriod < 6 && _weiAmount < weiMinSaleIco){
amountOfTokens = 0;
}
return amountOfTokens;
}
/**
* Pre-ICO sale starts on 31 of March, ends on 06 April 2018
* 1st. Stage starts 07 of April , ends on 16 of April , 2018
* 2nd. Stage starts 17 of April , ends on 26 of April , 2018
* 3rd. Stage starts 27 of April , ends on 06 of May , 2018
* 4th. Stage starts 07 of May, ends on 16 of May , 2018
* 4th. Stage starts 17 of May, ends on 31 of May , 2018
*/
function getPeriod(uint256 _currentDate) public pure returns (uint) {
//1522454400 - March, 31, 2018 00:00:00 && 1523059199 - April, 06, 2018 23:59:59
if( 1522454400 <= _currentDate && _currentDate <= 1523059199){
return 0;
}
//1523059200 - April, 07, 2018 00:00:00 && 1523923199 - April, 16, 2018 23:59:59
if( 1523059200 <= _currentDate && _currentDate <= 1523923199){
return 1;
}
//1523923200 - April, 17, 2018 00:00:00 && 1524787199 - April, 26, 2018 23:59:59
if( 1523923200 <= _currentDate && _currentDate <= 1524787199){
return 2;
}
//1524787200 - April, 27, 2018 00:00:00 && 1525651199 - May, 06, 2018 23:59:59
if( 1524787200 <= _currentDate && _currentDate <= 1525651199){
return 3;
}
//1525651200 - May, 07, 2018 00:00:00 && 1526515199 - May, 16, 2018 23:59:59
if( 1525651200 <= _currentDate && _currentDate <= 1526515199){
return 4;
}
//1526515200 - May, 17, 2018 00:00:00 && 1527811199 - May, 31, 2018 23:59:59
if( 1526515200 <= _currentDate && _currentDate <= 1527811199){
return 5;
}
return 10;
}
function getAfterIcoPeriod(uint256 _currentDate) public pure returns (uint) {
uint256 endIco = 1527811199; // May, 31, 2018 23:59:59
if( endIco < _currentDate && _currentDate <= endIco + 2 years){
return 100;
}
if( endIco + 2 years < _currentDate && _currentDate <= endIco + 4 years){
return 200;
}
if( endIco + 4 years < _currentDate && _currentDate <= endIco + 6 years){
return 300;
}
if( endIco + 6 years < _currentDate && _currentDate <= endIco + 8 years){
return 400;
}
return 0;
}
function mintAfterIcoPeriod() public returns (bool result) {
uint256 totalCost = tokenAllocated.div(priceToken);
uint256 fivePercent = 0;
uint256 currentDate = now;
//currentDate = 1564704000; //for test Aug, 02, 2019
bool changePeriod = false;
uint256 nonSoldToken = totalSupply.sub(tokenAllocated);
uint256 mintTokens = 0;
result = false;
if (currentAfterIcoPeriod < getAfterIcoPeriod(currentDate)){
currentAfterIcoPeriod = currentAfterIcoPeriod.add(getAfterIcoPeriod(currentDate));
changePeriod = true;
}
if(totalCost.mul(100).div(weiRaised) < 200 || changePeriod){
mintTokens = nonSoldToken.div(4); // 25%
fivePercent = mintTokens.div(20); // 5%
balances[addressFundBonus] = balances[addressFundBonus].add(fivePercent.mul(2));
balances[addressFundBounty] = balances[addressFundBounty].add(fivePercent);
balances[addressFundInvestment] = balances[addressFundInvestment].add(fivePercent.mul(10));
balances[addressFundAdministration] = balances[addressFundAdministration].add(fivePercent);
//balances[ownerTwo] = balances[ownerTwo].add(fivePercent.mul(6));
balances[owner] = balances[owner].sub(fivePercent.mul(14)); // - 70%
tokenAllocated = tokenAllocated.add(fivePercent.mul(14));
result = true;
}
}
function deposit(address investor) internal {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function mintForOwner(address _wallet) internal returns (bool result) {
result = false;
uint256 fundBounty = 24533333 * (10 ** uint256(decimals));
uint256 fundDevelopers = 122666665 * (10 ** uint256(decimals));
require(_wallet != address(0));
balances[addressFundDevelopers] = balances[addressFundDevelopers].add(fundDevelopers);
balances[addressFundBounty] = balances[addressFundBounty].add(fundBounty);
tokenAllocated = tokenAllocated.add(fundDevelopers).add(fundBounty);
balances[_wallet] = balances[_wallet].add(INITIAL_SUPPLY).sub(tokenAllocated);
result = true;
}
function getDeposited(address _investor) public view returns (uint256){
return deposited[_investor];
}
function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (tokenAllocated.add(addTokens) > fundForSale) {
TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
if (weiRaised.add(_weiAmount) > hardWeiCap) {
HardCapReached();
return 0;
}
return addTokens;
}
function finalize() public onlyOwner inState(State.Active) returns (bool result) {
result = false;
state = State.Closed;
wallet.transfer(this.balance);
finishMinting();
Finalized();
result = true;
}
}
|
Allows the current owner to transfer control of the contract to a newOwner. _newOwner The address to transfer ownership to./
|
function changeOwnerTwo(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
OwnerChanged(owner, _newOwner);
ownerTwo = _newOwner;
}
| 9,898,352
|
./full_match/1/0x3C6FBc94288f5af5201085948DdB18aDED2E6879/sources/contracts/ApeFiNFT.sol
|
Phase 2 - Whitelist mint NFT. merkleProof The merkle proof/ Whitelist can only mint 1 NFT.
|
function whitelistMint(
bytes32[] calldata merkleProof
) external payable whenNotPaused nonReentrant onlyEOA {
require(getStartTime() != 0, "start time not set");
require(
getBlockTimestamp() >= getWhitelistMintStartTime(),
"whitelist mint not started"
);
require(
getBlockTimestamp() < getPublicMintStartTime(),
"whitelist mint closed"
);
require(totalSupply() + 1 <= maxSupply(), "max supply exceeded");
require(!_whitelistMinted[msg.sender], "already minted");
require(
MerkleProof.verify(
merkleProof,
_whitelistMerkleRoot,
keccak256(abi.encodePacked(msg.sender))
),
"merkle proof verification failed"
);
require(msg.value >= WHITELIST_PRICE, "not enough ether");
_whitelistMinted[msg.sender] = true;
_mint(msg.sender, 1);
}
| 3,053,465
|
./full_match/42220/0x1f93720b14B349Ee07010245D19813DF51fE3047/sources/contracts/FossilFarms.sol
|
Withdraw LP tokens from Faucet. _pid ID of a specific LP token pool. See index of PoolInfo[]. _amount Amount of LP tokens to withdraw./
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "Can't withdraw more token than previously deposited.");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accDinoPerShare).div(1e12).sub(user.rewardDebt);
safeDinoTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accDinoPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 16,328,700
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {GnosisAuction} from "../../libraries/GnosisAuction.sol";
import {Vault} from "../../libraries/Vault.sol";
import {VaultLifecycle} from "../../libraries/VaultLifecycle.sol";
import {VaultLifecycleSTETH} from "../../libraries/VaultLifecycleSTETH.sol";
import {ShareMath} from "../../libraries/ShareMath.sol";
import {RibbonVault} from "./base/RibbonVault.sol";
import {
RibbonThetaSTETHVaultStorage
} from "../../storage/RibbonThetaSTETHVaultStorage.sol";
/**
* UPGRADEABILITY: Since we use the upgradeable proxy pattern, we must observe
* the inheritance chain closely.
* Any changes/appends in storage variable needs to happen in RibbonThetaSTETHVaultStorage.
* RibbonThetaSTETHVault should not inherit from any other contract aside from RibbonVault, RibbonThetaSTETHVaultStorage
*/
contract RibbonThetaSTETHVault is RibbonVault, RibbonThetaSTETHVaultStorage {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using ShareMath for Vault.DepositReceipt;
/************************************************
* IMMUTABLES & CONSTANTS
***********************************************/
/// @notice is the factory contract used to spawn otokens. Used to lookup otokens.
address public immutable OTOKEN_FACTORY;
// The minimum duration for an option auction.
uint256 private constant MIN_AUCTION_DURATION = 1 hours;
/************************************************
* EVENTS
***********************************************/
event OpenShort(
address indexed options,
uint256 depositAmount,
address indexed manager
);
event CloseShort(
address indexed options,
uint256 withdrawAmount,
address indexed manager
);
event NewOptionStrikeSelected(uint256 strikePrice, uint256 delta);
event PremiumDiscountSet(
uint256 premiumDiscount,
uint256 newPremiumDiscount
);
event AuctionDurationSet(
uint256 auctionDuration,
uint256 newAuctionDuration
);
event InstantWithdraw(
address indexed account,
uint256 amount,
uint256 round
);
event InitiateGnosisAuction(
address indexed auctioningToken,
address indexed biddingToken,
uint256 auctionCounter,
address indexed manager
);
/************************************************
* CONSTRUCTOR & INITIALIZATION
***********************************************/
/**
* @notice Initializes the contract with immutable variables
* @param _weth is the Wrapped Ether contract
* @param _usdc is the USDC contract
* @param _wsteth is the LDO contract
* @param _ldo is the LDO contract
* @param _oTokenFactory is the contract address for minting new opyn option types (strikes, asset, expiry)
* @param _gammaController is the contract address for opyn actions
* @param _marginPool is the contract address for providing collateral to opyn
* @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions
* @param _crvPool is the steth/eth crv stables pool
*/
constructor(
address _weth,
address _usdc,
address _wsteth,
address _ldo,
address _oTokenFactory,
address _gammaController,
address _marginPool,
address _gnosisEasyAuction,
address _crvPool
)
RibbonVault(
_weth,
_usdc,
_wsteth,
_ldo,
_gammaController,
_marginPool,
_gnosisEasyAuction,
_crvPool
)
{
require(_oTokenFactory != address(0), "!_oTokenFactory");
OTOKEN_FACTORY = _oTokenFactory;
}
/**
* @notice Initializes the OptionVault contract with storage variables.
* @param _owner is the owner of the vault with critical permissions
* @param _keeper is the keeper of the vault with medium permissions (weekly actions)
* @param _feeRecipient is the address to recieve vault performance and management fees
* @param _managementFee is the management fee pct.
* @param _performanceFee is the perfomance fee pct.
* @param _tokenName is the name of the token
* @param _tokenSymbol is the symbol of the token
* @param _optionsPremiumPricer is the address of the contract with the
black-scholes premium calculation logic
* @param _strikeSelection is the address of the contract with strike selection logic
* @param _premiumDiscount is the vault's discount applied to the premium
* @param _auctionDuration is the duration of the gnosis auction
* @param _vaultParams is the struct with vault general data
*/
function initialize(
address _owner,
address _keeper,
address _feeRecipient,
uint256 _managementFee,
uint256 _performanceFee,
string memory _tokenName,
string memory _tokenSymbol,
address _optionsPremiumPricer,
address _strikeSelection,
uint32 _premiumDiscount,
uint256 _auctionDuration,
Vault.VaultParams calldata _vaultParams
) external initializer {
baseInitialize(
_owner,
_keeper,
_feeRecipient,
_managementFee,
_performanceFee,
_tokenName,
_tokenSymbol,
_vaultParams
);
require(_optionsPremiumPricer != address(0), "!_optionsPremiumPricer");
require(_strikeSelection != address(0), "!_strikeSelection");
require(
_premiumDiscount > 0 &&
_premiumDiscount < 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER,
"!_premiumDiscount"
);
require(_auctionDuration >= MIN_AUCTION_DURATION, "!_auctionDuration");
optionsPremiumPricer = _optionsPremiumPricer;
strikeSelection = _strikeSelection;
premiumDiscount = _premiumDiscount;
auctionDuration = _auctionDuration;
}
/************************************************
* SETTERS
***********************************************/
/**
* @notice Sets the new discount on premiums for options we are selling
* @param newPremiumDiscount is the premium discount
*/
function setPremiumDiscount(uint256 newPremiumDiscount) external onlyOwner {
require(
newPremiumDiscount > 0 &&
newPremiumDiscount < 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER,
"Invalid discount"
);
emit PremiumDiscountSet(premiumDiscount, newPremiumDiscount);
premiumDiscount = newPremiumDiscount;
}
/**
* @notice Sets the new auction duration
* @param newAuctionDuration is the auction duration
*/
function setAuctionDuration(uint256 newAuctionDuration) external onlyOwner {
require(
newAuctionDuration >= MIN_AUCTION_DURATION,
"Invalid auction duration"
);
emit AuctionDurationSet(auctionDuration, newAuctionDuration);
auctionDuration = newAuctionDuration;
}
/**
* @notice Sets the new strike selection or options premium pricer contract
* @param newContract is the address of the new strike selection or options premium pricer contract
* @param isStrikeSelection is whether we are setting the strike selection contract
*/
function setStrikeSelectionOrPricer(
address newContract,
bool isStrikeSelection
) external onlyOwner {
require(newContract != address(0), "!newContract");
if (isStrikeSelection) {
strikeSelection = newContract;
} else {
optionsPremiumPricer = newContract;
}
}
/**
* @notice Optionality to set strike price manually
* @param strikePrice is the strike price of the new oTokens (decimals = 8)
*/
function setStrikePrice(uint128 strikePrice)
external
onlyOwner
nonReentrant
{
require(strikePrice > 0, "!strikePrice");
overriddenStrikePrice = strikePrice;
lastStrikeOverrideRound = vaultState.round;
}
/************************************************
* VAULT OPERATIONS
***********************************************/
/**
* @notice Withdraws the assets on the vault using the outstanding `DepositReceipt.amount`
* @param amount is the amount to withdraw in `asset`
* @param minETHOut is the min amount of `asset` to recieve for the swapped amount of steth in crv pool
*/
function withdrawInstantly(uint256 amount, uint256 minETHOut)
external
nonReentrant
{
Vault.DepositReceipt storage depositReceipt =
depositReceipts[msg.sender];
uint256 currentRound = vaultState.round;
require(amount > 0, "!amount");
require(depositReceipt.round == currentRound, "Invalid round");
uint256 receiptAmount = depositReceipt.amount;
require(receiptAmount >= amount, "Exceed amount");
// Subtraction underflow checks already ensure it is smaller than uint104
depositReceipt.amount = uint104(receiptAmount.sub(amount));
vaultState.totalPending = uint128(
uint256(vaultState.totalPending).sub(amount)
);
emit InstantWithdraw(msg.sender, amount, currentRound);
// Unwrap may incur curve pool slippage
uint256 amountETHOut =
VaultLifecycleSTETH.unwrapYieldToken(
amount,
address(collateralToken),
STETH_ETH_CRV_POOL,
minETHOut
);
VaultLifecycleSTETH.transferAsset(msg.sender, amountETHOut);
}
/**
* @notice Sets the next option the vault will be shorting, and closes the existing short.
* This allows all the users to withdraw if the next option is malicious.
*/
function commitAndClose() external nonReentrant {
address oldOption = optionState.currentOption;
VaultLifecycle.CloseParams memory closeParams =
VaultLifecycle.CloseParams({
OTOKEN_FACTORY: OTOKEN_FACTORY,
USDC: USDC,
currentOption: oldOption,
delay: DELAY,
lastStrikeOverrideRound: lastStrikeOverrideRound,
overriddenStrikePrice: overriddenStrikePrice
});
(
address otokenAddress,
uint256 premium,
uint256 strikePrice,
uint256 delta
) =
VaultLifecycleSTETH.commitAndClose(
strikeSelection,
optionsPremiumPricer,
premiumDiscount,
closeParams,
vaultParams,
vaultState,
address(collateralToken)
);
emit NewOptionStrikeSelected(strikePrice, delta);
ShareMath.assertUint104(premium);
currentOtokenPremium = uint104(premium);
optionState.nextOption = otokenAddress;
uint256 nextOptionReady = block.timestamp.add(DELAY);
require(
nextOptionReady <= type(uint32).max,
"Overflow nextOptionReady"
);
optionState.nextOptionReadyAt = uint32(nextOptionReady);
_closeShort(oldOption);
}
/**
* @notice Closes the existing short position for the vault.
*/
function _closeShort(address oldOption) private {
optionState.currentOption = address(0);
uint256 lockedAmount = vaultState.lockedAmount;
vaultState.lastLockedAmount = uint104(lockedAmount);
vaultState.lockedAmount = 0;
if (oldOption != address(0)) {
uint256 withdrawAmount =
VaultLifecycle.settleShort(GAMMA_CONTROLLER);
emit CloseShort(oldOption, withdrawAmount, msg.sender);
}
}
/**
* @notice Rolls the vault's funds into a new short position.
*/
function rollToNextOption() external onlyKeeper nonReentrant {
(address newOption, uint256 queuedWithdrawAmount) =
_rollToNextOption(uint256(lastQueuedWithdrawAmount));
lastQueuedWithdrawAmount = queuedWithdrawAmount;
// Locked balance denominated in `collateralToken`
uint256 lockedBalance =
collateralToken.balanceOf(address(this)).sub(
collateralToken.getWstETHByStETH(queuedWithdrawAmount)
);
emit OpenShort(newOption, lockedBalance, msg.sender);
VaultLifecycleSTETH.createShort(
GAMMA_CONTROLLER,
MARGIN_POOL,
newOption,
lockedBalance
);
_startAuction();
}
/**
* @notice Initiate the gnosis auction.
*/
function startAuction() external onlyKeeper nonReentrant {
_startAuction();
}
function _startAuction() private {
GnosisAuction.AuctionDetails memory auctionDetails;
uint256 currOtokenPremium = currentOtokenPremium;
require(currOtokenPremium > 0, "!currentOtokenPremium");
auctionDetails.oTokenAddress = optionState.currentOption;
auctionDetails.gnosisEasyAuction = GNOSIS_EASY_AUCTION;
auctionDetails.asset = vaultParams.asset;
auctionDetails.assetDecimals = vaultParams.decimals;
auctionDetails.oTokenPremium = currOtokenPremium;
auctionDetails.duration = auctionDuration;
optionAuctionID = VaultLifecycle.startAuction(auctionDetails);
}
/**
* @notice Burn the remaining oTokens left over from gnosis auction.
*/
function burnRemainingOTokens() external onlyKeeper nonReentrant {
uint256 unlockedAssedAmount =
VaultLifecycle.burnOtokens(
GAMMA_CONTROLLER,
optionState.currentOption
);
vaultState.lockedAmount = uint104(
uint256(vaultState.lockedAmount).sub(unlockedAssedAmount)
);
// Wrap entire `asset` balance to `collateralToken` balance
VaultLifecycleSTETH.wrapToYieldToken(WETH, address(collateralToken));
}
}
// 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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DSMath} from "../vendor/DSMath.sol";
import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol";
import {IOtoken} from "../interfaces/GammaInterface.sol";
import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol";
import {Vault} from "./Vault.sol";
import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol";
library GnosisAuction {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event InitiateGnosisAuction(
address indexed auctioningToken,
address indexed biddingToken,
uint256 auctionCounter,
address indexed manager
);
event PlaceAuctionBid(
uint256 auctionId,
address indexed auctioningToken,
uint256 sellAmount,
uint256 buyAmount,
address indexed bidder
);
struct AuctionDetails {
address oTokenAddress;
address gnosisEasyAuction;
address asset;
uint256 assetDecimals;
uint256 oTokenPremium;
uint256 duration;
}
struct BidDetails {
address oTokenAddress;
address gnosisEasyAuction;
address asset;
uint256 assetDecimals;
uint256 auctionId;
uint256 lockedBalance;
uint256 optionAllocation;
uint256 optionPremium;
address bidder;
}
function startAuction(AuctionDetails calldata auctionDetails)
internal
returns (uint256 auctionID)
{
uint256 oTokenSellAmount =
getOTokenSellAmount(auctionDetails.oTokenAddress);
IERC20(auctionDetails.oTokenAddress).safeApprove(
auctionDetails.gnosisEasyAuction,
IERC20(auctionDetails.oTokenAddress).balanceOf(address(this))
);
// minBidAmount is total oTokens to sell * premium per oToken
// shift decimals to correspond to decimals of USDC for puts
// and underlying for calls
uint256 minBidAmount =
DSMath
.wmul(
oTokenSellAmount.mul(10**10),
auctionDetails
.oTokenPremium
)
.div(10**(uint256(18).sub(auctionDetails.assetDecimals)));
require(
minBidAmount <= type(uint96).max,
"optionPremium * oTokenSellAmount > type(uint96) max value!"
);
uint256 auctionEnd = block.timestamp.add(auctionDetails.duration);
auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction)
.initiateAuction(
// address of oToken we minted and are selling
auctionDetails.oTokenAddress,
// address of asset we want in exchange for oTokens. Should match vault `asset`
auctionDetails.asset,
// orders can be cancelled at any time during the auction
auctionEnd,
// order will last for `duration`
auctionEnd,
// we are selling all of the otokens minus a fee taken by gnosis
uint96(oTokenSellAmount),
// the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price
uint96(minBidAmount),
// the minimum bidding amount must be 1 * 10 ** -assetDecimals
1,
// the min funding threshold
0,
// no atomic closure
false,
// access manager contract
address(0),
// bytes for storing info like a whitelist for who can bid
bytes("")
);
emit InitiateGnosisAuction(
auctionDetails.oTokenAddress,
auctionDetails.asset,
auctionID,
msg.sender
);
}
function placeBid(BidDetails calldata bidDetails)
internal
returns (
uint256 sellAmount,
uint256 buyAmount,
uint64 userId
)
{
// calculate how much to allocate
sellAmount = bidDetails
.lockedBalance
.mul(bidDetails.optionAllocation)
.div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER);
// divide the `asset` sellAmount by the target premium per oToken to
// get the number of oTokens to buy (8 decimals)
buyAmount = sellAmount
.mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS)))
.div(bidDetails.optionPremium)
.div(10**bidDetails.assetDecimals);
require(
sellAmount <= type(uint96).max,
"sellAmount > type(uint96) max value!"
);
require(
buyAmount <= type(uint96).max,
"buyAmount > type(uint96) max value!"
);
// approve that amount
IERC20(bidDetails.asset).safeApprove(
bidDetails.gnosisEasyAuction,
sellAmount
);
uint96[] memory _minBuyAmounts = new uint96[](1);
uint96[] memory _sellAmounts = new uint96[](1);
bytes32[] memory _prevSellOrders = new bytes32[](1);
_minBuyAmounts[0] = uint96(buyAmount);
_sellAmounts[0] = uint96(sellAmount);
_prevSellOrders[
0
] = 0x0000000000000000000000000000000000000000000000000000000000000001;
// place sell order with that amount
userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders(
bidDetails.auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
"0x"
);
emit PlaceAuctionBid(
bidDetails.auctionId,
bidDetails.oTokenAddress,
sellAmount,
buyAmount,
bidDetails.bidder
);
return (sellAmount, buyAmount, userId);
}
function claimAuctionOtokens(
Vault.AuctionSellOrder calldata auctionSellOrder,
address gnosisEasyAuction,
address counterpartyThetaVault
) internal {
bytes32 order =
encodeOrder(
auctionSellOrder.userId,
auctionSellOrder.buyAmount,
auctionSellOrder.sellAmount
);
bytes32[] memory orders = new bytes32[](1);
orders[0] = order;
IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder(
IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(),
orders
);
}
function getOTokenSellAmount(address oTokenAddress)
internal
view
returns (uint256)
{
// We take our current oToken balance. That will be our sell amount
// but otokens will be transferred to gnosis.
uint256 oTokenSellAmount =
IERC20(oTokenAddress).balanceOf(address(this));
require(
oTokenSellAmount <= type(uint96).max,
"oTokenSellAmount > type(uint96) max value!"
);
return oTokenSellAmount;
}
function getOTokenPremium(
address oTokenAddress,
address optionsPremiumPricer,
uint256 premiumDiscount
) internal view returns (uint256) {
IOtoken newOToken = IOtoken(oTokenAddress);
IOptionsPremiumPricer premiumPricer =
IOptionsPremiumPricer(optionsPremiumPricer);
// Apply black-scholes formula (from rvol library) to option given its features
// and get price for 100 contracts denominated in the underlying asset for call option
// and USDC for put option
uint256 optionPremium =
premiumPricer.getPremium(
newOToken.strikePrice(),
newOToken.expiryTimestamp(),
newOToken.isPut()
);
// Apply a discount to incentivize arbitraguers
optionPremium = optionPremium.mul(premiumDiscount).div(
100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER
);
require(
optionPremium <= type(uint96).max,
"optionPremium > type(uint96) max value!"
);
return optionPremium;
}
function encodeOrder(
uint64 userId,
uint96 buyAmount,
uint96 sellAmount
) internal pure returns (bytes32) {
return
bytes32(
(uint256(userId) << 192) +
(uint256(buyAmount) << 96) +
uint256(sellAmount)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library Vault {
/************************************************
* IMMUTABLES & CONSTANTS
***********************************************/
// Fees are 6-decimal places. For example: 20 * 10**6 = 20%
uint256 internal constant FEE_MULTIPLIER = 10**6;
// Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount.
uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10;
// Otokens have 8 decimal places.
uint256 internal constant OTOKEN_DECIMALS = 8;
// Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10%
uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2;
// Placeholder uint value to prevent cold writes
uint256 internal constant PLACEHOLDER_UINT = 1;
struct VaultParams {
// Option type the vault is selling
bool isPut;
// Token decimals for vault shares
uint8 decimals;
// Asset used in Theta / Delta Vault
address asset;
// Underlying asset of the options sold by vault
address underlying;
// Minimum supply of the vault shares issued, for ETH it's 10**10
uint56 minimumSupply;
// Vault cap
uint104 cap;
}
struct OptionState {
// Option that the vault is shorting / longing in the next cycle
address nextOption;
// Option that the vault is currently shorting / longing
address currentOption;
// The timestamp when the `nextOption` can be used by the vault
uint32 nextOptionReadyAt;
}
struct VaultState {
// 32 byte slot 1
// Current round number. `round` represents the number of `period`s elapsed.
uint16 round;
// Amount that is currently locked for selling options
uint104 lockedAmount;
// Amount that was locked for selling options in the previous round
// used for calculating performance fee deduction
uint104 lastLockedAmount;
// 32 byte slot 2
// Stores the total tally of how much of `asset` there is
// to be used to mint rTHETA tokens
uint128 totalPending;
// Amount locked for scheduled withdrawals;
uint128 queuedWithdrawShares;
}
struct DepositReceipt {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit
uint104 amount;
// Unredeemed shares balance
uint128 unredeemedShares;
}
struct Withdrawal {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Number of shares withdrawn
uint128 shares;
}
struct AuctionSellOrder {
// Amount of `asset` token offered in auction
uint96 sellAmount;
// Amount of oToken requested in auction
uint96 buyAmount;
// User Id of delta vault in latest gnosis auction
uint64 userId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Vault} from "./Vault.sol";
import {ShareMath} from "./ShareMath.sol";
import {IStrikeSelection} from "../interfaces/IRibbon.sol";
import {GnosisAuction} from "./GnosisAuction.sol";
import {
IOtokenFactory,
IOtoken,
IController,
GammaTypes
} from "../interfaces/GammaInterface.sol";
import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol";
import {SupportsNonCompliantERC20} from "./SupportsNonCompliantERC20.sol";
library VaultLifecycle {
using SafeMath for uint256;
using SupportsNonCompliantERC20 for IERC20;
struct CloseParams {
address OTOKEN_FACTORY;
address USDC;
address currentOption;
uint256 delay;
uint16 lastStrikeOverrideRound;
uint256 overriddenStrikePrice;
}
/**
* @notice Sets the next option the vault will be shorting, and calculates its premium for the auction
* @param strikeSelection is the address of the contract with strike selection logic
* @param optionsPremiumPricer is the address of the contract with the
black-scholes premium calculation logic
* @param premiumDiscount is the vault's discount applied to the premium
* @param closeParams is the struct with details on previous option and strike selection details
* @param vaultParams is the struct with vault general data
* @param vaultState is the struct with vault accounting state
* @return otokenAddress is the address of the new option
* @return premium is the premium of the new option
* @return strikePrice is the strike price of the new option
* @return delta is the delta of the new option
*/
function commitAndClose(
address strikeSelection,
address optionsPremiumPricer,
uint256 premiumDiscount,
CloseParams calldata closeParams,
Vault.VaultParams storage vaultParams,
Vault.VaultState storage vaultState
)
external
returns (
address otokenAddress,
uint256 premium,
uint256 strikePrice,
uint256 delta
)
{
uint256 expiry;
// uninitialized state
if (closeParams.currentOption == address(0)) {
expiry = getNextFriday(block.timestamp);
} else {
expiry = getNextFriday(
IOtoken(closeParams.currentOption).expiryTimestamp()
);
}
IStrikeSelection selection = IStrikeSelection(strikeSelection);
bool isPut = vaultParams.isPut;
address underlying = vaultParams.underlying;
address asset = vaultParams.asset;
(strikePrice, delta) = closeParams.lastStrikeOverrideRound ==
vaultState.round
? (closeParams.overriddenStrikePrice, selection.delta())
: selection.getStrikePrice(expiry, isPut);
require(strikePrice != 0, "!strikePrice");
// retrieve address if option already exists, or deploy it
otokenAddress = getOrDeployOtoken(
closeParams,
vaultParams,
underlying,
asset,
strikePrice,
expiry,
isPut
);
// get the black scholes premium of the option
premium = GnosisAuction.getOTokenPremium(
otokenAddress,
optionsPremiumPricer,
premiumDiscount
);
require(premium > 0, "!premium");
return (otokenAddress, premium, strikePrice, delta);
}
/**
* @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes
* @param otokenAddress is the address of the otoken
* @param vaultParams is the struct with vault general data
* @param collateralAsset is the address of the collateral asset
* @param USDC is the address of usdc
* @param delay is the delay between commitAndClose and rollToNextOption
*/
function verifyOtoken(
address otokenAddress,
Vault.VaultParams storage vaultParams,
address collateralAsset,
address USDC,
uint256 delay
) private view {
require(otokenAddress != address(0), "!otokenAddress");
IOtoken otoken = IOtoken(otokenAddress);
require(otoken.isPut() == vaultParams.isPut, "Type mismatch");
require(
otoken.underlyingAsset() == vaultParams.underlying,
"Wrong underlyingAsset"
);
require(
otoken.collateralAsset() == collateralAsset,
"Wrong collateralAsset"
);
// we just assume all options use USDC as the strike
require(otoken.strikeAsset() == USDC, "strikeAsset != USDC");
uint256 readyAt = block.timestamp.add(delay);
require(otoken.expiryTimestamp() >= readyAt, "Expiry before delay");
}
/**
* @notice Calculate the shares to mint, new price per share, and
amount of funds to re-allocate as collateral for the new round
* @param currentShareSupply is the total supply of shares
* @param asset is the address of the vault's asset
* @param decimals is the decimals of the asset
* @param pendingAmount is the amount of funds pending from recent deposits
* @return newLockedAmount is the amount of funds to allocate for the new round
* @return queuedWithdrawAmount is the amount of funds set aside for withdrawal
* @return newPricePerShare is the price per share of the new round
* @return mintShares is the amount of shares to mint from deposits
*/
function rollover(
uint256 currentShareSupply,
address asset,
uint256 decimals,
uint256 pendingAmount,
uint256 queuedWithdrawShares
)
external
view
returns (
uint256 newLockedAmount,
uint256 queuedWithdrawAmount,
uint256 newPricePerShare,
uint256 mintShares
)
{
uint256 currentBalance = IERC20(asset).balanceOf(address(this));
newPricePerShare = ShareMath.pricePerShare(
currentShareSupply,
currentBalance,
pendingAmount,
decimals
);
// After closing the short, if the options expire in-the-money
// vault pricePerShare would go down because vault's asset balance decreased.
// This ensures that the newly-minted shares do not take on the loss.
uint256 _mintShares =
ShareMath.assetToShares(pendingAmount, newPricePerShare, decimals);
uint256 newSupply = currentShareSupply.add(_mintShares);
uint256 queuedWithdraw =
newSupply > 0
? ShareMath.sharesToAsset(
queuedWithdrawShares,
newPricePerShare,
decimals
)
: 0;
return (
currentBalance.sub(queuedWithdraw),
queuedWithdraw,
newPricePerShare,
_mintShares
);
}
/**
* @notice Creates the actual Opyn short position by depositing collateral and minting otokens
* @param gammaController is the address of the opyn controller contract
* @param marginPool is the address of the opyn margin contract which holds the collateral
* @param oTokenAddress is the address of the otoken to mint
* @param depositAmount is the amount of collateral to deposit
* @return the otoken mint amount
*/
function createShort(
address gammaController,
address marginPool,
address oTokenAddress,
uint256 depositAmount
) external returns (uint256) {
IController controller = IController(gammaController);
uint256 newVaultID =
(controller.getAccountVaultCounter(address(this))).add(1);
// An otoken's collateralAsset is the vault's `asset`
// So in the context of performing Opyn short operations we call them collateralAsset
IOtoken oToken = IOtoken(oTokenAddress);
address collateralAsset = oToken.collateralAsset();
uint256 collateralDecimals =
uint256(IERC20Detailed(collateralAsset).decimals());
uint256 mintAmount;
if (oToken.isPut()) {
// For minting puts, there will be instances where the full depositAmount will not be used for minting.
// This is because of an issue with precision.
//
// For ETH put options, we are calculating the mintAmount (10**8 decimals) using
// the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down.
// As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens.
//
// For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens.
// We retain the dust in the vault so the calling contract can withdraw the
// actual locked amount + dust at settlement.
//
// To test this behavior, we can console.log
// MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault)
// to see how much dust (or excess collateral) is left behind.
mintAmount = depositAmount
.mul(10**Vault.OTOKEN_DECIMALS)
.mul(10**18) // we use 10**18 to give extra precision
.div(oToken.strikePrice().mul(10**(10 + collateralDecimals)));
} else {
mintAmount = depositAmount;
uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals
if (mintAmount > scaleBy && collateralDecimals > 8) {
mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8
}
}
// double approve to fix non-compliant ERC20s
IERC20 collateralToken = IERC20(collateralAsset);
collateralToken.safeApproveNonCompliant(marginPool, depositAmount);
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](3);
actions[0] = IController.ActionArgs(
IController.ActionType.OpenVault,
address(this), // owner
address(this), // receiver
address(0), // asset, otoken
newVaultID, // vaultId
0, // amount
0, //index
"" //data
);
actions[1] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this), // owner
address(this), // address to transfer from
collateralAsset, // deposited asset
newVaultID, // vaultId
depositAmount, // amount
0, //index
"" //data
);
actions[2] = IController.ActionArgs(
IController.ActionType.MintShortOption,
address(this), // owner
address(this), // address to transfer to
oTokenAddress, // deposited asset
newVaultID, // vaultId
mintAmount, // amount
0, //index
"" //data
);
controller.operate(actions);
return mintAmount;
}
/**
* @notice Close the existing short otoken position. Currently this implementation is simple.
* It closes the most recent vault opened by the contract. This assumes that the contract will
* only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by
calling SettleVault action, this assumption should hold.
* @param gammaController is the address of the opyn controller contract
* @return amount of collateral redeemed from the vault
*/
function settleShort(address gammaController) external returns (uint256) {
IController controller = IController(gammaController);
// gets the currently active vault ID
uint256 vaultID = controller.getAccountVaultCounter(address(this));
GammaTypes.Vault memory vault =
controller.getVault(address(this), vaultID);
require(vault.shortOtokens.length > 0, "No short");
// An otoken's collateralAsset is the vault's `asset`
// So in the context of performing Opyn short operations we call them collateralAsset
IERC20 collateralToken = IERC20(vault.collateralAssets[0]);
// The short position has been previously closed, or all the otokens have been burned.
// So we return early.
if (address(collateralToken) == address(0)) {
return 0;
}
// This is equivalent to doing IERC20(vault.asset).balanceOf(address(this))
uint256 startCollateralBalance =
collateralToken.balanceOf(address(this));
// If it is after expiry, we need to settle the short position using the normal way
// Delete the vault and withdraw all remaining collateral from the vault
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.SettleVault,
address(this), // owner
address(this), // address to transfer to
address(0), // not used
vaultID, // vaultId
0, // not used
0, // not used
"" // not used
);
controller.operate(actions);
uint256 endCollateralBalance = collateralToken.balanceOf(address(this));
return endCollateralBalance.sub(startCollateralBalance);
}
/**
* @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple.
* It calls the `Redeem` action to claim the payout.
* @param gammaController is the address of the opyn controller contract
* @param oldOption is the address of the old option
* @param asset is the address of the vault's asset
* @return amount of asset received by exercising the option
*/
function settleLong(
address gammaController,
address oldOption,
address asset
) external returns (uint256) {
IController controller = IController(gammaController);
uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this));
if (controller.getPayout(oldOption, oldOptionBalance) == 0) {
return 0;
}
uint256 startAssetBalance = IERC20(asset).balanceOf(address(this));
// If it is after expiry, we need to redeem the profits
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.Redeem,
address(0), // not used
address(this), // address to send profits to
oldOption, // address of otoken
0, // not used
oldOptionBalance, // otoken balance
0, // not used
"" // not used
);
controller.operate(actions);
uint256 endAssetBalance = IERC20(asset).balanceOf(address(this));
return endAssetBalance.sub(startAssetBalance);
}
/**
* @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple.
* It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will
* only have a single vault open at any given time.
* @param gammaController is the address of the opyn controller contract
* @param currentOption is the address of the current option
* @return amount of collateral redeemed by burning otokens
*/
function burnOtokens(address gammaController, address currentOption)
external
returns (uint256)
{
uint256 numOTokensToBurn =
IERC20(currentOption).balanceOf(address(this));
require(numOTokensToBurn > 0, "No oTokens to burn");
IController controller = IController(gammaController);
// gets the currently active vault ID
uint256 vaultID = controller.getAccountVaultCounter(address(this));
GammaTypes.Vault memory vault =
controller.getVault(address(this), vaultID);
require(vault.shortOtokens.length > 0, "No short");
IERC20 collateralToken = IERC20(vault.collateralAssets[0]);
uint256 startCollateralBalance =
collateralToken.balanceOf(address(this));
// Burning `amount` of oTokens from the ribbon vault,
// then withdrawing the corresponding collateral amount from the vault
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](2);
actions[0] = IController.ActionArgs(
IController.ActionType.BurnShortOption,
address(this), // owner
address(this), // address to transfer from
address(vault.shortOtokens[0]), // otoken address
vaultID, // vaultId
numOTokensToBurn, // amount
0, //index
"" //data
);
actions[1] = IController.ActionArgs(
IController.ActionType.WithdrawCollateral,
address(this), // owner
address(this), // address to transfer to
address(collateralToken), // withdrawn asset
vaultID, // vaultId
vault.collateralAmounts[0].mul(numOTokensToBurn).div(
vault.shortAmounts[0]
), // amount
0, //index
"" //data
);
controller.operate(actions);
uint256 endCollateralBalance = collateralToken.balanceOf(address(this));
return endCollateralBalance.sub(startCollateralBalance);
}
/**
* @notice Calculates the performance and management fee for this week's round
* @param vaultState is the struct with vault accounting state
* @param currentLockedBalance is the amount of funds currently locked in opyn
* @param performanceFeePercent is the performance fee pct.
* @param managementFeePercent is the management fee pct.
* @return performanceFeeInAsset is the performance fee
* @return managementFeeInAsset is the management fee
* @return vaultFee is the total fees
*/
function getVaultFees(
Vault.VaultState storage vaultState,
uint256 currentLockedBalance,
uint256 performanceFeePercent,
uint256 managementFeePercent
)
external
view
returns (
uint256 performanceFeeInAsset,
uint256 managementFeeInAsset,
uint256 vaultFee
)
{
uint256 prevLockedAmount = vaultState.lastLockedAmount;
uint256 lockedBalanceSansPending =
currentLockedBalance.sub(vaultState.totalPending);
uint256 _performanceFeeInAsset;
uint256 _managementFeeInAsset;
uint256 _vaultFee;
// Take performance fee and management fee ONLY if difference between
// last week and this week's vault deposits, taking into account pending
// deposits and withdrawals, is positive. If it is negative, last week's
// option expired ITM past breakeven, and the vault took a loss so we
// do not collect performance fee for last week
if (lockedBalanceSansPending > prevLockedAmount) {
_performanceFeeInAsset = performanceFeePercent > 0
? lockedBalanceSansPending
.sub(prevLockedAmount)
.mul(performanceFeePercent)
.div(100 * Vault.FEE_MULTIPLIER)
: 0;
_managementFeeInAsset = managementFeePercent > 0
? lockedBalanceSansPending.mul(managementFeePercent).div(
100 * Vault.FEE_MULTIPLIER
)
: 0;
_vaultFee = _performanceFeeInAsset.add(_managementFeeInAsset);
}
return (_performanceFeeInAsset, _managementFeeInAsset, _vaultFee);
}
/**
* @notice Either retrieves the option token if it already exists, or deploy it
* @param closeParams is the struct with details on previous option and strike selection details
* @param vaultParams is the struct with vault general data
* @param underlying is the address of the underlying asset of the option
* @param collateralAsset is the address of the collateral asset of the option
* @param strikePrice is the strike price of the option
* @param expiry is the expiry timestamp of the option
* @param isPut is whether the option is a put
* @return the address of the option
*/
function getOrDeployOtoken(
CloseParams calldata closeParams,
Vault.VaultParams storage vaultParams,
address underlying,
address collateralAsset,
uint256 strikePrice,
uint256 expiry,
bool isPut
) internal returns (address) {
IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY);
address otokenFromFactory =
factory.getOtoken(
underlying,
closeParams.USDC,
collateralAsset,
strikePrice,
expiry,
isPut
);
if (otokenFromFactory != address(0)) {
return otokenFromFactory;
}
address otoken =
factory.createOtoken(
underlying,
closeParams.USDC,
collateralAsset,
strikePrice,
expiry,
isPut
);
verifyOtoken(
otoken,
vaultParams,
collateralAsset,
closeParams.USDC,
closeParams.delay
);
return otoken;
}
/**
* @notice Starts the gnosis auction
* @param auctionDetails is the struct with all the custom parameters of the auction
* @return the auction id of the newly created auction
*/
function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails)
external
returns (uint256)
{
return GnosisAuction.startAuction(auctionDetails);
}
/**
* @notice Places a bid in an auction
* @param bidDetails is the struct with all the details of the
bid including the auction's id and how much to bid
*/
function placeBid(GnosisAuction.BidDetails calldata bidDetails)
external
returns (
uint256 sellAmount,
uint256 buyAmount,
uint64 userId
)
{
return GnosisAuction.placeBid(bidDetails);
}
/**
* @notice Claims the oTokens belonging to the vault
* @param auctionSellOrder is the sell order of the bid
* @param gnosisEasyAuction is the address of the gnosis auction contract
holding custody to the funds
* @param counterpartyThetaVault is the address of the counterparty theta
vault of this delta vault
*/
function claimAuctionOtokens(
Vault.AuctionSellOrder calldata auctionSellOrder,
address gnosisEasyAuction,
address counterpartyThetaVault
) external {
GnosisAuction.claimAuctionOtokens(
auctionSellOrder,
gnosisEasyAuction,
counterpartyThetaVault
);
}
/**
* @notice Verify the constructor params satisfy requirements
* @param owner is the owner of the vault with critical permissions
* @param feeRecipient is the address to recieve vault performance and management fees
* @param performanceFee is the perfomance fee pct.
* @param tokenName is the name of the token
* @param tokenSymbol is the symbol of the token
* @param _vaultParams is the struct with vault general data
*/
function verifyInitializerParams(
address owner,
address keeper,
address feeRecipient,
uint256 performanceFee,
uint256 managementFee,
string calldata tokenName,
string calldata tokenSymbol,
Vault.VaultParams calldata _vaultParams
) external pure {
require(owner != address(0), "!owner");
require(keeper != address(0), "!keeper");
require(feeRecipient != address(0), "!feeRecipient");
require(
performanceFee < 100 * Vault.FEE_MULTIPLIER,
"performanceFee >= 100%"
);
require(
managementFee < 100 * Vault.FEE_MULTIPLIER,
"managementFee >= 100%"
);
require(bytes(tokenName).length > 0, "!tokenName");
require(bytes(tokenSymbol).length > 0, "!tokenSymbol");
require(_vaultParams.asset != address(0), "!asset");
require(_vaultParams.underlying != address(0), "!underlying");
require(_vaultParams.minimumSupply > 0, "!minimumSupply");
require(_vaultParams.cap > 0, "!cap");
require(
_vaultParams.cap > _vaultParams.minimumSupply,
"cap has to be higher than minimumSupply"
);
}
/**
* @notice Gets the next options expiry timestamp
* @param currentExpiry is the expiry timestamp of the current option
* Reference: https://codereview.stackexchange.com/a/33532
* Examples:
* getNextFriday(week 1 thursday) -> week 1 friday
* getNextFriday(week 1 friday) -> week 2 friday
* getNextFriday(week 1 saturday) -> week 2 friday
*/
function getNextFriday(uint256 currentExpiry)
internal
pure
returns (uint256)
{
// dayOfWeek = 0 (sunday) - 6 (saturday)
uint256 dayOfWeek = ((currentExpiry / 1 days) + 4) % 7;
uint256 nextFriday = currentExpiry + ((7 + 5 - dayOfWeek) % 7) * 1 days;
uint256 friday8am = nextFriday - (nextFriday % (24 hours)) + (8 hours);
// If the passed currentExpiry is day=Friday hour>8am, we simply increment it by a week to next Friday
if (currentExpiry >= friday8am) {
friday8am += 7 days;
}
return friday8am;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {DSMath} from "../vendor/DSMath.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {VaultLifecycle} from "./VaultLifecycle.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Vault} from "./Vault.sol";
import {ShareMath} from "./ShareMath.sol";
import {ISTETH, IWSTETH} from "../interfaces/ISTETH.sol";
import {IWETH} from "../interfaces/IWETH.sol";
import {ICRV} from "../interfaces/ICRV.sol";
import {IStrikeSelection} from "../interfaces/IRibbon.sol";
import {GnosisAuction} from "./GnosisAuction.sol";
import {
IOtokenFactory,
IOtoken,
IController,
GammaTypes
} from "../interfaces/GammaInterface.sol";
import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol";
library VaultLifecycleSTETH {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Sets the next option the vault will be shorting, and calculates its premium for the auction
* @param strikeSelection is the address of the contract with strike selection logic
* @param optionsPremiumPricer is the address of the contract with the
black-scholes premium calculation logic
* @param premiumDiscount is the vault's discount applied to the premium
* @param closeParams is the struct with details on previous option and strike selection details
* @param vaultParams is the struct with vault general data
* @param vaultState is the struct with vault accounting state
* @param collateralAsset is the address of the collateral asset
* @return otokenAddress is the address of the new option
* @return premium is the premium of the new option
* @return strikePrice is the strike price of the new option
* @return delta is the delta of the new option
*/
function commitAndClose(
address strikeSelection,
address optionsPremiumPricer,
uint256 premiumDiscount,
VaultLifecycle.CloseParams calldata closeParams,
Vault.VaultParams storage vaultParams,
Vault.VaultState storage vaultState,
address collateralAsset
)
external
returns (
address otokenAddress,
uint256 premium,
uint256 strikePrice,
uint256 delta
)
{
uint256 expiry;
// uninitialized state
if (closeParams.currentOption == address(0)) {
expiry = VaultLifecycle.getNextFriday(block.timestamp);
} else {
expiry = VaultLifecycle.getNextFriday(
IOtoken(closeParams.currentOption).expiryTimestamp()
);
}
IStrikeSelection selection = IStrikeSelection(strikeSelection);
// calculate strike and delta
(strikePrice, delta) = closeParams.lastStrikeOverrideRound ==
vaultState.round
? (closeParams.overriddenStrikePrice, selection.delta())
: selection.getStrikePrice(expiry, false);
require(strikePrice != 0, "!strikePrice");
// retrieve address if option already exists, or deploy it
otokenAddress = VaultLifecycle.getOrDeployOtoken(
closeParams,
vaultParams,
vaultParams.underlying,
collateralAsset,
strikePrice,
expiry,
false
);
// get the black scholes premium of the option and adjust premium based on
// steth <-> eth exchange rate
premium = DSMath.wmul(
GnosisAuction.getOTokenPremium(
otokenAddress,
optionsPremiumPricer,
premiumDiscount
),
IWSTETH(collateralAsset).stEthPerToken()
);
require(premium > 0, "!premium");
return (otokenAddress, premium, strikePrice, delta);
}
/**
* @notice Calculate the shares to mint, new price per share, and
amount of funds to re-allocate as collateral for the new round
* @param currentShareSupply is the total supply of shares
* @param currentBalance is the total balance of the vault
* @param vaultParams is the struct with vault general data
* @param vaultState is the struct with vault accounting state
* @return newLockedAmount is the amount of funds to allocate for the new round
* @return queuedWithdrawAmount is the amount of funds set aside for withdrawal
* @return newPricePerShare is the price per share of the new round
* @return mintShares is the amount of shares to mint from deposits
*/
function rollover(
uint256 currentShareSupply,
uint256 currentBalance,
Vault.VaultParams calldata vaultParams,
Vault.VaultState calldata vaultState
)
external
pure
returns (
uint256 newLockedAmount,
uint256 queuedWithdrawAmount,
uint256 newPricePerShare,
uint256 mintShares
)
{
uint256 pendingAmount = uint256(vaultState.totalPending);
uint256 _decimals = vaultParams.decimals;
newPricePerShare = ShareMath.pricePerShare(
currentShareSupply,
currentBalance,
pendingAmount,
_decimals
);
// After closing the short, if the options expire in-the-money
// vault pricePerShare would go down because vault's asset balance decreased.
// This ensures that the newly-minted shares do not take on the loss.
uint256 _mintShares =
ShareMath.assetToShares(pendingAmount, newPricePerShare, _decimals);
uint256 newSupply = currentShareSupply.add(_mintShares);
uint256 queuedAmount =
newSupply > 0
? ShareMath.sharesToAsset(
vaultState.queuedWithdrawShares,
newPricePerShare,
_decimals
)
: 0;
return (
currentBalance.sub(queuedAmount),
queuedAmount,
newPricePerShare,
_mintShares
);
}
/**
* @notice Creates the actual Opyn short position by depositing collateral and minting otokens
* @param gammaController is the address of the opyn controller contract
* @param marginPool is the address of the opyn margin contract which holds the collateral
* @param oTokenAddress is the address of the otoken to mint
* @param depositAmount is the amount of collateral to deposit
* @return the otoken mint amount
*/
function createShort(
address gammaController,
address marginPool,
address oTokenAddress,
uint256 depositAmount
) external returns (uint256) {
IController controller = IController(gammaController);
uint256 newVaultID =
(controller.getAccountVaultCounter(address(this))).add(1);
// An otoken's collateralAsset is the vault's `asset`
// So in the context of performing Opyn short operations we call them collateralAsset
IOtoken oToken = IOtoken(oTokenAddress);
address collateralAsset = oToken.collateralAsset();
uint256 collateralDecimals =
uint256(IERC20Detailed(collateralAsset).decimals());
uint256 mintAmount;
mintAmount = depositAmount;
uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals
if (mintAmount > scaleBy && collateralDecimals > 8) {
mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8
}
// double approve to fix non-compliant ERC20s
IERC20 collateralToken = IERC20(collateralAsset);
collateralToken.safeApprove(marginPool, depositAmount);
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](3);
actions[0] = IController.ActionArgs(
IController.ActionType.OpenVault,
address(this), // owner
address(this), // receiver
address(0), // asset, otoken
newVaultID, // vaultId
0, // amount
0, //index
"" //data
);
actions[1] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this), // owner
address(this), // address to transfer from
collateralAsset, // deposited asset
newVaultID, // vaultId
depositAmount, // amount
0, //index
"" //data
);
actions[2] = IController.ActionArgs(
IController.ActionType.MintShortOption,
address(this), // owner
address(this), // address to transfer to
oTokenAddress, // deposited asset
newVaultID, // vaultId
mintAmount, // amount
0, //index
"" //data
);
controller.operate(actions);
return mintAmount;
}
/**
* @notice Withdraws stETH + ETH (if necessary) from vault using vault shares
* @param collateralToken is the address of the collateral token
* @param weth is the WETH address
* @param recipient is the recipient
* @param amount is the withdraw amount in `asset`
* @return withdrawAmount is the withdraw amount in `collateralToken`
*/
function withdrawYieldAndBaseToken(
address collateralToken,
address weth,
address recipient,
uint256 amount
) external returns (uint256) {
IWSTETH collateral = IWSTETH(collateralToken);
uint256 withdrawAmount = collateral.getWstETHByStETH(amount);
uint256 yieldTokenBalance =
withdrawYieldToken(collateralToken, recipient, withdrawAmount);
// If there is not enough wstETH in the vault, it withdraws as much as possible and
// transfers the rest in `asset`
if (withdrawAmount > yieldTokenBalance) {
withdrawBaseToken(
collateralToken,
weth,
recipient,
withdrawAmount,
yieldTokenBalance
);
}
return withdrawAmount;
}
/**
* @notice Withdraws stETH from vault
* @param collateralToken is the address of the collateral token
* @param recipient is the recipient
* @param withdrawAmount is the withdraw amount in terms of yearn tokens
* @return yieldTokenBalance is the balance of the yield token
*/
function withdrawYieldToken(
address collateralToken,
address recipient,
uint256 withdrawAmount
) internal returns (uint256) {
IERC20 collateral = IERC20(collateralToken);
uint256 yieldTokenBalance = collateral.balanceOf(address(this));
uint256 yieldTokensToWithdraw =
DSMath.min(yieldTokenBalance, withdrawAmount);
if (yieldTokensToWithdraw > 0) {
collateral.safeTransfer(recipient, yieldTokensToWithdraw);
}
return yieldTokenBalance;
}
/**
* @notice Withdraws `asset` from vault
* @param collateralToken is the address of the collateral token
* @param weth is the WETH address
* @param recipient is the recipient
* @param withdrawAmount is the withdraw amount in terms of yearn tokens
* @param yieldTokenBalance is the collateral token (stETH) balance of the vault
*/
function withdrawBaseToken(
address collateralToken,
address weth,
address recipient,
uint256 withdrawAmount,
uint256 yieldTokenBalance
) internal {
uint256 underlyingTokensToWithdraw =
IWSTETH(collateralToken).getStETHByWstETH(
withdrawAmount.sub(yieldTokenBalance)
);
IWETH(weth).deposit{value: underlyingTokensToWithdraw}();
IERC20(weth).safeTransfer(recipient, underlyingTokensToWithdraw);
}
/**
* @notice Unwraps the necessary amount of the yield-bearing yearn token
* and transfers amount to vault
* @param amount is the amount of `asset` to withdraw
* @param collateralToken is the address of the collateral token
* @param crvPool is the address of the steth <-> eth pool on curve
* @param minETHOut is the min eth to recieve
* @return amountETHOut is the amount of eth we have
available for the withdrawal (may incur curve slippage)
*/
function unwrapYieldToken(
uint256 amount,
address collateralToken,
address crvPool,
uint256 minETHOut
) external returns (uint256) {
uint256 assetBalance = address(this).balance;
uint256 amountETHOut = DSMath.min(assetBalance, amount);
uint256 amountToUnwrap =
IWSTETH(collateralToken).getWstETHByStETH(
DSMath.max(assetBalance, amount).sub(assetBalance)
);
if (amountToUnwrap > 0) {
IWSTETH wsteth = IWSTETH(collateralToken);
// Unrap to stETH
wsteth.unwrap(amountToUnwrap);
// approve steth exchange
IERC20(wsteth.stETH()).safeApprove(crvPool, amountToUnwrap);
// CRV SWAP HERE from steth -> eth
// 0 = ETH, 1 = STETH
amountETHOut = amountETHOut.add(
ICRV(crvPool).exchange(1, 0, amountToUnwrap, minETHOut)
);
}
return amountETHOut;
}
/**
* @notice Wraps the necessary amount of the base token to the yield-bearing yearn token
* @param weth is the address of weth
* @param collateralToken is the address of the collateral token
*/
function wrapToYieldToken(address weth, address collateralToken) external {
// Unwrap all weth premiums transferred to contract
IWETH wethToken = IWETH(weth);
uint256 wethBalance = wethToken.balanceOf(address(this));
if (wethBalance > 0) {
wethToken.withdraw(wethBalance);
}
uint256 ethBalance = address(this).balance;
IWSTETH collateral = IWSTETH(collateralToken);
ISTETH stethToken = ISTETH(collateral.stETH());
if (ethBalance > 0) {
// Send eth to Lido, recieve steth
stethToken.submit{value: ethBalance}(address(this));
}
// Get all steth in contract
uint256 stethBalance = stethToken.balanceOf(address(this));
if (stethBalance > 0) {
// approve wrap
IERC20(address(stethToken)).safeApprove(
collateralToken,
stethBalance.add(1)
);
// Wrap to wstETH - need to add 1 to steth balance as it is innacurate
collateral.wrap(stethBalance.add(1));
}
}
/**
* @notice Helper function to make either an ETH transfer or ERC20 transfer
* @param recipient is the receiving address
* @param amount is the transfer amount
*/
function transferAsset(address recipient, uint256 amount) public {
(bool success, ) = payable(recipient).call{value: amount}("");
require(success, "!success");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {Vault} from "./Vault.sol";
library ShareMath {
using SafeMath for uint256;
uint256 internal constant PLACEHOLDER_UINT = 1;
function assetToShares(
uint256 assetAmount,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256) {
// If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet
// which should never happen.
// Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.
require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare");
return assetAmount.mul(10**decimals).div(assetPerShare);
}
function sharesToAsset(
uint256 shares,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256) {
// If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet
// which should never happen.
// Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.
require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare");
return shares.mul(assetPerShare).div(10**decimals);
}
/**
* @notice Returns the shares unredeemed by the user given their DepositReceipt
* @param depositReceipt is the user's deposit receipt
* @param currentRound is the `round` stored on the vault
* @param assetPerShare is the price in asset per share
* @param decimals is the number of decimals the asset/shares use
* @return unredeemedShares is the user's virtual balance of shares that are owed
*/
function getSharesFromReceipt(
Vault.DepositReceipt memory depositReceipt,
uint256 currentRound,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256 unredeemedShares) {
if (depositReceipt.round > 0 && depositReceipt.round < currentRound) {
uint256 sharesFromRound =
assetToShares(depositReceipt.amount, assetPerShare, decimals);
return
uint256(depositReceipt.unredeemedShares).add(sharesFromRound);
}
return depositReceipt.unredeemedShares;
}
function pricePerShare(
uint256 totalSupply,
uint256 totalBalance,
uint256 pendingAmount,
uint256 decimals
) internal pure returns (uint256) {
uint256 singleShare = 10**decimals;
return
totalSupply > 0
? singleShare.mul(totalBalance.sub(pendingAmount)).div(
totalSupply
)
: singleShare;
}
/************************************************
* HELPERS
***********************************************/
function assertUint104(uint256 num) internal pure {
require(num <= type(uint104).max, "Overflow uint104");
}
function assertUint128(uint256 num) internal pure {
require(num <= type(uint128).max, "Overflow uint128");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IWSTETH} from "../../../interfaces/ISTETH.sol";
import {IWETH} from "../../../interfaces/IWETH.sol";
import {Vault} from "../../../libraries/Vault.sol";
import {VaultLifecycle} from "../../../libraries/VaultLifecycle.sol";
import {VaultLifecycleSTETH} from "../../../libraries/VaultLifecycleSTETH.sol";
import {ShareMath} from "../../../libraries/ShareMath.sol";
contract RibbonVault is
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
ERC20Upgradeable
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
using ShareMath for Vault.DepositReceipt;
/************************************************
* NON UPGRADEABLE STORAGE
***********************************************/
/// @notice Stores the user's pending deposit for the round
mapping(address => Vault.DepositReceipt) public depositReceipts;
/// @notice On every round's close, the pricePerShare value of an rTHETA token is stored
/// This is used to determine the number of shares to be returned
/// to a user with their DepositReceipt.depositAmount
mapping(uint256 => uint256) public roundPricePerShare;
/// @notice Stores pending user withdrawals
mapping(address => Vault.Withdrawal) public withdrawals;
/// @notice Vault's parameters like cap, decimals
Vault.VaultParams public vaultParams;
/// @notice Vault's lifecycle state like round and locked amounts
Vault.VaultState public vaultState;
/// @notice Vault's state of the options sold and the timelocked option
Vault.OptionState public optionState;
/// @notice Fee recipient for the performance and management fees
address public feeRecipient;
/// @notice role in charge of weekly vault operations such as rollToNextOption and burnRemainingOTokens
// no access to critical vault changes
address public keeper;
/// @notice Performance fee charged on premiums earned in rollToNextOption. Only charged when there is no loss.
uint256 public performanceFee;
/// @notice Management fee charged on entire AUM in rollToNextOption. Only charged when there is no loss.
uint256 public managementFee;
/// @notice wstETH vault contract
IWSTETH public immutable collateralToken;
// Gap is left to avoid storage collisions. Though RibbonVault is not upgradeable, we add this as a safety measure.
uint256[30] private ____gap;
// *IMPORTANT* NO NEW STORAGE VARIABLES SHOULD BE ADDED HERE
// This is to prevent storage collisions. All storage variables should be appended to RibbonThetaSTETHVaultStorage
// https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts
/************************************************
* IMMUTABLES & CONSTANTS
***********************************************/
/// @notice WETH9 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
address public immutable WETH;
/// @notice USDC 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
address public immutable USDC;
/// @notice Lido DAO token 0x5a98fcbea516cf06857215779fd812ca3bef1b32
address public immutable LDO;
/// @notice 15 minute timelock between commitAndClose and rollToNexOption.
uint256 public constant DELAY = 15 minutes;
/// @notice 7 day period between each options sale.
uint256 public constant PERIOD = 7 days;
// Number of weeks per year = 52.142857 weeks * FEE_MULTIPLIER = 52142857
// Dividing by weeks per year requires doing num.mul(FEE_MULTIPLIER).div(WEEKS_PER_YEAR)
uint256 private constant WEEKS_PER_YEAR = 52142857;
// GAMMA_CONTROLLER is the top-level contract in Gamma protocol
// which allows users to perform multiple actions on their vaults
// and positions https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/Controller.sol
address public immutable GAMMA_CONTROLLER;
// MARGIN_POOL is Gamma protocol's collateral pool.
// Needed to approve collateral.safeTransferFrom for minting otokens.
// https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/MarginPool.sol
address public immutable MARGIN_POOL;
// GNOSIS_EASY_AUCTION is Gnosis protocol's contract for initiating auctions and placing bids
// https://github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol
address public immutable GNOSIS_EASY_AUCTION;
// Curve stETH / ETH stables pool
address public immutable STETH_ETH_CRV_POOL;
/************************************************
* EVENTS
***********************************************/
event Deposit(address indexed account, uint256 amount, uint256 round);
event InitiateWithdraw(
address indexed account,
uint256 shares,
uint256 round
);
event Redeem(address indexed account, uint256 share, uint256 round);
event ManagementFeeSet(uint256 managementFee, uint256 newManagementFee);
event PerformanceFeeSet(uint256 performanceFee, uint256 newPerformanceFee);
event CapSet(uint256 oldCap, uint256 newCap, address manager);
event Withdraw(address indexed account, uint256 amount, uint256 shares);
event CollectVaultFees(
uint256 performanceFee,
uint256 vaultFee,
uint256 round,
address indexed feeRecipient
);
/************************************************
* CONSTRUCTOR & INITIALIZATION
***********************************************/
/**
* @notice Initializes the contract with immutable variables
* @param _weth is the Wrapped Ether contract
* @param _usdc is the USDC contract
* @param _wsteth is the LDO contract
* @param _ldo is the LDO contract
* @param _gammaController is the contract address for opyn actions
* @param _marginPool is the contract address for providing collateral to opyn
* @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions
* @param _crvPool is the steth/eth crv stables pool
*/
constructor(
address _weth,
address _usdc,
address _wsteth,
address _ldo,
address _gammaController,
address _marginPool,
address _gnosisEasyAuction,
address _crvPool
) {
require(_weth != address(0), "!_weth");
require(_usdc != address(0), "!_usdc");
require(_wsteth != address(0), "!_wsteth");
require(_ldo != address(0), "!_ldo");
require(_gnosisEasyAuction != address(0), "!_gnosisEasyAuction");
require(_gammaController != address(0), "!_gammaController");
require(_marginPool != address(0), "!_marginPool");
require(_crvPool != address(0), "!_crvPool");
WETH = _weth;
USDC = _usdc;
LDO = _ldo;
GAMMA_CONTROLLER = _gammaController;
MARGIN_POOL = _marginPool;
GNOSIS_EASY_AUCTION = _gnosisEasyAuction;
STETH_ETH_CRV_POOL = _crvPool;
collateralToken = IWSTETH(_wsteth);
}
/**
* @notice Initializes the OptionVault contract with storage variables.
*/
function baseInitialize(
address _owner,
address _keeper,
address _feeRecipient,
uint256 _managementFee,
uint256 _performanceFee,
string memory _tokenName,
string memory _tokenSymbol,
Vault.VaultParams calldata _vaultParams
) internal initializer {
VaultLifecycle.verifyInitializerParams(
_owner,
_keeper,
_feeRecipient,
_performanceFee,
_managementFee,
_tokenName,
_tokenSymbol,
_vaultParams
);
__ReentrancyGuard_init();
__ERC20_init(_tokenName, _tokenSymbol);
__Ownable_init();
transferOwnership(_owner);
keeper = _keeper;
feeRecipient = _feeRecipient;
performanceFee = _performanceFee;
managementFee = _managementFee.mul(Vault.FEE_MULTIPLIER).div(
WEEKS_PER_YEAR
);
vaultParams = _vaultParams;
uint256 assetBalance = totalBalance();
ShareMath.assertUint104(assetBalance);
vaultState.lastLockedAmount = uint104(assetBalance);
vaultState.round = 1;
}
/**
* @dev Throws if called by any account other than the keeper.
*/
modifier onlyKeeper() {
require(msg.sender == keeper, "!keeper");
_;
}
/************************************************
* SETTERS
***********************************************/
/**
* @notice Sets the new keeper
* @param newKeeper is the address of the new keeper
*/
function setNewKeeper(address newKeeper) external onlyOwner {
require(newKeeper != address(0), "!newKeeper");
keeper = newKeeper;
}
/**
* @notice Sets the new fee recipient
* @param newFeeRecipient is the address of the new fee recipient
*/
function setFeeRecipient(address newFeeRecipient) external onlyOwner {
require(newFeeRecipient != address(0), "!newFeeRecipient");
require(newFeeRecipient != feeRecipient, "Must be new feeRecipient");
feeRecipient = newFeeRecipient;
}
/**
* @notice Sets the management fee for the vault
* @param newManagementFee is the management fee (6 decimals). ex: 2 * 10 ** 6 = 2%
*/
function setManagementFee(uint256 newManagementFee) external onlyOwner {
require(
newManagementFee < 100 * Vault.FEE_MULTIPLIER,
"Invalid management fee"
);
// We are dividing annualized management fee by num weeks in a year
managementFee = newManagementFee.mul(Vault.FEE_MULTIPLIER).div(
WEEKS_PER_YEAR
);
}
/**
* @notice Sets the performance fee for the vault
* @param newPerformanceFee is the performance fee (6 decimals). ex: 20 * 10 ** 6 = 20%
*/
function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner {
require(
newPerformanceFee < 100 * Vault.FEE_MULTIPLIER,
"Invalid performance fee"
);
emit PerformanceFeeSet(performanceFee, newPerformanceFee);
performanceFee = newPerformanceFee;
}
/**
* @notice Sets a new cap for deposits
* @param newCap is the new cap for deposits
*/
function setCap(uint256 newCap) external onlyOwner {
require(newCap > 0, "!newCap");
ShareMath.assertUint104(newCap);
vaultParams.cap = uint104(newCap);
}
/************************************************
* DEPOSIT & WITHDRAWALS
***********************************************/
/**
* @notice Deposits ETH into the contract and mint vault shares.
*/
function depositETH() external payable nonReentrant {
require(msg.value > 0, "!value");
_depositFor(msg.value, msg.sender, true);
}
/**
* @notice Deposits the `collateralAsset` into the contract and mint vault shares.
* @param amount is the amount of `collateralAsset` to deposit
*/
function depositYieldToken(uint256 amount) external nonReentrant {
require(amount > 0, "!amount");
_depositFor(
// off by one
collateralToken.getStETHByWstETH(amount).sub(1),
msg.sender,
false
);
IERC20(collateralToken.stETH()).safeTransferFrom(
msg.sender,
address(this),
amount
);
}
/**
* @notice Deposits the `asset` from msg.sender added to `creditor`'s deposit.
* @notice Used for vault -> vault deposits on the user's behalf
* @param creditor is the address that can claim/withdraw deposited amount
*/
function depositFor(address creditor) external payable nonReentrant {
require(msg.value > 0, "!value");
require(creditor != address(0), "!creditor");
_depositFor(msg.value, creditor, true);
}
/**
* @notice Mints the vault shares to the creditor
* @param amount is the amount of `asset` deposited
* @param creditor is the address to receieve the deposit
* @param isETH is whether this is a depositETH call
*/
function _depositFor(
uint256 amount,
address creditor,
bool isETH
) private {
uint256 currentRound = vaultState.round;
uint256 totalWithDepositedAmount =
isETH ? totalBalance() : totalBalance().add(amount);
require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap");
require(
totalWithDepositedAmount >= vaultParams.minimumSupply,
"Insufficient balance"
);
emit Deposit(creditor, amount, currentRound);
Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor];
// If we have an unprocessed pending deposit from the previous rounds, we have to process it.
uint256 unredeemedShares =
depositReceipt.getSharesFromReceipt(
currentRound,
roundPricePerShare[depositReceipt.round],
vaultParams.decimals
);
uint256 depositAmount = amount;
// If we have a pending deposit in the current round, we add on to the pending deposit
if (currentRound == depositReceipt.round) {
uint256 newAmount = uint256(depositReceipt.amount).add(amount);
depositAmount = newAmount;
}
ShareMath.assertUint104(depositAmount);
depositReceipts[creditor] = Vault.DepositReceipt({
round: uint16(currentRound),
amount: uint104(depositAmount),
unredeemedShares: uint128(unredeemedShares)
});
uint256 newTotalPending = uint256(vaultState.totalPending).add(amount);
ShareMath.assertUint128(newTotalPending);
vaultState.totalPending = uint128(newTotalPending);
}
/**
* @notice Initiates a withdrawal that can be processed once the round completes
* @param numShares is the number of shares to withdraw
*/
function initiateWithdraw(uint256 numShares) external nonReentrant {
require(numShares > 0, "!numShares");
// We do a max redeem before initiating a withdrawal
// But we check if they must first have unredeemed shares
if (
depositReceipts[msg.sender].amount > 0 ||
depositReceipts[msg.sender].unredeemedShares > 0
) {
_redeem(0, true);
}
// This caches the `round` variable used in shareBalances
uint256 currentRound = vaultState.round;
Vault.Withdrawal storage withdrawal = withdrawals[msg.sender];
bool withdrawalIsSameRound = withdrawal.round == currentRound;
emit InitiateWithdraw(msg.sender, numShares, currentRound);
uint256 existingShares = uint256(withdrawal.shares);
uint256 withdrawalShares;
if (withdrawalIsSameRound) {
withdrawalShares = existingShares.add(numShares);
} else {
require(existingShares == 0, "Existing withdraw");
withdrawalShares = numShares;
withdrawals[msg.sender].round = uint16(currentRound);
}
ShareMath.assertUint128(withdrawalShares);
withdrawals[msg.sender].shares = uint128(withdrawalShares);
uint256 newQueuedWithdrawShares =
uint256(vaultState.queuedWithdrawShares).add(numShares);
ShareMath.assertUint128(newQueuedWithdrawShares);
vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares);
_transfer(msg.sender, address(this), numShares);
}
/**
* @notice Completes a scheduled withdrawal from a past round. Uses finalized pps for the round
* @param minETHOut is the min amount of `asset` to recieve for the swapped amount of steth in crv pool
*/
function completeWithdraw(uint256 minETHOut) external nonReentrant {
Vault.Withdrawal storage withdrawal = withdrawals[msg.sender];
uint256 withdrawalShares = withdrawal.shares;
uint256 withdrawalRound = withdrawal.round;
// This checks if there is a withdrawal
require(withdrawalShares > 0, "Not initiated");
require(withdrawalRound < vaultState.round, "Round not closed");
// We leave the round number as non-zero to save on gas for subsequent writes
withdrawals[msg.sender].shares = 0;
vaultState.queuedWithdrawShares = uint128(
uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares)
);
uint256 withdrawAmount =
ShareMath.sharesToAsset(
withdrawalShares,
roundPricePerShare[withdrawalRound],
vaultParams.decimals
);
// Unwrap may incur curve pool slippage
uint256 amountETHOut =
VaultLifecycleSTETH.unwrapYieldToken(
withdrawAmount,
address(collateralToken),
STETH_ETH_CRV_POOL,
minETHOut
);
emit Withdraw(msg.sender, amountETHOut, withdrawalShares);
_burn(address(this), withdrawalShares);
require(amountETHOut > 0, "!amountETHOut");
VaultLifecycleSTETH.transferAsset(msg.sender, amountETHOut);
}
/**
* @notice Redeems shares that are owed to the account
* @param numShares is the number of shares to redeem
*/
function redeem(uint256 numShares) external nonReentrant {
require(numShares > 0, "!numShares");
_redeem(numShares, false);
}
/**
* @notice Redeems the entire unredeemedShares balance that is owed to the account
*/
function maxRedeem() external nonReentrant {
_redeem(0, true);
}
/**
* @notice Redeems shares that are owed to the account
* @param numShares is the number of shares to redeem, could be 0 when isMax=true
* @param isMax is flag for when callers do a max redemption
*/
function _redeem(uint256 numShares, bool isMax) internal {
Vault.DepositReceipt memory depositReceipt =
depositReceipts[msg.sender];
// This handles the null case when depositReceipt.round = 0
// Because we start with round = 1 at `initialize`
uint256 currentRound = vaultState.round;
uint256 unredeemedShares =
depositReceipt.getSharesFromReceipt(
currentRound,
roundPricePerShare[depositReceipt.round],
vaultParams.decimals
);
numShares = isMax ? unredeemedShares : numShares;
if (numShares == 0) {
return;
}
require(numShares <= unredeemedShares, "Exceeds available");
// If we have a depositReceipt on the same round, BUT we have some unredeemed shares
// we debit from the unredeemedShares, but leave the amount field intact
// If the round has past, with no new deposits, we just zero it out for new deposits.
depositReceipts[msg.sender].amount = depositReceipt.round < currentRound
? 0
: depositReceipt.amount;
ShareMath.assertUint128(numShares);
depositReceipts[msg.sender].unredeemedShares = uint128(
unredeemedShares.sub(numShares)
);
emit Redeem(msg.sender, numShares, depositReceipt.round);
_transfer(address(this), msg.sender, numShares);
}
/************************************************
* VAULT OPERATIONS
***********************************************/
/*
* @notice Helper function that helps to save gas for writing values into the roundPricePerShare map.
* Writing `1` into the map makes subsequent writes warm, reducing the gas from 20k to 5k.
* Having 1 initialized beforehand will not be an issue as long as we round down share calculations to 0.
* @param numRounds is the number of rounds to initialize in the map
*/
function initRounds(uint256 numRounds) external nonReentrant {
require(numRounds > 0, "!numRounds");
uint256 _round = vaultState.round;
for (uint256 i = 0; i < numRounds; i++) {
uint256 index = _round + i;
require(index >= _round, "Overflow");
require(roundPricePerShare[index] == 0, "Initialized"); // AVOID OVERWRITING ACTUAL VALUES
roundPricePerShare[index] = ShareMath.PLACEHOLDER_UINT;
}
}
/*
* @notice Helper function that performs most administrative tasks
* such as setting next option, minting new shares, getting vault fees, etc.
* @param lastQueuedWithdrawAmount is old queued withdraw amount
* @return newOption is the new option address
* @return queuedWithdrawAmount is the queued amount for withdrawal
*/
function _rollToNextOption(uint256 lastQueuedWithdrawAmount)
internal
returns (address, uint256)
{
require(block.timestamp >= optionState.nextOptionReadyAt, "!ready");
address newOption = optionState.nextOption;
require(newOption != address(0), "!nextOption");
(
uint256 lockedBalance,
uint256 queuedWithdrawAmount,
uint256 newPricePerShare,
uint256 mintShares
) =
VaultLifecycleSTETH.rollover(
totalSupply(),
totalBalance(),
vaultParams,
vaultState
);
optionState.currentOption = newOption;
optionState.nextOption = address(0);
// Finalize the pricePerShare at the end of the round
uint256 currentRound = vaultState.round;
roundPricePerShare[currentRound] = newPricePerShare;
// Wrap entire `asset` balance to `collateralToken` balance
VaultLifecycleSTETH.wrapToYieldToken(WETH, address(collateralToken));
uint256 withdrawAmountDiff =
queuedWithdrawAmount > lastQueuedWithdrawAmount
? queuedWithdrawAmount.sub(lastQueuedWithdrawAmount)
: 0;
// Take management / performance fee from previous round and deduct
lockedBalance = lockedBalance.sub(
_collectVaultFees(lockedBalance.add(withdrawAmountDiff))
);
vaultState.totalPending = 0;
vaultState.round = uint16(currentRound + 1);
ShareMath.assertUint104(lockedBalance);
vaultState.lockedAmount = uint104(lockedBalance);
_mint(address(this), mintShares);
return (newOption, queuedWithdrawAmount);
}
/*
* @notice Helper function that transfers management fees and performance fees from previous round.
* @param pastWeekBalance is the balance we are about to lock for next round
* @return vaultFee is the fee deducted
*/
function _collectVaultFees(uint256 pastWeekBalance)
internal
returns (uint256)
{
(uint256 performanceFeeInAsset, , uint256 vaultFee) =
VaultLifecycle.getVaultFees(
vaultState,
pastWeekBalance,
performanceFee,
managementFee
);
if (vaultFee > 0) {
VaultLifecycleSTETH.withdrawYieldAndBaseToken(
address(collateralToken),
WETH,
feeRecipient,
vaultFee
);
emit CollectVaultFees(
performanceFeeInAsset,
vaultFee,
vaultState.round,
feeRecipient
);
}
return vaultFee;
}
/*
* @notice Transfers LDO rewards to feeRecipient
*/
function sendLDORewards() external {
IERC20 ldo = IERC20(LDO);
ldo.safeTransfer(feeRecipient, ldo.balanceOf(address(this)));
}
/************************************************
* GETTERS
***********************************************/
/**
* @notice Returns the asset balance held on the vault for the account
* @param account is the address to lookup balance for
* @return the amount of `asset` custodied by the vault for the user
*/
function accountVaultBalance(address account)
external
view
returns (uint256)
{
uint256 _decimals = vaultParams.decimals;
uint256 assetPerShare =
ShareMath.pricePerShare(
totalSupply(),
totalBalance(),
vaultState.totalPending,
_decimals
);
return
ShareMath.sharesToAsset(shares(account), assetPerShare, _decimals);
}
/**
* @notice Getter for returning the account's share balance including unredeemed shares
* @param account is the account to lookup share balance for
* @return the share balance
*/
function shares(address account) public view returns (uint256) {
(uint256 heldByAccount, uint256 heldByVault) = shareBalances(account);
return heldByAccount.add(heldByVault);
}
/**
* @notice Getter for returning the account's share balance split between account and vault holdings
* @param account is the account to lookup share balance for
* @return heldByAccount is the shares held by account
* @return heldByVault is the shares held on the vault (unredeemedShares)
*/
function shareBalances(address account)
public
view
returns (uint256 heldByAccount, uint256 heldByVault)
{
Vault.DepositReceipt memory depositReceipt = depositReceipts[account];
if (depositReceipt.round < ShareMath.PLACEHOLDER_UINT) {
return (balanceOf(account), 0);
}
uint256 unredeemedShares =
depositReceipt.getSharesFromReceipt(
vaultState.round,
roundPricePerShare[depositReceipt.round],
vaultParams.decimals
);
return (balanceOf(account), unredeemedShares);
}
/**
* @notice The price of a unit of share denominated in the `asset`
*/
function pricePerShare() external view returns (uint256) {
return
ShareMath.pricePerShare(
totalSupply(),
totalBalance(),
vaultState.totalPending,
vaultParams.decimals
);
}
/**
* @notice Returns the vault's total balance, including the amounts locked into a short position
* @return total balance of the vault, including the amounts locked in third party protocols
*/
function totalBalance() public view returns (uint256) {
uint256 ethBalance =
IWETH(WETH).balanceOf(address(this)).add(address(this).balance);
uint256 wstethToeth =
collateralToken.getStETHByWstETH(
collateralToken.balanceOf(address(this)).add(
IERC20(collateralToken.stETH()).balanceOf(address(this))
)
);
return
uint256(vaultState.lockedAmount).add(ethBalance).add(wstethToeth);
}
/**
* @notice Returns the token decimals
*/
function decimals() public view override returns (uint8) {
return vaultParams.decimals;
}
function cap() external view returns (uint256) {
return vaultParams.cap;
}
function nextOptionReadyAt() external view returns (uint256) {
return optionState.nextOptionReadyAt;
}
function currentOption() external view returns (address) {
return optionState.currentOption;
}
function nextOption() external view returns (address) {
return optionState.nextOption;
}
function totalPending() external view returns (uint256) {
return vaultState.totalPending;
}
/************************************************
* HELPERS
***********************************************/
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
abstract contract RibbonThetaSTETHVaultStorageV1 {
// Logic contract used to price options
address public optionsPremiumPricer;
// Logic contract used to select strike prices
address public strikeSelection;
// Premium discount on options we are selling (thousandths place: 000 - 999)
uint256 public premiumDiscount;
// Current oToken premium
uint256 public currentOtokenPremium;
// Last round id at which the strike was manually overridden
uint16 public lastStrikeOverrideRound;
// Price last overridden strike set to
uint256 public overriddenStrikePrice;
// Auction duration
uint256 public auctionDuration;
// Auction id of current option
uint256 public optionAuctionID;
}
abstract contract RibbonThetaSTETHVaultStorageV2 {
// Amount locked for scheduled withdrawals last week;
uint256 public lastQueuedWithdrawAmount;
}
// We are following Compound's method of upgrading new contract implementations
// When we need to add new storage variables, we create a new version of RibbonThetaVaultStorage
// e.g. RibbonThetaVaultStorage<versionNumber>, so finally it would look like
// contract RibbonThetaVaultStorage is RibbonThetaVaultStorageV1, RibbonThetaVaultStorageV2
abstract contract RibbonThetaSTETHVaultStorage is
RibbonThetaSTETHVaultStorageV1,
RibbonThetaSTETHVaultStorageV2
{
}
// 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
/// 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;
library DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
//rounds to zero if x*y < WAD / 2
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 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(uint256 x, uint256 n) internal pure returns (uint256 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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library AuctionType {
struct AuctionData {
IERC20 auctioningToken;
IERC20 biddingToken;
uint256 orderCancellationEndDate;
uint256 auctionEndDate;
bytes32 initialAuctionOrder;
uint256 minimumBiddingAmountPerOrder;
uint256 interimSumBidAmount;
bytes32 interimOrder;
bytes32 clearingPriceOrder;
uint96 volumeClearingPriceOrder;
bool minFundingThresholdNotReached;
bool isAtomicClosureAllowed;
uint256 feeNumerator;
uint256 minFundingThreshold;
}
}
interface IGnosisAuction {
function initiateAuction(
address _auctioningToken,
address _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) external returns (uint256);
function auctionCounter() external view returns (uint256);
function auctionData(uint256 auctionId)
external
view
returns (AuctionType.AuctionData memory);
function auctionAccessManager(uint256 auctionId)
external
view
returns (address);
function auctionAccessData(uint256 auctionId)
external
view
returns (bytes memory);
function FEE_DENOMINATOR() external view returns (uint256);
function feeNumerator() external view returns (uint256);
function settleAuction(uint256 auctionId) external returns (bytes32);
function placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData
) external returns (uint64);
function claimFromParticipantOrder(
uint256 auctionId,
bytes32[] memory orders
) external returns (uint256, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library GammaTypes {
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault {
// addresses of oTokens a user has shorted (i.e. written) against this vault
address[] shortOtokens;
// addresses of oTokens a user has bought and deposited in this vault
// user can be long oTokens without opening a vault (e.g. by buying on a DEX)
// generally, long oTokens will be 'deposited' in vaults to act as collateral
// in order to write oTokens against (i.e. in spreads)
address[] longOtokens;
// addresses of other ERC-20s a user has deposited as collateral in this vault
address[] collateralAssets;
// quantity of oTokens minted/written for each oToken address in shortOtokens
uint256[] shortAmounts;
// quantity of oTokens owned and held in the vault for each oToken address in longOtokens
uint256[] longAmounts;
// quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets
uint256[] collateralAmounts;
}
}
interface IOtoken {
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
}
interface IOtokenFactory {
function getOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
function createOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external returns (address);
function getTargetOtokenAddress(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
event OtokenCreated(
address tokenAddress,
address creator,
address indexed underlying,
address indexed strike,
address indexed collateral,
uint256 strikePrice,
uint256 expiry,
bool isPut
);
}
interface IController {
// possible actions that can be performed
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate
}
struct ActionArgs {
// type of action that is being performed on the system
ActionType actionType;
// address of the account owner
address owner;
// address which we move assets from or to (depending on the action type)
address secondAddress;
// asset that is to be transfered
address asset;
// index of the vault that is to be modified (if any)
uint256 vaultId;
// amount of asset that is to be transfered
uint256 amount;
// each vault can hold multiple short / long / collateral assets
// but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// any other data that needs to be passed in for arbitrary function calls
bytes data;
}
struct RedeemArgs {
// address to which we pay out the oToken proceeds
address receiver;
// oToken that is to be redeemed
address otoken;
// amount of oTokens that is to be redeemed
uint256 amount;
}
function getPayout(address _otoken, uint256 _amount)
external
view
returns (uint256);
function operate(ActionArgs[] calldata _actions) external;
function getAccountVaultCounter(address owner)
external
view
returns (uint256);
function oracle() external view returns (address);
function getVault(address _owner, uint256 _vaultId)
external
view
returns (GammaTypes.Vault memory);
function getProceed(address _owner, uint256 _vaultId)
external
view
returns (uint256);
function isSettlementAllowed(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
interface IStrikeSelection {
function getStrikePrice(uint256 expiryTimestamp, bool isPut)
external
view
returns (uint256, uint256);
function delta() external view returns (uint256);
}
interface IOptionsPremiumPricer {
function getPremium(
uint256 strikePrice,
uint256 timeToExpiry,
bool isPut
) external view returns (uint256);
function getOptionDelta(
uint256 spotPrice,
uint256 strikePrice,
uint256 volatility,
uint256 expiryTimestamp
) external view returns (uint256 delta);
function getUnderlyingPrice() external view returns (uint256);
function priceOracle() external view returns (address);
function volatilityOracle() external view returns (address);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Vault} from "../libraries/Vault.sol";
interface IRibbonThetaVault {
function currentOption() external view returns (address);
function nextOption() external view returns (address);
function vaultParams() external view returns (Vault.VaultParams memory);
function vaultState() external view returns (Vault.VaultState memory);
function optionState() external view returns (Vault.OptionState memory);
function optionAuctionID() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Detailed is IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string calldata);
function name() external view returns (string calldata);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* This library supports ERC20s that have quirks in their behavior.
* One such ERC20 is USDT, which requires allowance to be 0 before calling approve.
* We plan to update this library with ERC20s that display such idiosyncratic behavior.
*/
library SupportsNonCompliantERC20 {
address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
function safeApproveNonCompliant(
IERC20 token,
address spender,
uint256 amount
) internal {
if (address(token) == USDT) {
SafeERC20.safeApprove(token, spender, 0);
}
SafeERC20.safeApprove(token, spender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
interface IWSTETH {
function getStETHByWstETH(uint256 _amount) external view returns (uint256);
function getWstETHByStETH(uint256 _amount) external view returns (uint256);
function stEthPerToken() external view returns (uint256);
function tokensPerStEth() external view returns (uint256);
function stETH() external view returns (address);
function wrap(uint256 _amount) external returns (uint256);
function unwrap(uint256 _amount) external returns (uint256);
function approve(address _recipient, uint256 _amount)
external
returns (bool);
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 transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function decimals() external view returns (uint256);
}
interface ISTETH {
function getBufferedEther(uint256 _amount) external view returns (uint256);
function getPooledEthByShares(uint256 _amount)
external
view
returns (uint256);
function getSharesByPooledEth(uint256 _amount)
external
view
returns (uint256);
function submit(address _referralAddress)
external
payable
returns (uint256);
function withdraw(uint256 _amount, bytes32 _pubkeyHash)
external
returns (uint256);
function approve(address _recipient, uint256 _amount)
external
returns (bool);
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 transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function decimals() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
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);
function decimals() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
interface ICRV {
function get_dy(
int128 _indexIn,
int128 _indexOut,
uint256 _amountIn
) external view returns (uint256);
// https://github.com/curvefi/curve-contract/blob/
// b0bbf77f8f93c9c5f4e415bce9cd71f0cdee960e/contracts/pools/steth/StableSwapSTETH.vy#L431
function exchange(
int128 _indexIn,
int128 _indexOut,
uint256 _amountIn,
uint256 _minAmountOut
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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);
}
|
Initializes the OptionVault contract with storage variables./
|
function baseInitialize(
address _owner,
address _keeper,
address _feeRecipient,
uint256 _managementFee,
uint256 _performanceFee,
string memory _tokenName,
string memory _tokenSymbol,
Vault.VaultParams calldata _vaultParams
) internal initializer {
VaultLifecycle.verifyInitializerParams(
_owner,
_keeper,
_feeRecipient,
_performanceFee,
_managementFee,
_tokenName,
_tokenSymbol,
_vaultParams
);
__ReentrancyGuard_init();
__ERC20_init(_tokenName, _tokenSymbol);
__Ownable_init();
transferOwnership(_owner);
keeper = _keeper;
feeRecipient = _feeRecipient;
performanceFee = _performanceFee;
managementFee = _managementFee.mul(Vault.FEE_MULTIPLIER).div(
WEEKS_PER_YEAR
);
vaultParams = _vaultParams;
uint256 assetBalance = totalBalance();
ShareMath.assertUint104(assetBalance);
vaultState.lastLockedAmount = uint104(assetBalance);
vaultState.round = 1;
}
| 5,809,038
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Arrays.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "./allowlist/AllowList.sol";
import "./traits/TokenTraits.sol";
import "./traits/ITraits.sol";
import "./IVampireGame.sol";
/// @title The Vampire Game NFT contract
///
/// Note: The original Wolf Game's contract was used as insipiration, and a
/// few parts of the contract were taken directly, in particular the trait selection
/// and rarity using Walker's Alias method, and using a separate `Traits` contract
/// for getting the tokenURI.
///
/// Some info about how this contract works:
///
/// ### Allow-list
///
/// Using a merkle-tree based allow-list that caps the amount of nfts a wallet
/// can mint. This increases a bit the gas cost to mint on **presale**, but we
/// compensate this by paying half of the minting price when we reveal the NFTs.
///
/// ### On-chain vs Off-chain
///
/// What is on-chain here?
/// - The generated traits
/// - The revealed traits metadata
/// - The traits img data
///
/// What is off-chain?
/// - The random number we get for batch reveals. We use a neutral, trusted third party
/// that is widely known in the community: Chainlink VRF.
/// - The non-revealed traits metadata (before your nft is revealed).
///
/// ### Minting and Revealing
///
/// 1. The user mints an NFT
/// 2. After a few mints, we request a random number to Chainlink VRF
/// 3. We use this random number to reveal the batch of NFTs that were minted
/// before we got the seed.
///
/// Why? We believe that as long as minting and revealing happens in the same
/// transaction, people will be able to cheat.
///
/// ### Traits
///
/// The traits are all stored on-chain in another contract "Traits" similar to Wolf Game.
///
/// ### Game Controllers
///
/// For us to be able to expand on this game, future "game controller" contracts will be
/// able to freely call `mint` functions, and `transferFrom`, the logic to safeguard
/// those functions will be delegated to those contracts.
///
/// Unfortunatelly, to be able to expand, and to not fall into traps like Wolf Game did,
/// we had to leave a few things open that requires our users to _trust us_ for now. We
/// hope to make this trustless some day.
///
contract VampireGame is
IVampireGame,
IVampireGameControls,
ERC721Enumerable,
AllowList,
Ownable,
ReentrancyGuard,
VRFConsumerBase
{
/// @notice used to find seeds for token ids
using Arrays for uint256[];
/// ==== Immutable
// Most of the immutable variables are initiated in the constructor
// to make it easier to test
/// @notice minting price in wei
uint256 public immutable MINT_PRICE;
/// @notice max amount of tokens that can be minted
uint256 public immutable MAX_SUPPLY;
/// @notice max mints per address
uint256 public immutable MAX_PER_ADDRESS;
/// @notice max mints per address in presale
uint256 public immutable MAX_PER_ADDRESS_PRESALE;
/// @notice price in $LINK to make VRF requests
uint256 public LINK_VRF_PRICE;
/// @notice number of tokens that can be bought with ether
uint256 public PAID_TOKENS;
/// @notice size of the batch that will be revealed by a single
uint256 public SEED_BATCH_SIZE;
/// @notice random numbers generated from Chainlink VRF.
uint256[] public seeds;
/// @notice array of tokenIds in ascending order that matches the length of the `seeds` array.
/// @dev using this to set which seeds are for which token, for example if let's say
/// the array has the values [100, 1000], then tokens from 0~99 will use seed[0] and
/// tokens from 100~999 will use seed[1].
uint256[] public seedTokenBoundaries;
/// @notice mapping from tokenId to tokenTraits
mapping(uint256 => TokenTraits) public tokenTraits;
/// @notice mapping from token hash to tokenId to prevent duplicated traits
mapping(uint256 => uint256) public existingCombinations;
/// @notice mapping from address to amount of tokens minted
mapping(address => uint8) public amountMintedByAddress;
/// @notice game controllers they can access special functions
mapping(address => bool) public controllers;
/// @notice chainlink key hash
bytes32 public immutable KEY_HASH;
/// @notice LINK token
IERC20 public immutable LINK_TOKEN;
/// @notice contract storing the traits data
ITraits public traits;
/// @notice address to withdraw the eth
address private immutable splitter;
/// @notice controls if mintWithEthPresale is paused
bool public mintWithEthPresalePaused = true;
/// @notice controls if mintWithEth is paused
bool public mintWithEthPaused = true;
/// @notice controls if mintFromController is paused
bool public mintFromControllerPaused = true;
/// @notice controls if token reveal is paused
bool public revealPaused = true;
/// @notice list of probabilities for each trait type 0 - 9 are associated with Sheep, 10 - 18 are associated with Wolves
/// @dev won't mutate but can't make it immutable
uint8[][18] public RARITIES;
/// @notice list of aliases for Walker's Alias algorithm 0 - 9 are associated with Sheep, 10 - 18 are associated with Wolves
/// @dev won't mutate but can't make it immutable
uint8[][18] public ALIASES;
/// === Constructor
/// @dev constructor, most of the immutable props can be set here so it's easier to test
/// @param _LINK_KEY_HASH Chainlink's VRF Key Hash
/// @param _LINK_ADDRESS Chainlink's LINK contract address
/// @param _LINK_VRF_COORDINATOR_ADDRESS Chainlink's coordinator contract address
/// @param _LINK_VRF_PRICE Price in $LINK to request a random number from Chainlink VRF
/// @param _MINT_PRICE price to mint one token in wei
/// @param _MAX_SUPPLY maximum amount of available tokens to mint
/// @param _MAX_PER_ADDRESS maximum amount of tokens one address can mint
/// @param _MAX_PER_ADDRESS_PRESALE maximum amount of tokens one address can mint
/// @param _SEED_BATCH_SIZE amount of tokens revealed by one seed
/// @param _PAID_TOKENS maxiumum amount of tokens that can be bought with eth
/// @param _splitter address to where the funds will go
constructor(
bytes32 _LINK_KEY_HASH,
address _LINK_ADDRESS,
address _LINK_VRF_COORDINATOR_ADDRESS,
uint256 _LINK_VRF_PRICE,
uint256 _MINT_PRICE,
uint256 _MAX_SUPPLY,
uint256 _MAX_PER_ADDRESS,
uint256 _MAX_PER_ADDRESS_PRESALE,
uint256 _SEED_BATCH_SIZE,
uint256 _PAID_TOKENS,
address _splitter
)
VRFConsumerBase(_LINK_VRF_COORDINATOR_ADDRESS, _LINK_ADDRESS)
ERC721("The Vampire Game", "VGAME")
{
LINK_TOKEN = IERC20(_LINK_ADDRESS);
KEY_HASH = _LINK_KEY_HASH;
LINK_VRF_PRICE = _LINK_VRF_PRICE;
MINT_PRICE = _MINT_PRICE;
MAX_SUPPLY = _MAX_SUPPLY;
MAX_PER_ADDRESS = _MAX_PER_ADDRESS;
MAX_PER_ADDRESS_PRESALE = _MAX_PER_ADDRESS_PRESALE;
SEED_BATCH_SIZE = _SEED_BATCH_SIZE;
PAID_TOKENS = _PAID_TOKENS;
splitter = _splitter;
// Humans
// Skin
RARITIES[0] = [50, 15, 15, 250, 255];
ALIASES[0] = [3, 4, 4, 0, 3];
// Face
RARITIES[1] = [
133,
189,
57,
255,
243,
133,
114,
135,
168,
38,
222,
57,
95,
57,
152,
114,
57,
133,
189
];
ALIASES[1] = [
1,
0,
3,
1,
3,
3,
3,
4,
7,
4,
8,
4,
8,
10,
10,
10,
18,
18,
14
];
// T-Shirt
RARITIES[2] = [
181,
224,
147,
236,
220,
168,
160,
84,
173,
224,
221,
254,
140,
252,
224,
250,
100,
207,
84,
252,
196,
140,
228,
140,
255,
183,
241,
140
];
ALIASES[2] = [
1,
0,
3,
1,
3,
3,
4,
11,
11,
4,
9,
10,
13,
11,
13,
14,
15,
15,
20,
17,
19,
24,
20,
24,
22,
26,
24,
26
];
// Pants
RARITIES[3] = [
126,
171,
225,
240,
227,
112,
255,
240,
217,
80,
64,
160,
228,
80,
64,
167
];
ALIASES[3] = [2, 0, 1, 2, 3, 3, 4, 6, 7, 4, 6, 7, 8, 8, 15, 12];
// Boots
RARITIES[4] = [150, 30, 60, 255, 150, 60];
ALIASES[4] = [0, 3, 3, 0, 3, 4];
// Accessory
RARITIES[5] = [
210,
135,
80,
245,
235,
110,
80,
100,
190,
100,
255,
160,
215,
80,
100,
185,
250,
240,
240,
100
];
ALIASES[5] = [
0,
0,
3,
0,
3,
4,
10,
12,
4,
16,
8,
16,
10,
17,
18,
12,
15,
16,
17,
18
];
// Hair
RARITIES[6] = [250, 115, 100, 40, 175, 255, 180, 100, 175, 185];
ALIASES[6] = [0, 0, 4, 6, 0, 4, 5, 9, 6, 8];
// Cape
RARITIES[7] = [255];
ALIASES[7] = [0];
// predatorIndex
RARITIES[8] = [255];
ALIASES[8] = [0];
// Vampires
// Skin
RARITIES[9] = [
234,
239,
234,
234,
255,
234,
244,
249,
130,
234,
234,
247,
234
];
ALIASES[9] = [0, 0, 1, 2, 3, 4, 5, 6, 12, 7, 9, 10, 11];
// Face
RARITIES[10] = [
45,
255,
165,
60,
195,
195,
45,
120,
75,
75,
105,
120,
255,
180,
150
];
ALIASES[10] = [1, 0, 1, 4, 2, 4, 5, 12, 12, 13, 13, 14, 5, 12, 13];
// Clothes
RARITIES[11] = [
147,
180,
246,
201,
210,
252,
219,
189,
195,
156,
177,
171,
165,
225,
135,
135,
186,
135,
150,
243,
135,
255,
231,
141,
183,
150,
135
];
ALIASES[11] = [
2,
2,
0,
2,
3,
4,
5,
6,
7,
3,
3,
4,
4,
8,
5,
6,
13,
13,
19,
16,
19,
19,
21,
21,
21,
21,
22
];
// Pants
RARITIES[12] = [255];
ALIASES[12] = [0];
// Boots
RARITIES[13] = [255];
ALIASES[13] = [0];
// Accessory
RARITIES[14] = [255];
ALIASES[14] = [0];
// Hair
RARITIES[15] = [255];
ALIASES[15] = [0];
// Cape
RARITIES[16] = [9, 9, 150, 90, 9, 210, 9, 9, 255];
ALIASES[16] = [5, 5, 0, 2, 8, 3, 8, 8, 5];
// predatorIndex
RARITIES[17] = [255, 8, 160, 73];
ALIASES[17] = [0, 0, 0, 2];
}
/// ==== Modifiers
modifier onlyControllers() {
require(controllers[_msgSender()], "ONLY_CONTROLLERS");
_;
}
/// ==== Minting
/// @notice mint an unrevealed token using eth
/// @param amount amount to mint
function mintWithETH(uint8 amount) external payable nonReentrant {
require(!mintWithEthPaused, "MINT_WITH_ETH_PAUSED");
uint8 addressMintedSoFar = amountMintedByAddress[_msgSender()];
require(
addressMintedSoFar + amount <= MAX_PER_ADDRESS,
"MAX_TOKEN_PER_WALLET"
);
require(totalSupply() + amount <= PAID_TOKENS, "NOT_ENOUGH_TOKENS");
require(amount > 0, "INVALID_AMOUNT");
require(amount * MINT_PRICE == msg.value, "WRONG_VALUE");
amountMintedByAddress[_msgSender()] = addressMintedSoFar + amount;
_mintMany(_msgSender(), amount);
}
/// @notice mint an unrevealed token using eth
/// @param amount amount to mint
function mintWithETHPresale(uint8 amount, bytes32[] calldata proof)
external
payable
nonReentrant
{
require(!mintWithEthPresalePaused, "PRESALE_PAUSED");
require(isAddressInAllowList(_msgSender(), proof), "NOT_IN_ALLOWLIST");
uint8 addressMintedSoFar = amountMintedByAddress[_msgSender()];
require(
addressMintedSoFar + amount <= MAX_PER_ADDRESS_PRESALE,
"MAX_TOKEN_PER_WALLET"
);
require(totalSupply() + amount <= PAID_TOKENS, "NOT_ENOUGH_TOKENS");
require(amount > 0, "INVALID_AMOUNT");
require(amount * MINT_PRICE == msg.value, "WRONG_VALUE");
amountMintedByAddress[_msgSender()] = addressMintedSoFar + amount;
_mintMany(_msgSender(), amount);
}
/// @dev mint any amount of tokens to an address
/// common logic to many functions, the function calling
/// this should do the guard checks
function _mintMany(address to, uint8 amount) private {
uint256 supply = totalSupply();
for (uint8 i = 0; i < amount; i++) {
uint256 tokenId = supply + i;
_safeMint(to, tokenId);
if ((tokenId + 1) % SEED_BATCH_SIZE == 0) {
requestRandomness(KEY_HASH, LINK_VRF_PRICE);
}
}
}
/// ==== Revealing
/// @notice reveal the metadata of multiple of tokenIds.
/// @dev admin check if this won't fail
function revealGenZeroTokens(uint256[] calldata tokenIds)
external
onlyOwner
{
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(canRevealToken(tokenId), "CANT_REVEAL");
// Find seed index in the seedTokenBoundaries array
uint256 seedIndex = seedTokenBoundaries.findUpperBound(tokenId);
uint256 seed = uint256(keccak256(abi.encode(seeds[seedIndex], tokenId)));
_revealToken(tokenId, seed);
}
}
/// @dev returns true if a token can be revealed.
/// Conditions for a token to be revealed:
/// - Was not revealed yet
/// - There is a seed that was added after the was already minted
function canRevealToken(uint256 tokenId)
private
view
returns (bool)
{
// Token already revealed
if (tokenTraits[tokenId].exists) {
return false;
}
// No seeds
if (seedTokenBoundaries.length == 0) {
return false;
}
// If the last element of the seedTokenBoundaries array is greater
// than the tokenId it means that there is a seed available for that
// token so the token can be revealed
return seedTokenBoundaries[seedTokenBoundaries.length - 1] > tokenId;
}
/// @dev reveal one token given an id and a seed
function _revealToken(uint256 tokenId, uint256 seed) private {
(
TokenTraits memory tt,
uint256 ttHash
) = _generateNonDuplicatedTokenTraits(tokenId, seed);
tokenTraits[tokenId] = tt;
existingCombinations[ttHash] = tokenId;
}
/// @dev recursive function to generate a TokenTraits without colliding
/// with other previously generated traits. It uses a seed from
/// Chainlink VRF and if there is a collision, it keeps re-hashing the
/// seed with the tokenId until it finds a unique set of traits.
/// @param tokenId the id of the token to generate the traits for
/// @param seed a value derived from a randomly generated value
/// @return tt a TokenTraits struct
function _generateNonDuplicatedTokenTraits(uint256 tokenId, uint256 seed)
private
returns (TokenTraits memory tt, uint256 ttHash)
{
// generate traits from seed
tt = selectTraits(seed);
// hash to check if the token is unique
ttHash = structToHash(tt);
if (existingCombinations[ttHash] == 0) {
tokenTraits[tokenId] = tt;
existingCombinations[ttHash] = tokenId;
return (tt, ttHash);
}
// If it's here, then the generated traits collided with another
// set of traits. Hopefully this won't happen.
// generates a new seed combining the current seed and the tokenId
uint256 newSeed = uint256(keccak256(abi.encode(seed, tokenId)));
// recursive call D:
return _generateNonDuplicatedTokenTraits(tokenId, newSeed);
}
/// @dev select traits based on the seed value.
/// @param seed a uint256 to derive traits from
/// @return tt the TokenTraits
function selectTraits(uint256 seed)
private
view
returns (TokenTraits memory tt)
{
tt.exists = true;
tt.isVampire = (seed & 0xFFFF) % 10 == 0;
uint8 shift = tt.isVampire ? 9 : 0;
seed >>= 16;
tt.skin = selectTrait(uint16(seed & 0xFFFF), 0 + shift);
seed >>= 16;
tt.face = selectTrait(uint16(seed & 0xFFFF), 1 + shift);
seed >>= 16;
tt.clothes = selectTrait(uint16(seed & 0xFFFF), 2 + shift);
seed >>= 16;
tt.pants = selectTrait(uint16(seed & 0xFFFF), 3 + shift);
seed >>= 16;
tt.boots = selectTrait(uint16(seed & 0xFFFF), 4 + shift);
seed >>= 16;
tt.accessory = selectTrait(uint16(seed & 0xFFFF), 5 + shift);
seed >>= 16;
tt.hair = selectTrait(uint16(seed & 0xFFFF), 6 + shift);
seed >>= 16;
tt.cape = selectTrait(uint16(seed & 0xFFFF), 7 + shift);
seed >>= 16;
tt.predatorIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift);
}
/// @dev select a trait from the traitType
/// @param seed a uint256 number to get the trait value from
/// @param traitType the trait type
function selectTrait(uint16 seed, uint8 traitType)
private
view
returns (uint8)
{
uint8 trait = uint8(seed) % uint8(RARITIES[traitType].length);
if (seed >> 8 < RARITIES[traitType][trait]) return trait;
return ALIASES[traitType][trait];
}
/// @dev hash a TokenTraits struct
/// @param tt the TokenTraits struct
/// @return the uint256 hash
function structToHash(TokenTraits memory tt)
private
pure
returns (uint256)
{
return
uint256(
bytes32(
abi.encodePacked(
tt.isVampire,
tt.skin,
tt.face,
tt.clothes,
tt.pants,
tt.boots,
tt.accessory,
tt.hair,
tt.cape,
tt.predatorIndex
)
)
);
}
/// ==== State Control
/// @notice set the new merkle tree root for allow-list
function setMerkleTreeRoot(bytes32 newMerkleTreeRoot) external onlyOwner {
_setMerkleTreeRoot(newMerkleTreeRoot);
}
/// @notice set the max amount of gen 0 tokens
function setPaidTokens(uint256 _PAID_TOKENS) external onlyOwner {
require(PAID_TOKENS != _PAID_TOKENS, "NO_CHANGES");
PAID_TOKENS = _PAID_TOKENS;
}
/// @notice pause/unpause mintWithEthPresale function
function setMintWithEthPresalePaused(bool paused) external onlyOwner {
require(paused != mintWithEthPresalePaused, "NO_CHANGES");
mintWithEthPresalePaused = paused;
}
/// @notice pause/unpause mintWithEth function
function setMintWithEthPaused(bool paused) external onlyOwner {
require(paused != mintWithEthPaused, "NO_CHANGES");
mintWithEthPaused = paused;
}
/// @notice pause/unpause mintFromController function
function setMintFromControllerPaused(bool paused) external onlyOwner {
require(paused != mintFromControllerPaused, "NO_CHANGES");
mintFromControllerPaused = paused;
}
/// @notice pause/unpause token reveal functions
function setRevealPaused(bool paused) external onlyOwner {
require(paused != revealPaused, "NO_CHANGES");
revealPaused = paused;
}
/// @notice set the contract for the traits rendering
/// @param _traits the contract address
function setTraits(address _traits) external onlyOwner {
traits = ITraits(_traits);
}
/// @notice add controller authority to an address
/// @param _controller address to the game controller
function addController(address _controller) external onlyOwner {
controllers[_controller] = true;
}
/// @notice remove controller authority from an address
/// @param _controller address to the game controller
function removeController(address _controller) external onlyOwner {
controllers[_controller] = false;
}
/// ==== Withdraw
/// @notice withdraw the ether from the contract
function withdraw() external onlyOwner {
uint256 contractBalance = address(this).balance;
// solhint-disable-next-line avoid-low-level-calls
(bool sent, ) = splitter.call{value: contractBalance}("");
require(sent, "FAILED_TO_WITHDRAW");
}
/// @notice withdraw ERC20 tokens from the contract
/// people always randomly transfer ERC20 tokens to the
/// @param erc20TokenAddress the ERC20 token address
/// @param recipient who will get the tokens
/// @param amount how many tokens
function withdrawERC20(
address erc20TokenAddress,
address recipient,
uint256 amount
) external onlyOwner {
IERC20 erc20Contract = IERC20(erc20TokenAddress);
bool sent = erc20Contract.transfer(recipient, amount);
require(sent, "ERC20_WITHDRAW_FAILED");
}
/// @notice reserve some tokens for the team. Can only reserve gen 0 tokens
/// we also need token 0 to so ssetup market places befor mint
function reserve(address to, uint256 amount) external onlyOwner {
require(totalSupply() + amount < PAID_TOKENS);
uint256 supply = totalSupply();
for (uint8 i = 0; i < amount; i++) {
uint256 tokenId = supply + i;
_safeMint(to, tokenId);
}
}
/// @notice delete all entries in the seeds and seedTokenBoundaries arrays
/// just in case something weird happens
function cleanSeeds() external onlyOwner {
require(seeds.length > 0, "NO_SEEDS");
for (uint256 i = 0; i < seeds.length; i++) {
delete seeds[i];
delete seedTokenBoundaries[i];
}
}
/// @notice set the price for requesting a random number to Chainlink VRF
/// Note that the base link token has 18 zeroes.
function setVRFPrice(uint256 _LINK_VRF_PRICE) external onlyOwner {
require(_LINK_VRF_PRICE != LINK_VRF_PRICE, "NO_CHANGES");
LINK_VRF_PRICE = _LINK_VRF_PRICE;
}
/// @notice owner request reveal seed, just in case something goes wrong
function requestRevealSeed() external onlyOwner {
requestRandomness(KEY_HASH, LINK_VRF_PRICE);
}
/// ==== IVampireGameControls Overrides
/// @notice see {IVampireGameControls.mintFromController(receiver, amount)}
function mintFromController(address receiver, uint256 amount)
external
override
{
require(!mintFromControllerPaused, "MINT_FROM_CONTROLLER_PAUSED");
require(controllers[_msgSender()], "NOT_AUTHORIZED");
require(totalSupply() + amount <= MAX_SUPPLY, "NOT_ENOUGH_TOKENS");
for (uint256 i = 0; i < amount; i++) {
uint256 tokenId = totalSupply();
_safeMint(receiver, tokenId);
}
}
/// @notice for a game controller to reveal the metadata of multiple token ids
function controllerRevealTokens(
uint256[] calldata tokenIds,
uint256[] calldata _seeds
) external override onlyControllers {
require(!revealPaused, "REVEAL_PAUSED");
require(
tokenIds.length == seeds.length,
"INPUTS_SHOULD_HAVE_SAME_LENGTH"
);
for (uint256 i = 0; i < tokenIds.length; i++) {
_revealToken(tokenIds[i], _seeds[i]);
}
}
/// ==== IVampireGame Overrides
/// @notice see {IVampireGame.getGenZeroSupply()}
function getGenZeroSupply() external view override returns (uint256) {
return PAID_TOKENS;
}
/// @notice see {IVampireGame.getMaxSupply()}
function getMaxSupply() external view override returns (uint256) {
return MAX_SUPPLY;
}
/// @notice see {IVampireGame.getTokenTraits(tokenId)}
function getTokenTraits(uint256 tokenId)
external
view
override
returns (TokenTraits memory)
{
return tokenTraits[tokenId];
}
/// @notice see {IVampireGame.isTokenRevealed(tokenId)}
function isTokenRevealed(uint256 tokenId)
public
view
override
returns (bool)
{
return tokenTraits[tokenId].exists;
}
/// ==== ERC721 Overrides
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
// Hardcode approval of game controllers
if (!controllers[_msgSender()])
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
return traits.tokenURI(tokenId);
}
/// ==== Chainlink VRF Overrides
/// @notice Fulfills randomness from Chainlink VRF
/// @param requestId returned id of VRF request
/// @param randomness random number from VRF
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
uint256 minted = totalSupply();
// the amount of tokens minted has to be greater than the latest recorded
// seed boundary, otherwise it means that there is already a seed for tokens
// up to the current amount of tokens
if (
seedTokenBoundaries.length == 0 ||
minted > seedTokenBoundaries[seedTokenBoundaries.length - 1]
) {
seeds.push(randomness);
seedTokenBoundaries.push(minted);
}
// Otherwise we discard the number. I'm hoping this doesn't happen though :D
// More info: I'm hoping that this won't happen bevause we'll only ask for seeds
// on spaced enough intervals, but not guaranteeing it in the contract
}
}
// 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 "../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 "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @title AllowList
/// @notice Adds simple merkle-tree based allow-list functionality to a contract.
contract AllowList {
/// @notice stores the Merkle Tree root.
bytes32 internal _merkleTreeRoot;
/// @notice Sets the new merkle tree root
/// @param newMerkleTreeRoot the new root of the merkle tree
function _setMerkleTreeRoot(bytes32 newMerkleTreeRoot) internal {
require(_merkleTreeRoot != newMerkleTreeRoot, "NO_CHANGES");
_merkleTreeRoot = newMerkleTreeRoot;
}
/// @notice test if an address is part of the merkle tree
/// @param _address the address to verify
/// @param proof array of other hashes for proof calculation
/// @return true if the address is part of the merkle tree
function isAddressInAllowList(address _address, bytes32[] calldata proof)
public
view
returns (bool)
{
bytes32 leaf = keccak256(abi.encodePacked(_address));
return MerkleProof.verify(proof, _merkleTreeRoot, leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
struct TokenTraits {
/// @dev every initialised token should have this as true
/// this is just used to check agains a non-initialized struct
bool exists;
bool isVampire;
// Shared Traits
uint8 skin;
uint8 face;
uint8 clothes;
// Human-only Traits
uint8 pants;
uint8 boots;
uint8 accessory;
uint8 hair;
// Vampire-only Traits
uint8 cape;
uint8 predatorIndex;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./traits/TokenTraits.sol";
/// @notice Interface to interact with the VampireGame contract
interface IVampireGame {
/// @notice get the total supply of gen-0
function getGenZeroSupply() external view returns (uint256);
/// @notice get the total supply of tokens
function getMaxSupply() external view returns (uint256);
/// @notice get the TokenTraits for a given tokenId
function getTokenTraits(uint256 tokenId) external view returns (TokenTraits memory);
/// @notice returns true if a token is aleady revealed
function isTokenRevealed(uint256 tokenId) external view returns (bool);
}
/// @notice Interface to control parts of the VampireGame ERC 721
interface IVampireGameControls {
/// @notice mint any amount of nft to any address
/// Requirements:
/// - message sender should be an allowed address (game contract)
/// - amount + totalSupply() has to be smaller than MAX_SUPPLY
function mintFromController(address receiver, uint256 amount) external;
/// @notice reveal a list of tokens using specific seeds for each
function controllerRevealTokens(uint256[] calldata tokenIds, uint256[] calldata _seeds) external;
}
// 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.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 "../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 "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
|
see {IVampireGame.getTokenTraits(tokenId)}
|
function getTokenTraits(uint256 tokenId)
external
view
override
returns (TokenTraits memory)
{
return tokenTraits[tokenId];
}
| 2,475,685
|
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol";
import {IPremiaOptionNFTDisplay} from "../interface/IPremiaOptionNFTDisplay.sol";
import {IPoolView, IERC1155Metadata} from "./IPoolView.sol";
import {PoolInternal} from "./PoolInternal.sol";
import {PoolStorage} from "./PoolStorage.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
contract PoolView is IPoolView, PoolInternal {
using EnumerableSet for EnumerableSet.UintSet;
using PoolStorage for PoolStorage.Layout;
address internal immutable NFT_DISPLAY_ADDRESS;
constructor(
address nftDisplay,
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64
)
PoolInternal(
ivolOracle,
weth,
premiaMining,
feeReceiver,
feeDiscountAddress,
fee64x64
)
{
NFT_DISPLAY_ADDRESS = nftDisplay;
}
/**
* @inheritdoc IPoolView
*/
function getFeeReceiverAddress() external view override returns (address) {
return FEE_RECEIVER_ADDRESS;
}
/**
* @inheritdoc IPoolView
*/
function getPoolSettings()
external
view
override
returns (PoolStorage.PoolSettings memory)
{
PoolStorage.Layout storage l = PoolStorage.layout();
return
PoolStorage.PoolSettings(
l.underlying,
l.base,
l.underlyingOracle,
l.baseOracle
);
}
/**
* @inheritdoc IPoolView
*/
function getTokenIds() external view override returns (uint256[] memory) {
PoolStorage.Layout storage l = PoolStorage.layout();
uint256 length = l.tokenIds.length();
uint256[] memory result = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
result[i] = l.tokenIds.at(i);
}
return result;
}
/**
* @inheritdoc IPoolView
*/
function getCLevel64x64(bool isCall)
external
view
override
returns (int128 cLevel64x64)
{
(cLevel64x64, ) = PoolStorage.layout().getRealPoolState(isCall);
}
/**
* @inheritdoc IPoolView
*/
function getSteepness64x64(bool isCallPool)
external
view
override
returns (int128)
{
if (isCallPool) {
return PoolStorage.layout().steepnessUnderlying64x64;
} else {
return PoolStorage.layout().steepnessBase64x64;
}
}
/**
* @inheritdoc IPoolView
*/
function getPrice(uint256 timestamp)
external
view
override
returns (int128)
{
return PoolStorage.layout().getPriceUpdate(timestamp);
}
/**
* @inheritdoc IPoolView
*/
function getParametersForTokenId(uint256 tokenId)
external
pure
override
returns (
PoolStorage.TokenType,
uint64,
int128
)
{
return PoolStorage.parseTokenId(tokenId);
}
/**
* @inheritdoc IPoolView
*/
function getMinimumAmounts()
external
view
override
returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount)
{
PoolStorage.Layout storage l = PoolStorage.layout();
return (_getMinimumAmount(l, true), _getMinimumAmount(l, false));
}
/**
* @inheritdoc IPoolView
*/
function getCapAmounts()
external
view
override
returns (uint256 callTokenCapAmount, uint256 putTokenCapAmount)
{
PoolStorage.Layout storage l = PoolStorage.layout();
return (_getPoolCapAmount(l, true), _getPoolCapAmount(l, false));
}
/**
* @inheritdoc IPoolView
*/
function getUserTVL(address user)
external
view
override
returns (uint256 underlyingTVL, uint256 baseTVL)
{
PoolStorage.Layout storage l = PoolStorage.layout();
return (l.userTVL[user][true], l.userTVL[user][false]);
}
/**
* @inheritdoc IPoolView
*/
function getTotalTVL()
external
view
override
returns (uint256 underlyingTVL, uint256 baseTVL)
{
PoolStorage.Layout storage l = PoolStorage.layout();
return (l.totalTVL[true], l.totalTVL[false]);
}
/**
* @inheritdoc IPoolView
*/
function getLiquidityQueuePosition(address account, bool isCallPool)
external
view
override
returns (uint256 liquidityBeforePosition, uint256 positionSize)
{
PoolStorage.Layout storage l = PoolStorage.layout();
uint256 tokenId = _getFreeLiquidityTokenId(isCallPool);
if (!l.isInQueue(account, isCallPool)) {
liquidityBeforePosition = _totalSupply(tokenId);
} else {
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
address depositor = asc[address(0)];
while (depositor != account) {
liquidityBeforePosition += _balanceOf(depositor, tokenId);
depositor = asc[depositor];
}
positionSize = _balanceOf(depositor, tokenId);
}
}
/**
* @inheritdoc IPoolView
*/
function getPremiaMining() external view override returns (address) {
return PREMIA_MINING_ADDRESS;
}
/**
* @inheritdoc IPoolView
*/
function getDivestmentTimestamps(address account)
external
view
override
returns (
uint256 callDivestmentTimestamp,
uint256 putDivestmentTimestamp
)
{
PoolStorage.Layout storage l = PoolStorage.layout();
callDivestmentTimestamp = l.divestmentTimestamps[account][true];
putDivestmentTimestamp = l.divestmentTimestamps[account][false];
}
/**
* @inheritdoc IERC1155Metadata
* @dev SVG generated via external PremiaOptionNFTDisplay contract
*/
function uri(uint256 tokenId)
external
view
override
returns (string memory)
{
return
IPremiaOptionNFTDisplay(NFT_DISPLAY_ADDRESS).tokenURI(
address(this),
tokenId
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Set implementation with enumeration functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license)
*/
library EnumerableSet {
struct Set {
bytes32[] _values;
// 1-indexed to allow 0 to signify nonexistence
mapping(bytes32 => uint256) _indexes;
}
struct Bytes32Set {
Set _inner;
}
struct AddressSet {
Set _inner;
}
struct UintSet {
Set _inner;
}
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
function indexOf(Bytes32Set storage set, bytes32 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, value);
}
function indexOf(AddressSet storage set, address value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(uint256(uint160(value))));
}
function indexOf(UintSet storage set, uint256 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(value));
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
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];
}
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
function _indexOf(Set storage set, bytes32 value)
private
view
returns (uint256)
{
unchecked {
return set._indexes[value] - 1;
}
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 index = valueIndex - 1;
bytes32 last = set._values[set._values.length - 1];
// move last value to now-vacant index
set._values[index] = last;
set._indexes[last] = index + 1;
// clear last index
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPremiaOptionNFTDisplay {
function tokenURI(address _pool, uint256 _tokenId)
external
view
returns (string memory);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {IERC1155Metadata} from "@solidstate/contracts/token/ERC1155/metadata/IERC1155Metadata.sol";
import {PoolStorage} from "./PoolStorage.sol";
/**
* @notice Pool view function interface
*/
interface IPoolView is IERC1155Metadata {
/**
* @notice get fee receiver address
* @dev called by PremiaMakerKeeper
* @return fee receiver address
*/
function getFeeReceiverAddress() external view returns (address);
/**
* @notice get fundamental pool attributes
* @return structured PoolSettings
*/
function getPoolSettings()
external
view
returns (PoolStorage.PoolSettings memory);
/**
* @notice get the list of all token ids in circulation
* @return list of token ids
*/
function getTokenIds() external view returns (uint256[] memory);
/**
* @notice get current C-Level, accounting for unrealized decay and pending deposits
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function getCLevel64x64(bool isCall) external view returns (int128);
/**
* @notice get steepness coefficient
* @param isCall whether query is for call or put pool
* @return 64x64 fixed point representation of C steepness of Pool
*/
function getSteepness64x64(bool isCall) external view returns (int128);
/**
* @notice get oracle price at timestamp
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPrice(uint256 timestamp) external view returns (int128);
/**
* @notice get parameters for token id
* @param tokenId token id to query
* @return token type enum
* @return maturity
* @return 64x64 fixed point representation of strike price
*/
function getParametersForTokenId(uint256 tokenId)
external
pure
returns (
PoolStorage.TokenType,
uint64,
int128
);
/**
* @notice get minimum purchase and interval amounts
* @return minCallTokenAmount minimum call pool amount
* @return minPutTokenAmount minimum put pool amount
*/
function getMinimumAmounts()
external
view
returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount);
/**
* @notice get deposit cap amounts
* @return callTokenCapAmount call pool deposit cap
* @return putTokenCapAmount put pool deposit cap
*/
function getCapAmounts()
external
view
returns (uint256 callTokenCapAmount, uint256 putTokenCapAmount);
/**
* @notice get TVL (total value locked) for given address
* @param account address whose TVL to query
* @return underlyingTVL user total value locked in call pool (in underlying token amount)
* @return baseTVL user total value locked in put pool (in base token amount)
*/
function getUserTVL(address account)
external
view
returns (uint256 underlyingTVL, uint256 baseTVL);
/**
* @notice get TVL (total value locked) of entire Pool
* @return underlyingTVL total value locked in call pool (in underlying token amount)
* @return baseTVL total value locked in put pool (in base token amount)
*/
function getTotalTVL()
external
view
returns (uint256 underlyingTVL, uint256 baseTVL);
/**
* @notice get position in the liquidity queue of the Pool
* @param account account address whose liquidity position to query
* @param isCallPool whether query is for call or put pool
* @return liquidityBeforePosition total available liquidity before account's liquidity queue
* @return positionSize size of the account's liquidity queue position
*/
function getLiquidityQueuePosition(address account, bool isCallPool)
external
view
returns (uint256 liquidityBeforePosition, uint256 positionSize);
/**
* @notice get the address of PremiaMining contract
* @return address of PremiaMining contract
*/
function getPremiaMining() external view returns (address);
/**
* @notice get the gradual divestment timestamps of a user
* @param account address whose divestment timestamps to query
* @return callDivestmentTimestamp gradual divestment timestamp of the user for the call pool
* @return putDivestmentTimestamp gradual divestment timestamp of the user for the put pool
*/
function getDivestmentTimestamps(address account)
external
view
returns (
uint256 callDivestmentTimestamp,
uint256 putDivestmentTimestamp
);
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {IERC173} from "@solidstate/contracts/access/IERC173.sol";
import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol";
import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol";
import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol";
import {IWETH} from "@solidstate/contracts/utils/IWETH.sol";
import {PoolStorage} from "./PoolStorage.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol";
import {OptionMath} from "../libraries/OptionMath.sol";
import {IFeeDiscount} from "../staking/IFeeDiscount.sol";
import {IPoolEvents} from "./IPoolEvents.sol";
import {IPremiaMining} from "../mining/IPremiaMining.sol";
import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol";
/**
* @title Premia option pool
* @dev deployed standalone and referenced by PoolProxy
*/
contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal {
using ABDKMath64x64 for int128;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using PoolStorage for PoolStorage.Layout;
address internal immutable WETH_ADDRESS;
address internal immutable PREMIA_MINING_ADDRESS;
address internal immutable FEE_RECEIVER_ADDRESS;
address internal immutable FEE_DISCOUNT_ADDRESS;
address internal immutable IVOL_ORACLE_ADDRESS;
int128 internal immutable FEE_64x64;
uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID;
uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID;
uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID;
uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID;
uint256 internal constant INVERSE_BASIS_POINT = 1e4;
uint256 internal constant BATCHING_PERIOD = 260;
// Minimum APY for capital locked up to underwrite options.
// The quote will return a minimum price corresponding to this APY
int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3
constructor(
address ivolOracle,
address weth,
address premiaMining,
address feeReceiver,
address feeDiscountAddress,
int128 fee64x64
) {
IVOL_ORACLE_ADDRESS = ivolOracle;
WETH_ADDRESS = weth;
PREMIA_MINING_ADDRESS = premiaMining;
FEE_RECEIVER_ADDRESS = feeReceiver;
// PremiaFeeDiscount contract address
FEE_DISCOUNT_ADDRESS = feeDiscountAddress;
FEE_64x64 = fee64x64;
UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.UNDERLYING_FREE_LIQ,
0,
0
);
BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.BASE_FREE_LIQ,
0,
0
);
UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ,
0,
0
);
BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId(
PoolStorage.TokenType.BASE_RESERVED_LIQ,
0,
0
);
}
modifier onlyProtocolOwner() {
require(
msg.sender == IERC173(OwnableStorage.layout().owner).owner(),
"Not protocol owner"
);
_;
}
function _getFeeDiscount(address feePayer)
internal
view
returns (uint256 discount)
{
if (FEE_DISCOUNT_ADDRESS != address(0)) {
discount = IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer);
}
}
function _getFeeWithDiscount(address feePayer, uint256 fee)
internal
view
returns (uint256)
{
uint256 discount = _getFeeDiscount(feePayer);
return fee - ((fee * discount) / INVERSE_BASIS_POINT);
}
function _withdrawFees(bool isCall) internal returns (uint256 amount) {
uint256 tokenId = _getReservedLiquidityTokenId(isCall);
amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId);
if (amount > 0) {
_burn(FEE_RECEIVER_ADDRESS, tokenId, amount);
emit FeeWithdrawal(isCall, amount);
}
}
/**
* @notice calculate price of option contract
* @param args structured quote arguments
* @return result quote result
*/
function _quote(PoolStorage.QuoteArgsInternal memory args)
internal
view
returns (PoolStorage.QuoteResultInternal memory result)
{
require(
args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0,
"invalid args"
);
PoolStorage.Layout storage l = PoolStorage.layout();
int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals(
args.contractSize,
l.underlyingDecimals
);
(int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l
.getRealPoolState(args.isCall);
require(oldLiquidity64x64 > 0, "no liq");
int128 timeToMaturity64x64 = ABDKMath64x64.divu(
args.maturity - block.timestamp,
365 days
);
int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle(
IVOL_ORACLE_ADDRESS
).getAnnualizedVolatility64x64(
l.base,
l.underlying,
args.spot64x64,
args.strike64x64,
timeToMaturity64x64,
args.isCall
);
require(annualizedVolatility64x64 > 0, "vol = 0");
int128 collateral64x64 = args.isCall
? contractSize64x64
: contractSize64x64.mul(args.strike64x64);
(
int128 price64x64,
int128 cLevel64x64,
int128 slippageCoefficient64x64
) = OptionMath.quotePrice(
OptionMath.QuoteArgs(
annualizedVolatility64x64.mul(annualizedVolatility64x64),
args.strike64x64,
args.spot64x64,
timeToMaturity64x64,
adjustedCLevel64x64,
oldLiquidity64x64,
oldLiquidity64x64.sub(collateral64x64),
0x10000000000000000, // 64x64 fixed point representation of 1
MIN_APY_64x64,
args.isCall
)
);
result.baseCost64x64 = args.isCall
? price64x64.mul(contractSize64x64).div(args.spot64x64)
: price64x64.mul(contractSize64x64);
result.feeCost64x64 = result.baseCost64x64.mul(FEE_64x64);
result.cLevel64x64 = cLevel64x64;
result.slippageCoefficient64x64 = slippageCoefficient64x64;
int128 discount = ABDKMath64x64.divu(
_getFeeDiscount(args.feePayer),
INVERSE_BASIS_POINT
);
result.feeCost64x64 -= result.feeCost64x64.mul(discount);
}
/**
* @notice burn corresponding long and short option tokens
* @param account holder of tokens to annihilate
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize quantity of option contract tokens to annihilate
*/
function _annihilate(
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize
) internal {
uint256 longTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, true),
maturity,
strike64x64
);
uint256 shortTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
);
_burn(account, longTokenId, contractSize);
_burn(account, shortTokenId, contractSize);
emit Annihilate(shortTokenId, contractSize);
}
/**
* @notice purchase option
* @param l storage layout struct
* @param account recipient of purchased option
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize size of option contract
* @param newPrice64x64 64x64 fixed point representation of current spot price
* @return baseCost quantity of tokens required to purchase long position
* @return feeCost quantity of tokens required to pay fees
*/
function _purchase(
PoolStorage.Layout storage l,
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize,
int128 newPrice64x64
) internal returns (uint256 baseCost, uint256 feeCost) {
require(maturity > block.timestamp, "expired");
require(contractSize >= l.underlyingMinimum, "too small");
{
uint256 size = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(
strike64x64.mulu(contractSize)
);
require(
size <=
ERC1155EnumerableStorage.layout().totalSupply[
_getFreeLiquidityTokenId(isCall)
] -
l.nextDeposits[isCall].totalPendingDeposits,
"insuf liq"
);
}
PoolStorage.QuoteResultInternal memory quote = _quote(
PoolStorage.QuoteArgsInternal(
account,
maturity,
strike64x64,
newPrice64x64,
contractSize,
isCall
)
);
baseCost = ABDKMath64x64Token.toDecimals(
quote.baseCost64x64,
l.getTokenDecimals(isCall)
);
feeCost = ABDKMath64x64Token.toDecimals(
quote.feeCost64x64,
l.getTokenDecimals(isCall)
);
uint256 longTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, true),
maturity,
strike64x64
);
uint256 shortTokenId = PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
);
// mint long option token for buyer
_mint(account, longTokenId, contractSize);
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
// burn free liquidity tokens from other underwriters
_mintShortTokenLoop(
l,
account,
contractSize,
baseCost,
shortTokenId,
isCall
);
int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
_setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall);
// mint reserved liquidity tokens for fee receiver
_mint(
FEE_RECEIVER_ADDRESS,
_getReservedLiquidityTokenId(isCall),
feeCost
);
emit Purchase(
account,
longTokenId,
contractSize,
baseCost,
feeCost,
newPrice64x64
);
}
/**
* @notice reassign short position to new underwriter
* @param l storage layout struct
* @param account holder of positions to be reassigned
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @param isCall true for call, false for put
* @param contractSize quantity of option contract tokens to reassign
* @param newPrice64x64 64x64 fixed point representation of current spot price
* @return baseCost quantity of tokens required to reassign short position
* @return feeCost quantity of tokens required to pay fees
* @return amountOut quantity of liquidity freed
*/
function _reassign(
PoolStorage.Layout storage l,
address account,
uint64 maturity,
int128 strike64x64,
bool isCall,
uint256 contractSize,
int128 newPrice64x64
)
internal
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
)
{
(baseCost, feeCost) = _purchase(
l,
account,
maturity,
strike64x64,
isCall,
contractSize,
newPrice64x64
);
_annihilate(account, maturity, strike64x64, isCall, contractSize);
uint256 annihilateAmount = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize));
amountOut = annihilateAmount - baseCost - feeCost;
}
/**
* @notice exercise option on behalf of holder
* @dev used for processing of expired options if passed holder is zero address
* @param holder owner of long option tokens to exercise
* @param longTokenId long option token id
* @param contractSize quantity of tokens to exercise
*/
function _exercise(
address holder,
uint256 longTokenId,
uint256 contractSize
) internal {
uint64 maturity;
int128 strike64x64;
bool isCall;
bool onlyExpired = holder == address(0);
{
PoolStorage.TokenType tokenType;
(tokenType, maturity, strike64x64) = PoolStorage.parseTokenId(
longTokenId
);
require(
tokenType == PoolStorage.TokenType.LONG_CALL ||
tokenType == PoolStorage.TokenType.LONG_PUT,
"invalid type"
);
require(!onlyExpired || maturity < block.timestamp, "not expired");
isCall = tokenType == PoolStorage.TokenType.LONG_CALL;
}
PoolStorage.Layout storage l = PoolStorage.layout();
int128 spot64x64 = _update(l);
if (maturity < block.timestamp) {
spot64x64 = l.getPriceUpdateAfter(maturity);
}
require(
onlyExpired ||
(
isCall
? (spot64x64 > strike64x64)
: (spot64x64 < strike64x64)
),
"not ITM"
);
uint256 exerciseValue;
// option has a non-zero exercise value
if (isCall) {
if (spot64x64 > strike64x64) {
exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu(
contractSize
);
}
} else {
if (spot64x64 < strike64x64) {
exerciseValue = l.fromUnderlyingToBaseDecimals(
strike64x64.sub(spot64x64).mulu(contractSize)
);
}
}
uint256 totalFee;
if (onlyExpired) {
totalFee += _burnLongTokenLoop(
contractSize,
exerciseValue,
longTokenId,
isCall
);
} else {
// burn long option tokens from sender
_burn(holder, longTokenId, contractSize);
uint256 fee;
if (exerciseValue > 0) {
fee = _getFeeWithDiscount(
holder,
FEE_64x64.mulu(exerciseValue)
);
totalFee += fee;
_pushTo(holder, _getPoolToken(isCall), exerciseValue - fee);
}
emit Exercise(
holder,
longTokenId,
contractSize,
exerciseValue,
fee
);
}
totalFee += _burnShortTokenLoop(
contractSize,
exerciseValue,
PoolStorage.formatTokenId(
_getTokenType(isCall, false),
maturity,
strike64x64
),
isCall
);
_mint(
FEE_RECEIVER_ADDRESS,
_getReservedLiquidityTokenId(isCall),
totalFee
);
}
function _mintShortTokenLoop(
PoolStorage.Layout storage l,
address buyer,
uint256 contractSize,
uint256 premium,
uint256 shortTokenId,
bool isCall
) internal {
uint256 freeLiqTokenId = _getFreeLiquidityTokenId(isCall);
(, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId);
uint256 toPay = isCall
? contractSize
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize));
while (toPay > 0) {
address underwriter = l.liquidityQueueAscending[isCall][address(0)];
uint256 balance = _balanceOf(underwriter, freeLiqTokenId);
// If dust left, we remove underwriter and skip to next
if (balance < _getMinimumAmount(l, isCall)) {
l.removeUnderwriter(underwriter, isCall);
continue;
}
if (!l.getReinvestmentStatus(underwriter, isCall)) {
_burn(underwriter, freeLiqTokenId, balance);
_mint(
underwriter,
_getReservedLiquidityTokenId(isCall),
balance
);
_subUserTVL(l, underwriter, isCall, balance);
continue;
}
// amount of liquidity provided by underwriter, accounting for reinvested premium
uint256 intervalContractSize = ((balance -
l.pendingDeposits[underwriter][l.nextDeposits[isCall].eta][
isCall
]) * (toPay + premium)) / toPay;
if (intervalContractSize == 0) continue;
if (intervalContractSize > toPay) intervalContractSize = toPay;
// amount of premium paid to underwriter
uint256 intervalPremium = (premium * intervalContractSize) / toPay;
premium -= intervalPremium;
toPay -= intervalContractSize;
_addUserTVL(l, underwriter, isCall, intervalPremium);
// burn free liquidity tokens from underwriter
_burn(
underwriter,
freeLiqTokenId,
intervalContractSize - intervalPremium
);
if (isCall == false) {
// For PUT, conversion to contract amount is done here (Prior to this line, it is token amount)
intervalContractSize = l.fromBaseToUnderlyingDecimals(
strike64x64.inv().mulu(intervalContractSize)
);
}
// mint short option tokens for underwriter
// toPay == 0 ? contractSize : intervalContractSize : To prevent minting less than amount,
// because of rounding (Can happen for put, because of fixed point precision)
_mint(
underwriter,
shortTokenId,
toPay == 0 ? contractSize : intervalContractSize
);
emit Underwrite(
underwriter,
buyer,
shortTokenId,
toPay == 0 ? contractSize : intervalContractSize,
intervalPremium,
false
);
contractSize -= intervalContractSize;
}
}
function _burnLongTokenLoop(
uint256 contractSize,
uint256 exerciseValue,
uint256 longTokenId,
bool isCall
) internal returns (uint256 totalFee) {
EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage
.layout()
.accountsByToken[longTokenId];
while (contractSize > 0) {
address longTokenHolder = holders.at(holders.length() - 1);
uint256 intervalContractSize = _balanceOf(
longTokenHolder,
longTokenId
);
if (intervalContractSize > contractSize)
intervalContractSize = contractSize;
uint256 intervalExerciseValue;
uint256 fee;
if (exerciseValue > 0) {
intervalExerciseValue =
(exerciseValue * intervalContractSize) /
contractSize;
fee = _getFeeWithDiscount(
longTokenHolder,
FEE_64x64.mulu(intervalExerciseValue)
);
totalFee += fee;
exerciseValue -= intervalExerciseValue;
_pushTo(
longTokenHolder,
_getPoolToken(isCall),
intervalExerciseValue - fee
);
}
contractSize -= intervalContractSize;
emit Exercise(
longTokenHolder,
longTokenId,
intervalContractSize,
intervalExerciseValue - fee,
fee
);
_burn(longTokenHolder, longTokenId, intervalContractSize);
}
}
function _burnShortTokenLoop(
uint256 contractSize,
uint256 exerciseValue,
uint256 shortTokenId,
bool isCall
) internal returns (uint256 totalFee) {
EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage
.layout()
.accountsByToken[shortTokenId];
(, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId);
while (contractSize > 0) {
address underwriter = underwriters.at(underwriters.length() - 1);
// amount of liquidity provided by underwriter
uint256 intervalContractSize = _balanceOf(
underwriter,
shortTokenId
);
if (intervalContractSize > contractSize)
intervalContractSize = contractSize;
// amount of value claimed by buyer
uint256 intervalExerciseValue = (exerciseValue *
intervalContractSize) / contractSize;
exerciseValue -= intervalExerciseValue;
contractSize -= intervalContractSize;
uint256 freeLiq = isCall
? intervalContractSize - intervalExerciseValue
: PoolStorage.layout().fromUnderlyingToBaseDecimals(
strike64x64.mulu(intervalContractSize)
) - intervalExerciseValue;
uint256 fee = _getFeeWithDiscount(
underwriter,
FEE_64x64.mulu(freeLiq)
);
totalFee += fee;
uint256 tvlToSubtract = intervalExerciseValue;
// mint free liquidity tokens for underwriter
if (
PoolStorage.layout().getReinvestmentStatus(underwriter, isCall)
) {
_addToDepositQueue(underwriter, freeLiq - fee, isCall);
tvlToSubtract += fee;
} else {
_mint(
underwriter,
_getReservedLiquidityTokenId(isCall),
freeLiq - fee
);
tvlToSubtract += freeLiq;
}
_subUserTVL(
PoolStorage.layout(),
underwriter,
isCall,
tvlToSubtract
);
// burn short option tokens from underwriter
_burn(underwriter, shortTokenId, intervalContractSize);
emit AssignExercise(
underwriter,
shortTokenId,
freeLiq - fee,
intervalContractSize,
fee
);
}
}
function _addToDepositQueue(
address account,
uint256 amount,
bool isCallPool
) internal {
PoolStorage.Layout storage l = PoolStorage.layout();
_mint(account, _getFreeLiquidityTokenId(isCallPool), amount);
uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) *
BATCHING_PERIOD +
BATCHING_PERIOD;
l.pendingDeposits[account][nextBatch][isCallPool] += amount;
PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool];
batchData.totalPendingDeposits += amount;
batchData.eta = nextBatch;
}
function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall)
internal
{
PoolStorage.BatchData storage data = l.nextDeposits[isCall];
if (data.eta == 0 || block.timestamp < data.eta) return;
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
_setCLevel(
l,
oldLiquidity64x64,
oldLiquidity64x64.add(
ABDKMath64x64Token.fromDecimals(
data.totalPendingDeposits,
l.getTokenDecimals(isCall)
)
),
isCall
);
delete l.nextDeposits[isCall];
}
function _getFreeLiquidityTokenId(bool isCall)
internal
view
returns (uint256 freeLiqTokenId)
{
freeLiqTokenId = isCall
? UNDERLYING_FREE_LIQ_TOKEN_ID
: BASE_FREE_LIQ_TOKEN_ID;
}
function _getReservedLiquidityTokenId(bool isCall)
internal
view
returns (uint256 reservedLiqTokenId)
{
reservedLiqTokenId = isCall
? UNDERLYING_RESERVED_LIQ_TOKEN_ID
: BASE_RESERVED_LIQ_TOKEN_ID;
}
function _getPoolToken(bool isCall) internal view returns (address token) {
token = isCall
? PoolStorage.layout().underlying
: PoolStorage.layout().base;
}
function _getTokenType(bool isCall, bool isLong)
internal
pure
returns (PoolStorage.TokenType tokenType)
{
if (isCall) {
tokenType = isLong
? PoolStorage.TokenType.LONG_CALL
: PoolStorage.TokenType.SHORT_CALL;
} else {
tokenType = isLong
? PoolStorage.TokenType.LONG_PUT
: PoolStorage.TokenType.SHORT_PUT;
}
}
function _getMinimumAmount(PoolStorage.Layout storage l, bool isCall)
internal
view
returns (uint256 minimumAmount)
{
minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum;
}
function _getPoolCapAmount(PoolStorage.Layout storage l, bool isCall)
internal
view
returns (uint256 poolCapAmount)
{
poolCapAmount = isCall ? l.underlyingPoolCap : l.basePoolCap;
}
function _setCLevel(
PoolStorage.Layout storage l,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal {
int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool);
int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment(
oldCLevel64x64,
oldLiquidity64x64,
newLiquidity64x64,
isCallPool
);
l.setCLevel(cLevel64x64, isCallPool);
emit UpdateCLevel(
isCallPool,
cLevel64x64,
oldLiquidity64x64,
newLiquidity64x64
);
}
/**
* @notice calculate and store updated market state
* @param l storage layout struct
* @return newPrice64x64 64x64 fixed point representation of current spot price
*/
function _update(PoolStorage.Layout storage l)
internal
returns (int128 newPrice64x64)
{
if (l.updatedAt == block.timestamp) {
return (l.getPriceUpdate(block.timestamp));
}
newPrice64x64 = l.fetchPriceUpdate();
if (l.getPriceUpdate(block.timestamp) == 0) {
l.setPriceUpdate(block.timestamp, newPrice64x64);
}
l.updatedAt = block.timestamp;
_processPendingDeposits(l, true);
_processPendingDeposits(l, false);
}
/**
* @notice transfer ERC20 tokens to message sender
* @param token ERC20 token address
* @param amount quantity of token to transfer
*/
function _pushTo(
address to,
address token,
uint256 amount
) internal {
if (amount == 0) return;
require(IERC20(token).transfer(to, amount), "ERC20 transfer failed");
}
/**
* @notice transfer ERC20 tokens from message sender
* @param from address from which tokens are pulled from
* @param token ERC20 token address
* @param amount quantity of token to transfer
* @param skipWethDeposit if false, will not try to deposit weth from attach eth
*/
function _pullFrom(
address from,
address token,
uint256 amount,
bool skipWethDeposit
) internal {
if (!skipWethDeposit) {
if (token == WETH_ADDRESS) {
if (msg.value > 0) {
if (msg.value > amount) {
IWETH(WETH_ADDRESS).deposit{value: amount}();
(bool success, ) = payable(msg.sender).call{
value: msg.value - amount
}("");
require(success, "ETH refund failed");
amount = 0;
} else {
unchecked {
amount -= msg.value;
}
IWETH(WETH_ADDRESS).deposit{value: msg.value}();
}
}
} else {
require(msg.value == 0, "not WETH deposit");
}
}
if (amount > 0) {
require(
IERC20(token).transferFrom(from, address(this), amount),
"ERC20 transfer failed"
);
}
}
function _mint(
address account,
uint256 tokenId,
uint256 amount
) internal {
_mint(account, tokenId, amount, "");
}
function _addUserTVL(
PoolStorage.Layout storage l,
address user,
bool isCallPool,
uint256 amount
) internal {
uint256 userTVL = l.userTVL[user][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending(
user,
address(this),
isCallPool,
userTVL,
userTVL + amount,
totalTVL
);
l.userTVL[user][isCallPool] = userTVL + amount;
l.totalTVL[isCallPool] = totalTVL + amount;
}
function _subUserTVL(
PoolStorage.Layout storage l,
address user,
bool isCallPool,
uint256 amount
) internal {
uint256 userTVL = l.userTVL[user][isCallPool];
uint256 totalTVL = l.totalTVL[isCallPool];
IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending(
user,
address(this),
isCallPool,
userTVL,
userTVL - amount,
totalTVL
);
l.userTVL[user][isCallPool] = userTVL - amount;
l.totalTVL[isCallPool] = totalTVL - amount;
}
/**
* @notice ERC1155 hook: track eligible underwriters
* @param operator transaction sender
* @param from token sender
* @param to token receiver
* @param ids token ids transferred
* @param amounts token quantities transferred
* @param data data payload
*/
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);
PoolStorage.Layout storage l = PoolStorage.layout();
for (uint256 i; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
if (amount == 0) continue;
if (from == address(0)) {
l.tokenIds.add(id);
}
if (
to == address(0) &&
ERC1155EnumerableStorage.layout().totalSupply[id] == 0
) {
l.tokenIds.remove(id);
}
// prevent transfer of free and reserved liquidity during waiting period
if (
id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == BASE_FREE_LIQ_TOKEN_ID ||
id == UNDERLYING_RESERVED_LIQ_TOKEN_ID ||
id == BASE_RESERVED_LIQ_TOKEN_ID
) {
if (from != address(0) && to != address(0)) {
bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == UNDERLYING_RESERVED_LIQ_TOKEN_ID;
require(
l.depositedAt[from][isCallPool] + (1 days) <
block.timestamp,
"liq lock 1d"
);
}
}
if (
id == UNDERLYING_FREE_LIQ_TOKEN_ID ||
id == BASE_FREE_LIQ_TOKEN_ID
) {
bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID;
uint256 minimum = _getMinimumAmount(l, isCallPool);
if (from != address(0)) {
uint256 balance = _balanceOf(from, id);
if (balance > minimum && balance <= amount + minimum) {
require(
balance -
l.pendingDeposits[from][
l.nextDeposits[isCallPool].eta
][isCallPool] >=
amount,
"Insuf balance"
);
l.removeUnderwriter(from, isCallPool);
}
if (to != address(0)) {
_subUserTVL(l, from, isCallPool, amounts[i]);
_addUserTVL(l, to, isCallPool, amounts[i]);
}
}
if (to != address(0)) {
uint256 balance = _balanceOf(to, id);
if (balance <= minimum && balance + amount > minimum) {
l.addUnderwriter(to, isCallPool);
}
}
}
// Update userTVL on SHORT options transfers
(
PoolStorage.TokenType tokenType,
,
int128 strike64x64
) = PoolStorage.parseTokenId(id);
if (
(from != address(0) && to != address(0)) &&
(tokenType == PoolStorage.TokenType.SHORT_CALL ||
tokenType == PoolStorage.TokenType.SHORT_PUT)
) {
bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL;
uint256 collateral = isCall
? amount
: l.fromUnderlyingToBaseDecimals(strike64x64.mulu(amount));
_subUserTVL(l, from, isCall, collateral);
_addUserTVL(l, to, isCall, collateral);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol";
import {OptionMath} from "../libraries/OptionMath.sol";
library PoolStorage {
using ABDKMath64x64 for int128;
using PoolStorage for PoolStorage.Layout;
enum TokenType {
UNDERLYING_FREE_LIQ,
BASE_FREE_LIQ,
UNDERLYING_RESERVED_LIQ,
BASE_RESERVED_LIQ,
LONG_CALL,
SHORT_CALL,
LONG_PUT,
SHORT_PUT
}
struct PoolSettings {
address underlying;
address base;
address underlyingOracle;
address baseOracle;
}
struct QuoteArgsInternal {
address feePayer; // address of the fee payer
uint64 maturity; // timestamp of option maturity
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
uint256 contractSize; // size of option contract
bool isCall; // true for call, false for put
}
struct QuoteResultInternal {
int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee)
int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put
int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase
int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size
}
struct BatchData {
uint256 eta;
uint256 totalPendingDeposits;
}
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.Pool");
uint256 private constant C_DECAY_BUFFER = 12 hours;
uint256 private constant C_DECAY_INTERVAL = 4 hours;
struct Layout {
// ERC20 token addresses
address base;
address underlying;
// AggregatorV3Interface oracle addresses
address baseOracle;
address underlyingOracle;
// token metadata
uint8 underlyingDecimals;
uint8 baseDecimals;
// minimum amounts
uint256 baseMinimum;
uint256 underlyingMinimum;
// deposit caps
uint256 basePoolCap;
uint256 underlyingPoolCap;
// market state
int128 _deprecated_steepness64x64;
int128 cLevelBase64x64;
int128 cLevelUnderlying64x64;
uint256 cLevelBaseUpdatedAt;
uint256 cLevelUnderlyingUpdatedAt;
uint256 updatedAt;
// User -> isCall -> depositedAt
mapping(address => mapping(bool => uint256)) depositedAt;
mapping(address => mapping(bool => uint256)) divestmentTimestamps;
// doubly linked list of free liquidity intervals
// isCall -> User -> User
mapping(bool => mapping(address => address)) liquidityQueueAscending;
mapping(bool => mapping(address => address)) liquidityQueueDescending;
// minimum resolution price bucket => price
mapping(uint256 => int128) bucketPrices64x64;
// sequence id (minimum resolution price bucket / 256) => price update sequence
mapping(uint256 => uint256) priceUpdateSequences;
// isCall -> batch data
mapping(bool => BatchData) nextDeposits;
// user -> batch timestamp -> isCall -> pending amount
mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits;
EnumerableSet.UintSet tokenIds;
// user -> isCallPool -> total value locked of user (Used for liquidity mining)
mapping(address => mapping(bool => uint256)) userTVL;
// isCallPool -> total value locked
mapping(bool => uint256) totalTVL;
// steepness values
int128 steepnessBase64x64;
int128 steepnessUnderlying64x64;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
/**
* @notice calculate ERC1155 token id for given option parameters
* @param tokenType TokenType enum
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @return tokenId token id
*/
function formatTokenId(
TokenType tokenType,
uint64 maturity,
int128 strike64x64
) internal pure returns (uint256 tokenId) {
tokenId =
(uint256(tokenType) << 248) +
(uint256(maturity) << 128) +
uint256(int256(strike64x64));
}
/**
* @notice derive option maturity and strike price from ERC1155 token id
* @param tokenId token id
* @return tokenType TokenType enum
* @return maturity timestamp of option maturity
* @return strike64x64 option strike price
*/
function parseTokenId(uint256 tokenId)
internal
pure
returns (
TokenType tokenType,
uint64 maturity,
int128 strike64x64
)
{
assembly {
tokenType := shr(248, tokenId)
maturity := shr(128, tokenId)
strike64x64 := tokenId
}
}
function getTokenDecimals(Layout storage l, bool isCall)
internal
view
returns (uint8 decimals)
{
decimals = isCall ? l.underlyingDecimals : l.baseDecimals;
}
/**
* @notice get the total supply of free liquidity tokens, minus pending deposits
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return 64x64 fixed point representation of total free liquidity
*/
function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall)
internal
view
returns (int128)
{
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
return
ABDKMath64x64Token.fromDecimals(
ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits,
l.getTokenDecimals(isCall)
);
}
function getReinvestmentStatus(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
uint256 timestamp = l.divestmentTimestamps[account][isCallPool];
return timestamp == 0 || timestamp > block.timestamp;
}
function addUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (_isInQueue(account, asc, desc)) return;
address last = desc[address(0)];
asc[last] = account;
desc[account] = last;
desc[address(0)] = account;
}
function removeUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (!_isInQueue(account, asc, desc)) return;
address prev = desc[account];
address next = asc[account];
asc[prev] = next;
desc[next] = prev;
delete asc[account];
delete desc[account];
}
function isInQueue(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
return _isInQueue(account, asc, desc);
}
function _isInQueue(
address account,
mapping(address => address) storage asc,
mapping(address => address) storage desc
) private view returns (bool) {
return asc[account] != address(0) || desc[address(0)] == account;
}
/**
* @notice get current C-Level, without accounting for pending adjustments
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function getRawCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64;
}
/**
* @notice get current C-Level, accounting for unrealized decay
* @param l storage layout struct
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
// get raw C-Level from storage
cLevel64x64 = l.getRawCLevel64x64(isCall);
// account for C-Level decay
cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall);
}
/**
* @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits
* @param l storage layout struct
* @param isCall whether to update C-Level for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
* @return liquidity64x64 64x64 fixed point representation of new liquidity amount
*/
function getRealPoolState(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64, int128 liquidity64x64)
{
PoolStorage.BatchData storage batchData = l.nextDeposits[isCall];
int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall);
int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall);
if (
batchData.totalPendingDeposits > 0 &&
batchData.eta != 0 &&
block.timestamp >= batchData.eta
) {
liquidity64x64 = ABDKMath64x64Token
.fromDecimals(
batchData.totalPendingDeposits,
l.getTokenDecimals(isCall)
)
.add(oldLiquidity64x64);
cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment(
oldCLevel64x64,
oldLiquidity64x64,
liquidity64x64,
isCall
);
} else {
cLevel64x64 = oldCLevel64x64;
liquidity64x64 = oldLiquidity64x64;
}
}
/**
* @notice calculate updated C-Level, accounting for unrealized decay
* @param l storage layout struct
* @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay
* @param isCall whether query is for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay
*/
function applyCLevelDecayAdjustment(
Layout storage l,
int128 oldCLevel64x64,
bool isCall
) internal view returns (int128 cLevel64x64) {
uint256 timeElapsed = block.timestamp -
(isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt);
// do not apply C decay if less than 24 hours have elapsed
if (timeElapsed > C_DECAY_BUFFER) {
timeElapsed -= C_DECAY_BUFFER;
} else {
return oldCLevel64x64;
}
int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu(
timeElapsed,
C_DECAY_INTERVAL
);
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
uint256 tvl = l.totalTVL[isCall];
int128 utilization = ABDKMath64x64.divu(
tvl -
(ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits),
tvl
);
return
OptionMath.calculateCLevelDecay(
OptionMath.CalculateCLevelDecayArgs(
timeIntervalsElapsed64x64,
oldCLevel64x64,
utilization,
0xb333333333333333, // 0.7
0xe666666666666666, // 0.9
0x10000000000000000, // 1.0
0x10000000000000000, // 1.0
0xe666666666666666, // 0.9
0x56fc2a2c515da32ea // 2e
)
);
}
/**
* @notice calculate updated C-Level, accounting for change in liquidity
* @param l storage layout struct
* @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change
* @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity
* @param newLiquidity64x64 64x64 fixed point representation of current liquidity
* @param isCallPool whether to update C-Level for call or put pool
* @return cLevel64x64 64x64 fixed point representation of C-Level
*/
function applyCLevelLiquidityChangeAdjustment(
Layout storage l,
int128 oldCLevel64x64,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal view returns (int128 cLevel64x64) {
int128 steepness64x64 = isCallPool
? l.steepnessUnderlying64x64
: l.steepnessBase64x64;
// fallback to deprecated storage value if side-specific value is not set
if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64;
cLevel64x64 = OptionMath.calculateCLevel(
oldCLevel64x64,
oldLiquidity64x64,
newLiquidity64x64,
steepness64x64
);
if (cLevel64x64 < 0xb333333333333333) {
cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7
}
}
/**
* @notice set C-Level to arbitrary pre-calculated value
* @param cLevel64x64 new C-Level of pool
* @param isCallPool whether to update C-Level for call or put pool
*/
function setCLevel(
Layout storage l,
int128 cLevel64x64,
bool isCallPool
) internal {
if (isCallPool) {
l.cLevelUnderlying64x64 = cLevel64x64;
l.cLevelUnderlyingUpdatedAt = block.timestamp;
} else {
l.cLevelBase64x64 = cLevel64x64;
l.cLevelBaseUpdatedAt = block.timestamp;
}
}
function setOracles(
Layout storage l,
address baseOracle,
address underlyingOracle
) internal {
require(
AggregatorV3Interface(baseOracle).decimals() ==
AggregatorV3Interface(underlyingOracle).decimals(),
"Pool: oracle decimals must match"
);
l.baseOracle = baseOracle;
l.underlyingOracle = underlyingOracle;
}
function fetchPriceUpdate(Layout storage l)
internal
view
returns (int128 price64x64)
{
int256 priceUnderlying = AggregatorInterface(l.underlyingOracle)
.latestAnswer();
int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer();
return ABDKMath64x64.divi(priceUnderlying, priceBase);
}
/**
* @notice set price update for hourly bucket corresponding to given timestamp
* @param l storage layout struct
* @param timestamp timestamp to update
* @param price64x64 64x64 fixed point representation of price
*/
function setPriceUpdate(
Layout storage l,
uint256 timestamp,
int128 price64x64
) internal {
uint256 bucket = timestamp / (1 hours);
l.bucketPrices64x64[bucket] = price64x64;
l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255));
}
/**
* @notice get price update for hourly bucket corresponding to given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdate(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
return l.bucketPrices64x64[timestamp / (1 hours)];
}
/**
* @notice get first price update available following given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdateAfter(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
// price updates are grouped into hourly buckets
uint256 bucket = timestamp / (1 hours);
// divide by 256 to get the index of the relevant price update sequence
uint256 sequenceId = bucket >> 8;
// get position within sequence relevant to current price update
uint256 offset = bucket & 255;
// shift to skip buckets from earlier in sequence
uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >>
offset;
// iterate through future sequences until a price update is found
// sequence corresponding to current timestamp used as upper bound
uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours);
while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) {
sequence = l.priceUpdateSequences[++sequenceId];
}
// if no price update is found (sequence == 0) function will return 0
// this should never occur, as each relevant external function triggers a price update
// the most significant bit of the sequence corresponds to the offset of the relevant bucket
uint256 msb;
for (uint256 i = 128; i > 0; i >>= 1) {
if (sequence >> i > 0) {
msb += i;
sequence >>= i;
}
}
return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1];
}
function fromBaseToUnderlyingDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.baseDecimals
);
return
ABDKMath64x64Token.toDecimals(
valueFixed64x64,
l.underlyingDecimals
);
}
function fromUnderlyingToBaseDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.underlyingDecimals
);
return ABDKMath64x64Token.toDecimals(valueFixed64x64, l.baseDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1155Metadata interface
*/
interface IERC1155Metadata {
/**
* @notice get generated URI for given token
* @return token URI
*/
function uri(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer()
external
view
returns (
int256
);
function latestTimestamp()
external
view
returns (
uint256
);
function latestRound()
external
view
returns (
uint256
);
function getAnswer(
uint256 roundId
)
external
view
returns (
int256
);
function getTimestamp(
uint256 roundId
)
external
view
returns (
uint256
);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
library ERC1155EnumerableStorage {
struct Layout {
mapping(uint256 => uint256) totalSupply;
mapping(uint256 => EnumerableSet.AddressSet) accountsByToken;
mapping(address => EnumerableSet.UintSet) tokensByAccount;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC1155Enumerable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// 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: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library ABDKMath64x64Token {
using ABDKMath64x64 for int128;
/**
* @notice convert 64x64 fixed point representation of token amount to decimal
* @param value64x64 64x64 fixed point representation of token amount
* @param decimals token display decimals
* @return value decimal representation of token amount
*/
function toDecimals(int128 value64x64, uint8 decimals)
internal
pure
returns (uint256 value)
{
value = value64x64.mulu(10**decimals);
}
/**
* @notice convert decimal representation of token amount to 64x64 fixed point
* @param value decimal representation of token amount
* @param decimals token display decimals
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromDecimals(uint256 value, uint8 decimals)
internal
pure
returns (int128 value64x64)
{
value64x64 = ABDKMath64x64.divu(value, 10**decimals);
}
/**
* @notice convert 64x64 fixed point representation of token amount to wei (18 decimals)
* @param value64x64 64x64 fixed point representation of token amount
* @return value wei representation of token amount
*/
function toWei(int128 value64x64) internal pure returns (uint256 value) {
value = toDecimals(value64x64, 18);
}
/**
* @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point
* @param value wei representation of token amount
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromWei(uint256 value) internal pure returns (int128 value64x64) {
value64x64 = fromDecimals(value, 18);
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library OptionMath {
using ABDKMath64x64 for int128;
struct QuoteArgs {
int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years)
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase
int128 oldPoolState; // 64x64 fixed point representation of current state of the pool
int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade
int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier
int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options
bool isCall; // whether to price "call" or "put" option
}
struct CalculateCLevelDecayArgs {
int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay
int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate
int128 utilizationLowerBound64x64;
int128 utilizationUpperBound64x64;
int128 cLevelLowerBound64x64;
int128 cLevelUpperBound64x64;
int128 cConvergenceULowerBound64x64;
int128 cConvergenceUUpperBound64x64;
}
// 64x64 fixed point integer constants
int128 internal constant ONE_64x64 = 0x10000000000000000;
int128 internal constant THREE_64x64 = 0x30000000000000000;
// 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF
int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989
int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989
int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989
/**
* @notice recalculate C-Level based on change in liquidity
* @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update
* @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update
* @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update
* @param steepness64x64 64x64 fixed point representation of steepness coefficient
* @return 64x64 fixed point representation of new C-Level
*/
function calculateCLevel(
int128 initialCLevel64x64,
int128 oldPoolState64x64,
int128 newPoolState64x64,
int128 steepness64x64
) external pure returns (int128) {
return
newPoolState64x64
.sub(oldPoolState64x64)
.div(
oldPoolState64x64 > newPoolState64x64
? oldPoolState64x64
: newPoolState64x64
)
.mul(steepness64x64)
.neg()
.exp()
.mul(initialCLevel64x64);
}
/**
* @notice calculate the price of an option using the Premia Finance model
* @param args arguments of quotePrice
* @return premiaPrice64x64 64x64 fixed point representation of Premia option price
* @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase
*/
function quotePrice(QuoteArgs memory args)
external
pure
returns (
int128 premiaPrice64x64,
int128 cLevel64x64,
int128 slippageCoefficient64x64
)
{
int128 deltaPoolState64x64 = args
.newPoolState
.sub(args.oldPoolState)
.div(args.oldPoolState)
.mul(args.steepness64x64);
int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp();
int128 blackScholesPrice64x64 = _blackScholesPrice(
args.varianceAnnualized64x64,
args.strike64x64,
args.spot64x64,
args.timeToMaturity64x64,
args.isCall
);
cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64);
slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div(
deltaPoolState64x64
);
premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul(
slippageCoefficient64x64
);
int128 intrinsicValue64x64;
if (args.isCall && args.strike64x64 < args.spot64x64) {
intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64);
} else if (!args.isCall && args.strike64x64 > args.spot64x64) {
intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64);
}
int128 collateralValue64x64 = args.isCall
? args.spot64x64
: args.strike64x64;
int128 minPrice64x64 = intrinsicValue64x64.add(
collateralValue64x64.mul(args.minAPY64x64).mul(
args.timeToMaturity64x64
)
);
if (minPrice64x64 > premiaPrice64x64) {
premiaPrice64x64 = minPrice64x64;
}
}
/**
* @notice calculate the decay of C-Level based on heat diffusion function
* @param args structured CalculateCLevelDecayArgs
* @return cLevelDecayed64x64 C-Level after accounting for decay
*/
function calculateCLevelDecay(CalculateCLevelDecayArgs memory args)
external
pure
returns (int128 cLevelDecayed64x64)
{
int128 convFHighU64x64 = (args.utilization64x64 >=
args.utilizationUpperBound64x64 &&
args.oldCLevel64x64 <= args.cLevelLowerBound64x64)
? ONE_64x64
: int128(0);
int128 convFLowU64x64 = (args.utilization64x64 <=
args.utilizationLowerBound64x64 &&
args.oldCLevel64x64 >= args.cLevelUpperBound64x64)
? ONE_64x64
: int128(0);
cLevelDecayed64x64 = args
.oldCLevel64x64
.sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64))
.sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64))
.mul(
convFLowU64x64
.mul(ONE_64x64.sub(args.utilization64x64))
.add(convFHighU64x64.mul(args.utilization64x64))
.mul(args.timeIntervalsElapsed64x64)
.neg()
.exp()
)
.add(
args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add(
args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)
)
);
}
/**
* @notice calculate the exponential decay coefficient for a given interval
* @param oldTimestamp timestamp of previous update
* @param newTimestamp current timestamp
* @return 64x64 fixed point representation of exponential decay coefficient
*/
function _decay(uint256 oldTimestamp, uint256 newTimestamp)
internal
pure
returns (int128)
{
return
ONE_64x64.sub(
(-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp()
);
}
/**
* @notice calculate Choudhury’s approximation of the Black-Scholes CDF
* @param input64x64 64x64 fixed point representation of random variable
* @return 64x64 fixed point representation of the approximated CDF of x
*/
function _N(int128 input64x64) internal pure returns (int128) {
// squaring via mul is cheaper than via pow
int128 inputSquared64x64 = input64x64.mul(input64x64);
int128 value64x64 = (-inputSquared64x64 >> 1).exp().div(
CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add(
CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt())
)
);
return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64;
}
/**
* @notice calculate the price of an option using the Black-Scholes model
* @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance
* @param strike64x64 64x64 fixed point representation of strike price
* @param spot64x64 64x64 fixed point representation of spot price
* @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years)
* @param isCall whether to price "call" or "put" option
* @return 64x64 fixed point representation of Black-Scholes option price
*/
function _blackScholesPrice(
int128 varianceAnnualized64x64,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) internal pure returns (int128) {
int128 cumulativeVariance64x64 = timeToMaturity64x64.mul(
varianceAnnualized64x64
);
int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt();
int128 d1_64x64 = spot64x64
.div(strike64x64)
.ln()
.add(cumulativeVariance64x64 >> 1)
.div(cumulativeVarianceSqrt64x64);
int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64);
if (isCall) {
return
spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64)));
} else {
return
-spot64x64.mul(_N(-d1_64x64)).sub(
strike64x64.mul(_N(-d2_64x64))
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Contract ownership standard interface
* @dev see https://eips.ethereum.org/EIPS/eip-173
*/
interface IERC173 {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @notice get the ERC173 contract owner
* @return conract owner
*/
function owner() external view returns (address);
/**
* @notice transfer contract ownership to new account
* @param account address of new owner
*/
function transferOwnership(address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library OwnableStorage {
struct Layout {
address owner;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.Ownable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function setOwner(Layout storage l, address owner) internal {
l.owner = owner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20Internal } from './IERC20Internal.sol';
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 is IERC20Internal {
/**
* @notice query the total minted token supply
* @return token supply
*/
function totalSupply() external view returns (uint256);
/**
* @notice query the token balance of given account
* @param account address to query
* @return token balance
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice query the allowance granted from given holder to given spender
* @param holder approver of allowance
* @param spender recipient of allowance
* @return token allowance
*/
function allowance(address holder, address spender)
external
view
returns (uint256);
/**
* @notice grant approval to spender to spend tokens
* @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
* @param spender recipient of allowance
* @param amount quantity of tokens approved for spending
* @return success status (always true; otherwise function should revert)
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice transfer tokens to given recipient
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @notice transfer tokens to given recipient on behalf of given holder
* @param holder holder of tokens prior to transfer
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol';
import { IERC1155Enumerable } from './IERC1155Enumerable.sol';
import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol';
/**
* @title ERC1155 implementation including enumerable and aggregate functions
*/
abstract contract ERC1155Enumerable is
IERC1155Enumerable,
ERC1155Base,
ERC1155EnumerableInternal
{
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @inheritdoc IERC1155Enumerable
*/
function totalSupply(uint256 id)
public
view
virtual
override
returns (uint256)
{
return _totalSupply(id);
}
/**
* @inheritdoc IERC1155Enumerable
*/
function totalHolders(uint256 id)
public
view
virtual
override
returns (uint256)
{
return _totalHolders(id);
}
/**
* @inheritdoc IERC1155Enumerable
*/
function accountsByToken(uint256 id)
public
view
virtual
override
returns (address[] memory)
{
return _accountsByToken(id);
}
/**
* @inheritdoc IERC1155Enumerable
*/
function tokensByAccount(address account)
public
view
virtual
override
returns (uint256[] memory)
{
return _tokensByAccount(account);
}
/**
* @notice ERC1155 hook: update aggregate values
* @inheritdoc ERC1155EnumerableInternal
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
override(ERC1155BaseInternal, ERC1155EnumerableInternal)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20 } from '../token/ERC20/IERC20.sol';
import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol';
/**
* @title WETH (Wrapped ETH) interface
*/
interface IWETH is IERC20, IERC20Metadata {
/**
* @notice convert ETH to WETH
*/
function deposit() external payable;
/**
* @notice convert WETH to ETH
* @dev if caller is a contract, it should have a fallback or receive function
* @param amount quantity of WETH to convert, denominated in wei
*/
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {FeeDiscountStorage} from "./FeeDiscountStorage.sol";
interface IFeeDiscount {
event Staked(
address indexed user,
uint256 amount,
uint256 stakePeriod,
uint256 lockedUntil
);
event Unstaked(address indexed user, uint256 amount);
struct StakeLevel {
uint256 amount; // Amount to stake
uint256 discount; // Discount when amount is reached
}
/**
* @notice Stake using IERC2612 permit
* @param amount The amount of xPremia to stake
* @param period The lockup period (in seconds)
* @param deadline Deadline after which permit will fail
* @param v V
* @param r R
* @param s S
*/
function stakeWithPermit(
uint256 amount,
uint256 period,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Lockup xPremia for protocol fee discounts
* Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation
* @param amount The amount of xPremia to stake
* @param period The lockup period (in seconds)
*/
function stake(uint256 amount, uint256 period) external;
/**
* @notice Unstake xPremia (If lockup period has ended)
* @param amount The amount of xPremia to unstake
*/
function unstake(uint256 amount) external;
//////////
// View //
//////////
/**
* Calculate the stake amount of a user, after applying the bonus from the lockup period chosen
* @param user The user from which to query the stake amount
* @return The user stake amount after applying the bonus
*/
function getStakeAmountWithBonus(address user)
external
view
returns (uint256);
/**
* @notice Calculate the % of fee discount for user, based on his stake
* @param user The _user for which the discount is for
* @return Percentage of protocol fee discount (in basis point)
* Ex : 1000 = 10% fee discount
*/
function getDiscount(address user) external view returns (uint256);
/**
* @notice Get stake levels
* @return Stake levels
* Ex : 2500 = -25%
*/
function getStakeLevels() external returns (StakeLevel[] memory);
/**
* @notice Get stake period multiplier
* @param period The duration (in seconds) for which tokens are locked
* @return The multiplier for this staking period
* Ex : 20000 = x2
*/
function getStakePeriodMultiplier(uint256 period)
external
returns (uint256);
/**
* @notice Get staking infos of a user
* @param user The user address for which to get staking infos
* @return The staking infos of the user
*/
function getUserInfo(address user)
external
view
returns (FeeDiscountStorage.UserInfo memory);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPoolEvents {
event Purchase(
address indexed user,
uint256 longTokenId,
uint256 contractSize,
uint256 baseCost,
uint256 feeCost,
int128 spot64x64
);
event Exercise(
address indexed user,
uint256 longTokenId,
uint256 contractSize,
uint256 exerciseValue,
uint256 fee
);
event Underwrite(
address indexed underwriter,
address indexed longReceiver,
uint256 shortTokenId,
uint256 intervalContractSize,
uint256 intervalPremium,
bool isManualUnderwrite
);
event AssignExercise(
address indexed underwriter,
uint256 shortTokenId,
uint256 freedAmount,
uint256 intervalContractSize,
uint256 fee
);
event Deposit(address indexed user, bool isCallPool, uint256 amount);
event Withdrawal(
address indexed user,
bool isCallPool,
uint256 depositedAt,
uint256 amount
);
event FeeWithdrawal(bool indexed isCallPool, uint256 amount);
event Annihilate(uint256 shortTokenId, uint256 amount);
event UpdateCLevel(
bool indexed isCall,
int128 cLevel64x64,
int128 oldLiquidity64x64,
int128 newLiquidity64x64
);
event UpdateSteepness(int128 steepness64x64, bool isCallPool);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {PremiaMiningStorage} from "./PremiaMiningStorage.sol";
interface IPremiaMining {
function addPremiaRewards(uint256 _amount) external;
function premiaRewardsAvailable() external view returns (uint256);
function getTotalAllocationPoints() external view returns (uint256);
function getPoolInfo(address pool, bool isCallPool)
external
view
returns (PremiaMiningStorage.PoolInfo memory);
function getPremiaPerYear() external view returns (uint256);
function addPool(address _pool, uint256 _allocPoints) external;
function setPoolAllocPoints(
address[] memory _pools,
uint256[] memory _allocPoints
) external;
function pendingPremia(
address _pool,
bool _isCallPool,
address _user
) external view returns (uint256);
function updatePool(
address _pool,
bool _isCallPool,
uint256 _totalTVL
) external;
function allocatePending(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
function claim(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol";
interface IVolatilitySurfaceOracle {
function getWhitelistedRelayers() external view returns (address[] memory);
function getVolatilitySurface(address baseToken, address underlyingToken)
external
view
returns (VolatilitySurfaceOracleStorage.Update memory);
function getVolatilitySurfaceCoefficientsUnpacked(
address baseToken,
address underlyingToken,
bool isCall
) external view returns (int256[] memory);
function getTimeToMaturity64x64(uint64 maturity)
external
view
returns (int128);
function getAnnualizedVolatility64x64(
address baseToken,
address underlyingToken,
int128 spot64x64,
int128 strike64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (int128);
function getBlackScholesPrice64x64(
address baseToken,
address underlyingToken,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (int128);
function getBlackScholesPrice(
address baseToken,
address underlyingToken,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Partial ERC20 interface needed by internal functions
*/
interface IERC20Internal {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC1155 } from '../IERC1155.sol';
import { IERC1155Receiver } from '../IERC1155Receiver.sol';
import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol';
/**
* @title Base ERC1155 contract
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal {
/**
* @inheritdoc IERC1155
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
return _balanceOf(account, id);
}
/**
* @inheritdoc IERC1155
*/
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'
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
uint256[] memory batchBalances = new uint256[](accounts.length);
unchecked {
for (uint256 i; i < accounts.length; i++) {
require(
accounts[i] != address(0),
'ERC1155: batch balance query for the zero address'
);
batchBalances[i] = balances[ids[i]][accounts[i]];
}
}
return batchBalances;
}
/**
* @inheritdoc IERC1155
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return ERC1155BaseStorage.layout().operatorApprovals[account][operator];
}
/**
* @inheritdoc IERC1155
*/
function setApprovalForAll(address operator, bool status)
public
virtual
override
{
require(
msg.sender != operator,
'ERC1155: setting approval status for self'
);
ERC1155BaseStorage.layout().operatorApprovals[msg.sender][
operator
] = status;
emit ApprovalForAll(msg.sender, operator, status);
}
/**
* @inheritdoc IERC1155
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
'ERC1155: caller is not owner nor approved'
);
_safeTransfer(msg.sender, from, to, id, amount, data);
}
/**
* @inheritdoc IERC1155
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
'ERC1155: caller is not owner nor approved'
);
_safeTransferBatch(msg.sender, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1155 enumerable and aggregate function interface
*/
interface IERC1155Enumerable {
/**
* @notice query total minted supply of given token
* @param id token id to query
* @return token supply
*/
function totalSupply(uint256 id) external view returns (uint256);
/**
* @notice query total number of holders for given token
* @param id token id to query
* @return quantity of holders
*/
function totalHolders(uint256 id) external view returns (uint256);
/**
* @notice query holders of given token
* @param id token id to query
* @return list of holder addresses
*/
function accountsByToken(uint256 id)
external
view
returns (address[] memory);
/**
* @notice query tokens held by given address
* @param account address to query
* @return list of token ids
*/
function tokensByAccount(address account)
external
view
returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol';
import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol';
/**
* @title ERC1155Enumerable internal functions
*/
abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice query total minted supply of given token
* @param id token id to query
* @return token supply
*/
function _totalSupply(uint256 id) internal view returns (uint256) {
return ERC1155EnumerableStorage.layout().totalSupply[id];
}
/**
* @notice query total number of holders for given token
* @param id token id to query
* @return quantity of holders
*/
function _totalHolders(uint256 id) internal view returns (uint256) {
return ERC1155EnumerableStorage.layout().accountsByToken[id].length();
}
/**
* @notice query holders of given token
* @param id token id to query
* @return list of holder addresses
*/
function _accountsByToken(uint256 id)
internal
view
returns (address[] memory)
{
EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage
.layout()
.accountsByToken[id];
address[] memory addresses = new address[](accounts.length());
for (uint256 i; i < accounts.length(); i++) {
addresses[i] = accounts.at(i);
}
return addresses;
}
/**
* @notice query tokens held by given address
* @param account address to query
* @return list of token ids
*/
function _tokensByAccount(address account)
internal
view
returns (uint256[] memory)
{
EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage
.layout()
.tokensByAccount[account];
uint256[] memory ids = new uint256[](tokens.length());
for (uint256 i; i < tokens.length(); i++) {
ids[i] = tokens.at(i);
}
return ids;
}
/**
* @notice ERC1155 hook: update aggregate values
* @inheritdoc ERC1155BaseInternal
*/
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);
if (from != to) {
ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage
.layout();
mapping(uint256 => EnumerableSet.AddressSet)
storage tokenAccounts = l.accountsByToken;
EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from];
EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to];
for (uint256 i; i < ids.length; i++) {
uint256 amount = amounts[i];
if (amount > 0) {
uint256 id = ids[i];
if (from == address(0)) {
l.totalSupply[id] += amount;
} else if (_balanceOf(from, id) == amount) {
tokenAccounts[id].remove(from);
fromTokens.remove(id);
}
if (to == address(0)) {
l.totalSupply[id] -= amount;
} else if (_balanceOf(to, id) == 0) {
tokenAccounts[id].add(to);
toTokens.add(id);
}
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC1155Internal } from './IERC1155Internal.sol';
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @notice ERC1155 interface
* @dev see https://github.com/ethereum/EIPs/issues/1155
*/
interface IERC1155 is IERC1155Internal, IERC165 {
/**
* @notice query the balance of given token held by given address
* @param account address to query
* @param id token to query
* @return token balance
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @notice query the balances of given tokens held by given addresses
* @param accounts addresss to query
* @param ids tokens to query
* @return token balances
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @notice query approval status of given operator with respect to given address
* @param account address to query for approval granted
* @param operator address to query for approval received
* @return whether operator is approved to spend tokens held by account
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @notice grant approval to or revoke approval from given operator to spend held tokens
* @param operator address whose approval status to update
* @param status whether operator should be considered approved
*/
function setApprovalForAll(address operator, bool status) external;
/**
* @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable
* @param from sender of tokens
* @param to receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable
* @param from sender of tokens
* @param to receiver of tokens
* @param ids list of token IDs
* @param amounts list of quantities of tokens to transfer
* @param data data payload
*/
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 { IERC165 } from '../../introspection/IERC165.sol';
/**
* @title ERC1155 transfer receiver interface
*/
interface IERC1155Receiver is IERC165 {
/**
* @notice validate receipt of ERC1155 transfer
* @param operator executor of transfer
* @param from sender of tokens
* @param id token ID received
* @param value quantity of tokens received
* @param data data payload
* @return function's own selector if transfer is accepted
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @notice validate receipt of ERC1155 batch transfer
* @param operator executor of transfer
* @param from sender of tokens
* @param ids token IDs received
* @param values quantities of tokens received
* @param data data payload
* @return function's own selector if transfer is accepted
*/
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 { AddressUtils } from '../../../utils/AddressUtils.sol';
import { IERC1155Internal } from '../IERC1155Internal.sol';
import { IERC1155Receiver } from '../IERC1155Receiver.sol';
import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol';
/**
* @title Base ERC1155 internal functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
abstract contract ERC1155BaseInternal is IERC1155Internal {
using AddressUtils for address;
/**
* @notice query the balance of given token held by given address
* @param account address to query
* @param id token to query
* @return token balance
*/
function _balanceOf(address account, uint256 id)
internal
view
virtual
returns (uint256)
{
require(
account != address(0),
'ERC1155: balance query for the zero address'
);
return ERC1155BaseStorage.layout().balances[id][account];
}
/**
* @notice mint given quantity of tokens for given address
* @dev ERC1155Receiver implementation is not checked
* @param account beneficiary of minting
* @param id token ID
* @param amount quantity of tokens to mint
* @param data data payload
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), 'ERC1155: mint to the zero address');
_beforeTokenTransfer(
msg.sender,
address(0),
account,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
mapping(address => uint256) storage balances = ERC1155BaseStorage
.layout()
.balances[id];
balances[account] += amount;
emit TransferSingle(msg.sender, address(0), account, id, amount);
}
/**
* @notice mint given quantity of tokens for given address
* @param account beneficiary of minting
* @param id token ID
* @param amount quantity of tokens to mint
* @param data data payload
*/
function _safeMint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
_mint(account, id, amount, data);
_doSafeTransferAcceptanceCheck(
msg.sender,
address(0),
account,
id,
amount,
data
);
}
/**
* @notice mint batch of tokens for given address
* @dev ERC1155Receiver implementation is not checked
* @param account beneficiary of minting
* @param ids list of token IDs
* @param amounts list of quantities of tokens to mint
* @param data data payload
*/
function _mintBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(account != address(0), 'ERC1155: mint to the zero address');
require(
ids.length == amounts.length,
'ERC1155: ids and amounts length mismatch'
);
_beforeTokenTransfer(
msg.sender,
address(0),
account,
ids,
amounts,
data
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
for (uint256 i; i < ids.length; i++) {
balances[ids[i]][account] += amounts[i];
}
emit TransferBatch(msg.sender, address(0), account, ids, amounts);
}
/**
* @notice mint batch of tokens for given address
* @param account beneficiary of minting
* @param ids list of token IDs
* @param amounts list of quantities of tokens to mint
* @param data data payload
*/
function _safeMintBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
_mintBatch(account, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
msg.sender,
address(0),
account,
ids,
amounts,
data
);
}
/**
* @notice burn given quantity of tokens held by given address
* @param account holder of tokens to burn
* @param id token ID
* @param amount quantity of tokens to burn
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), 'ERC1155: burn from the zero address');
_beforeTokenTransfer(
msg.sender,
account,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
''
);
mapping(address => uint256) storage balances = ERC1155BaseStorage
.layout()
.balances[id];
unchecked {
require(
balances[account] >= amount,
'ERC1155: burn amount exceeds balances'
);
balances[account] -= amount;
}
emit TransferSingle(msg.sender, account, address(0), id, amount);
}
/**
* @notice burn given batch of tokens held by given address
* @param account holder of tokens to burn
* @param ids token IDs
* @param amounts quantities of tokens to burn
*/
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'
);
_beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, '');
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
unchecked {
for (uint256 i; i < ids.length; i++) {
uint256 id = ids[i];
require(
balances[id][account] >= amounts[i],
'ERC1155: burn amount exceeds balance'
);
balances[id][account] -= amounts[i];
}
}
emit TransferBatch(msg.sender, account, address(0), ids, amounts);
}
/**
* @notice transfer tokens between given addresses
* @dev ERC1155Receiver implementation is not checked
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function _transfer(
address operator,
address sender,
address recipient,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(
recipient != address(0),
'ERC1155: transfer to the zero address'
);
_beforeTokenTransfer(
operator,
sender,
recipient,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
unchecked {
uint256 senderBalance = balances[id][sender];
require(
senderBalance >= amount,
'ERC1155: insufficient balances for transfer'
);
balances[id][sender] = senderBalance - amount;
}
balances[id][recipient] += amount;
emit TransferSingle(operator, sender, recipient, id, amount);
}
/**
* @notice transfer tokens between given addresses
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
function _safeTransfer(
address operator,
address sender,
address recipient,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
_transfer(operator, sender, recipient, id, amount, data);
_doSafeTransferAcceptanceCheck(
operator,
sender,
recipient,
id,
amount,
data
);
}
/**
* @notice transfer batch of tokens between given addresses
* @dev ERC1155Receiver implementation is not checked
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _transferBatch(
address operator,
address sender,
address recipient,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(
recipient != address(0),
'ERC1155: transfer to the zero address'
);
require(
ids.length == amounts.length,
'ERC1155: ids and amounts length mismatch'
);
_beforeTokenTransfer(operator, sender, recipient, ids, amounts, data);
mapping(uint256 => mapping(address => uint256))
storage balances = ERC1155BaseStorage.layout().balances;
for (uint256 i; i < ids.length; i++) {
uint256 token = ids[i];
uint256 amount = amounts[i];
unchecked {
uint256 senderBalance = balances[token][sender];
require(
senderBalance >= amount,
'ERC1155: insufficient balances for transfer'
);
balances[token][sender] = senderBalance - amount;
}
balances[token][recipient] += amount;
}
emit TransferBatch(operator, sender, recipient, ids, amounts);
}
/**
* @notice transfer batch of tokens between given addresses
* @param operator executor of transfer
* @param sender sender of tokens
* @param recipient receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _safeTransferBatch(
address operator,
address sender,
address recipient,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
_transferBatch(operator, sender, recipient, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
operator,
sender,
recipient,
ids,
amounts,
data
);
}
/**
* @notice wrap given element in array of length 1
* @param element element to wrap
* @return singleton array
*/
function _asSingletonArray(uint256 element)
private
pure
returns (uint256[] memory)
{
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
/**
* @notice revert if applicable transfer recipient is not valid ERC1155Receiver
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param id token ID
* @param amount quantity of tokens to transfer
* @param data data payload
*/
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) {
require(
response == IERC1155Receiver.onERC1155Received.selector,
'ERC1155: ERC1155Receiver rejected tokens'
);
} catch Error(string memory reason) {
revert(reason);
} catch {
revert('ERC1155: transfer to non ERC1155Receiver implementer');
}
}
}
/**
* @notice revert if applicable transfer recipient is not valid ERC1155Receiver
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
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) {
require(
response ==
IERC1155Receiver.onERC1155BatchReceived.selector,
'ERC1155: ERC1155Receiver rejected tokens'
);
} catch Error(string memory reason) {
revert(reason);
} catch {
revert('ERC1155: transfer to non ERC1155Receiver implementer');
}
}
}
/**
* @notice ERC1155 hook, called before all transfers including mint and burn
* @dev function should be overridden and new implementation must call super
* @dev called for both single and batch transfers
* @param operator executor of transfer
* @param from sender of tokens
* @param to receiver of tokens
* @param ids token IDs
* @param amounts quantities of tokens to transfer
* @param data data payload
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC165 } from '../../introspection/IERC165.sol';
/**
* @notice Partial ERC1155 interface needed by internal functions
*/
interface IERC1155Internal {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC165 interface registration interface
* @dev see https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice query whether contract has registered support for given interface
* @param interfaceId interface id
* @return bool whether interface is supported
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library AddressUtils {
function toString(address account) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(uint160(account)));
bytes memory alphabet = '0123456789abcdef';
bytes memory chars = new bytes(42);
chars[0] = '0';
chars[1] = 'x';
for (uint256 i = 0; i < 20; i++) {
chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)];
chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(chars);
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable account, uint256 amount) internal {
(bool success, ) = account.call{ value: amount }('');
require(success, 'AddressUtils: failed to send value');
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionCall(target, data, 'AddressUtils: failed low-level call');
}
function functionCall(
address target,
bytes memory data,
string memory error
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, error);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'AddressUtils: failed low-level call with value'
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'AddressUtils: insufficient balance for call'
);
return _functionCallWithValue(target, data, value, error);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) private returns (bytes memory) {
require(
isContract(target),
'AddressUtils: function call to non-contract'
);
(bool success, bytes memory returnData) = target.call{ value: value }(
data
);
if (success) {
return returnData;
} else if (returnData.length > 0) {
assembly {
let returnData_size := mload(returnData)
revert(add(32, returnData), returnData_size)
}
} else {
revert(error);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ERC1155BaseStorage {
struct Layout {
mapping(uint256 => mapping(address => uint256)) balances;
mapping(address => mapping(address => bool)) operatorApprovals;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC1155Base');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC20 metadata interface
*/
interface IERC20Metadata {
/**
* @notice return token name
* @return token name
*/
function name() external view returns (string memory);
/**
* @notice return token symbol
* @return token symbol
*/
function symbol() external view returns (string memory);
/**
* @notice return token decimals, generally used only for display purposes
* @return token decimals
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
library FeeDiscountStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.staking.PremiaFeeDiscount");
struct UserInfo {
uint256 balance; // Balance staked by user
uint64 stakePeriod; // Stake period selected by user
uint64 lockedUntil; // Timestamp at which the lock ends
}
struct Layout {
// User data with xPREMIA balance staked and date at which lock ends
mapping(address => UserInfo) userInfo;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
library PremiaMiningStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.PremiaMining");
// Info of each pool.
struct PoolInfo {
uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block.
uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs
uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below.
}
// Info of each user.
struct UserInfo {
uint256 reward; // Total allocated unclaimed reward
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of PREMIA
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct Layout {
// Total PREMIA left to distribute
uint256 premiaAvailable;
// Amount of premia distributed per year
uint256 premiaPerYear;
// pool -> isCallPool -> PoolInfo
mapping(address => mapping(bool => PoolInfo)) poolInfo;
// pool -> isCallPool -> user -> UserInfo
mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 totalAllocPoint;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol";
library VolatilitySurfaceOracleStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.VolatilitySurfaceOracle");
uint256 internal constant COEFF_BITS = 51;
uint256 internal constant COEFF_BITS_MINUS_ONE = 50;
uint256 internal constant COEFF_AMOUNT = 5;
// START_BIT = COEFF_BITS * (COEFF_AMOUNT - 1)
uint256 internal constant START_BIT = 204;
struct Update {
uint256 updatedAt;
bytes32 callCoefficients;
bytes32 putCoefficients;
}
struct Layout {
// Base token -> Underlying token -> Update
mapping(address => mapping(address => Update)) volatilitySurfaces;
// Relayer addresses which can be trusted to provide accurate option trades
EnumerableSet.AddressSet whitelistedRelayers;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function getCoefficients(
Layout storage l,
address baseToken,
address underlyingToken,
bool isCall
) internal view returns (bytes32) {
Update storage u = l.volatilitySurfaces[baseToken][underlyingToken];
return isCall ? u.callCoefficients : u.putCoefficients;
}
function parseVolatilitySurfaceCoefficients(bytes32 input)
internal
pure
returns (int256[] memory coefficients)
{
coefficients = new int256[](COEFF_AMOUNT);
// Value to add to negative numbers to cast them to int256
int256 toAdd = (int256(-1) >> COEFF_BITS) << COEFF_BITS;
assembly {
let i := 0
// Value equal to -1
let mid := shl(COEFF_BITS_MINUS_ONE, 1)
for {
} lt(i, COEFF_AMOUNT) {
} {
let offset := sub(START_BIT, mul(COEFF_BITS, i))
let coeff := shr(
offset,
sub(
input,
shl(
add(offset, COEFF_BITS),
shr(add(offset, COEFF_BITS), input)
)
)
)
// Check if value is a negative number and needs casting
if or(eq(coeff, mid), gt(coeff, mid)) {
coeff := add(coeff, toAdd)
}
// Store result in the coefficients array
mstore(add(coefficients, add(0x20, mul(0x20, i))), coeff)
i := add(i, 1)
}
}
}
function formatVolatilitySurfaceCoefficients(int256[5] memory coefficients)
internal
pure
returns (bytes32 result)
{
for (uint256 i = 0; i < COEFF_AMOUNT; i++) {
int256 max = int256(1 << COEFF_BITS_MINUS_ONE);
require(
coefficients[i] < max && coefficients[i] > -max,
"Out of bounds"
);
}
assembly {
let i := 0
for {
} lt(i, COEFF_AMOUNT) {
} {
let offset := sub(START_BIT, mul(COEFF_BITS, i))
let coeff := mload(add(coefficients, mul(0x20, i)))
result := add(
result,
shl(
offset,
sub(coeff, shl(COEFF_BITS, shr(COEFF_BITS, coeff)))
)
)
i := add(i, 1)
}
}
}
}
|
@inheritdoc IPoolView/
|
function getPoolSettings()
external
view
override
returns (PoolStorage.PoolSettings memory)
{
PoolStorage.Layout storage l = PoolStorage.layout();
return
PoolStorage.PoolSettings(
l.underlying,
l.base,
l.underlyingOracle,
l.baseOracle
);
}
| 14,528,659
|
pragma solidity ^0.4.24;
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;
}
}
contract ApproveAndCallReceiver {
function receiveApproval(
address _from,
uint256 _amount,
address _token,
bytes _data
) public;
}
//normal contract. already compiled as bin
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
//block for check//bool private initialed = false;
address public controller;
constructor() public {
controller = msg.sender;
}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
//abstract contract. used for interface
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) payable public returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @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) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @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) public returns(bool);
}
contract ERC20Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
//function totalSupply() public constant returns (uint256 balance);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
mapping (address => uint256) public balanceOf;
//function balanceOf(address _owner) public constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
mapping (address => mapping (address => uint256)) public allowance;
//function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract TokenI is ERC20Token, Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals = 18; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
// ERC20 Methods
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(
address _spender,
uint256 _amount,
bytes _extraData
) public returns (bool success);
// Generate and destroy tokens
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount) public returns (bool);
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) public returns (bool);
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public;
// Safety Methods
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _tokens The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
/// @param _to The address of the token will be send. e.g. some user or exchange
function claimTokens(address[] _tokens, address _to) public;
// Events
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
}
contract Token is TokenI {
using SafeMath for uint256;
string public techProvider = "WeYii Tech";
string public officialSite = "http://www.beautybloc.io";
//owner是最初的币持有者。对比之下,controller 是合约操作者
address public owner;
struct FreezeInfo {
address user;
uint256 amount;
}
//Key1: step(募资阶段); Key2: user sequence(用户序列)
mapping (uint8 => mapping (uint32 => FreezeInfo)) public freezeOf; //所有锁仓,key 使用序号向上增加,方便程序查询。
mapping (uint8 => uint32) public lastFreezeSeq; //最后的 freezeOf 键值。key: step; value: sequence
bool public transfersEnabled = true;
/* This generates a public event on the blockchain that will notify clients */
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
event TransferMulti(uint256 userLen, uint256 valueAmount);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
address initialOwner
) public {
owner = initialOwner;
totalSupply = initialSupply * uint256(10) ** decimals;
balanceOf[owner] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier ownerOrController() {
require(msg.sender == owner || msg.sender == controller);
_;
}
modifier transable(){
require(transfersEnabled == true);
_;
}
modifier realUser(address user){
require(user != 0x0);
_;
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) {
return false;
}
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/* Send coins */
function transfer(address _to, uint256 _value) realUser(_to) transable public returns (bool) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) transable public returns (bool success) {
require(_value == 0 || (allowance[msg.sender][_spender] == 0));
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @notice `msg.sender` approves `_spender` to send `_amount` tokens on
* its behalf, and then a function is triggered in the contract that is
* being approved, `_spender`. This allows users to use their tokens to
* interact with contracts in one function call instead of two
* @param _spender The address of the contract able to transfer the tokens
* @param _amount The amount of tokens to be approved for transfer
* @return True if the function call was successful
*/
function approveAndCall(address _spender, uint256 _amount, bytes _extraData) transable public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallReceiver(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) realUser(_from) realUser(_to) transable public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the sender has enough
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function transferMulti(address[] _to, uint256[] _value) transable public returns (uint256 amount){
require(_to.length == _value.length && _to.length <= 1024);
uint256 balanceOfSender = balanceOf[msg.sender];
uint256 len = _to.length;
for(uint256 j; j<len; j++){
amount = amount.add(_value[j]);
}
balanceOf[msg.sender] = balanceOfSender.sub(amount);
address _toI;
uint256 _valueI;
for(uint256 i; i<len; i++){
_toI = _to[i];
_valueI = _value[i];
balanceOf[_toI] = balanceOf[_toI].add(_valueI);
emit Transfer(msg.sender, _toI, _valueI);
}
emit TransferMulti(len, amount);
}
//对多人按相同数量转账
function transferMultiSameVaule(address[] _to, uint256 _value) transable public returns (bool success){
uint256 len = _to.length;
uint256 amount = _value.mul(len);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); //this will check enough automatically
address _toI;
for(uint256 i; i<len; i++){
_toI = _to[i];
balanceOf[_toI] = balanceOf[_toI].add(_value);
emit Transfer(msg.sender, _toI, _value);
}
emit TransferMulti(len, amount);
return true;
}
//只owner和controller 才能冻结账户
function freeze(address _user, uint256 _value, uint8 _step) ownerOrController public returns (bool success) {
require(balanceOf[_user] >= _value);
balanceOf[_user] = balanceOf[_user] - _value;
freezeOf[_step][lastFreezeSeq[_step]] = FreezeInfo({user:_user, amount:_value});
lastFreezeSeq[_step]++;
emit Freeze(_user, _value);
return true;
}
//为用户解锁账户资金
function unFreeze(uint8 _step) ownerOrController public returns (bool unlockOver) {
uint32 _end = lastFreezeSeq[_step];
require(_end > 0);
unlockOver = (_end <= 99);
uint32 _start = (_end > 99) ? _end-100 : 0;
for(; _end>_start; _end--){
FreezeInfo storage fInfo = freezeOf[_step][_end-1];
uint256 _amount = fInfo.amount;
balanceOf[fInfo.user] += _amount;
delete freezeOf[_step][_end-1];
lastFreezeSeq[_step]--;
emit Unfreeze(fInfo.user, _amount);
}
}
//accept ether
function() payable public {
//屏蔽控制方的合约类型检查,以兼容发行方无控制合约的情况。
require(isContract(controller));
bool proxyPayment = TokenController(controller).proxyPayment.value(msg.value)(msg.sender);
require(proxyPayment);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _user The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _user, uint _amount) onlyController public returns (bool) {
require(balanceOf[owner] >= _amount);
balanceOf[_user] += _amount;
balanceOf[owner] -= _amount;
emit Transfer(0, _user, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _user The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _user, uint _amount) onlyController public returns (bool) {
require(balanceOf[_user] >= _amount);
balanceOf[owner] += _amount;
balanceOf[_user] -= _amount;
emit Transfer(_user, 0, _amount);
emit Burn(_user, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) ownerOrController public {
transfersEnabled = _transfersEnabled;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// set to 0 in case you want to extract ether.
function claimTokens(address[] tokens, address to) onlyOwner public {
if(to == 0x0){
to = owner;
}
address _token;
uint256 balance;
uint256 len = tokens.length;
for(uint256 i; i<len; i++){
_token = tokens[i];
if (_token == 0x0) {
balance = address(this).balance;
if(balance > 0){
to.transfer(balance);
}
}else{
ERC20Token token = ERC20Token(_token);
balance = token.balanceOf(address(this));
token.transfer(to, balance);
emit ClaimedTokens(_token, to, balance);
}
}
}
function changeOwner(address newOwner) onlyOwner public returns (bool) {
balanceOf[newOwner] = balanceOf[owner].add(balanceOf[newOwner]);
balanceOf[owner] = 0;
owner = newOwner;
return true;
}
}
|
This method can be used by the controller to extract mistakenly sent tokens to this contract. set to 0 in case you want to extract ether.
|
function claimTokens(address[] tokens, address to) onlyOwner public {
if(to == 0x0){
to = owner;
}
address _token;
uint256 balance;
uint256 len = tokens.length;
for(uint256 i; i<len; i++){
_token = tokens[i];
if (_token == 0x0) {
balance = address(this).balance;
if(balance > 0){
to.transfer(balance);
}
ERC20Token token = ERC20Token(_token);
balance = token.balanceOf(address(this));
token.transfer(to, balance);
emit ClaimedTokens(_token, to, balance);
}
}
}
| 2,188,657
|
./partial_match/1313161554/0x6190CDe6c42c460C335515A585DF253bEd51Cfdd/sources/ClustersLockSplitted.sol
|
Deposit (stake) ASSET tokens _pid Pool's id _amount Amount to stake
|
function deposit(uint256 _pid, uint256 _amount) public payable virtual nonReentrant hasPool(_pid) poolRunning(_pid) {
updatePool(_pid);
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
if (user.rewardsDebts.length == 0 && pool.rewardsTokens.length > 0) {
user.rewardsDebts = new uint256[](pool.rewardsTokens.length);
uint256 diff = pool.rewardsTokens.length - user.rewardsDebts.length;
for (uint256 i = 0; i < diff; i++) {
user.rewardsDebts.push(0);
}
}
uint256 poolAmountBefore = user.amount;
user.amount += _amount;
for (uint256 i = 0; i < pool.rewardsTokens.length; i++) {
_updateUserInfo(pool, user, i, poolAmountBefore, _msgSender());
}
poolInfo[_pid].poolSupply += _amount;
IERC20(pool.assetToken).safeTransferFrom(_msgSender(), address(this), _amount);
emit Deposit(_msgSender(), _pid, _amount);
}
| 16,923,319
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
contract PublicSalesActivation is Ownable {
uint256 public publicSalesStartTime;
modifier isPublicSalesActive() {
require(
isPublicSalesActivated(),
"PublicSalesActivation: Sale is not activated"
);
_;
}
constructor() {}
function isPublicSalesActivated() public view returns (bool) {
return
publicSalesStartTime > 0 && block.timestamp >= publicSalesStartTime;
}
// 1644069600: start time at 05 Feb 2022 (2 PM UTC+0) in seconds
function setPublicSalesTime(uint256 _startTime) external onlyOwner {
publicSalesStartTime = _startTime;
}
}
|
1644069600: start time at 05 Feb 2022 (2 PM UTC+0) in seconds
|
function setPublicSalesTime(uint256 _startTime) external onlyOwner {
publicSalesStartTime = _startTime;
}
| 1,031,592
|
//Address: 0xf4dec7c97afd5a2f03088513cc57cc2e48a7c5e5
//Contract name: VirtuePokerSale
//Balance: 0 Ether
//Verification Date: 4/20/2018
//Transacion Count: 656
// CODE STARTS HERE
pragma solidity 0.4.19;
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @tokenfoundry/sale-contracts/contracts/DisbursementHandler.sol
/// @title Disbursement handler - Manages time locked disbursements of ERC20 tokens
contract DisbursementHandler is Ownable {
using SafeMath for uint256;
struct Disbursement {
// Tokens cannot be withdrawn before this timestamp
uint256 timestamp;
// Amount of tokens to be disbursed
uint256 tokens;
}
event LogSetup(address indexed vestor, uint256 timestamp, uint256 tokens);
event LogWithdraw(address indexed to, uint256 value);
ERC20 public token;
uint256 public totalAmount;
mapping(address => Disbursement[]) public disbursements;
mapping(address => uint256) public withdrawnTokens;
function DisbursementHandler(address _token) public {
token = ERC20(_token);
}
/// @dev Called by the sale contract to create a disbursement.
/// @param vestor The address of the beneficiary.
/// @param tokens Amount of tokens to be locked.
/// @param timestamp Funds will be locked until this timestamp.
function setupDisbursement(
address vestor,
uint256 tokens,
uint256 timestamp
)
external
onlyOwner
{
require(block.timestamp < timestamp);
disbursements[vestor].push(Disbursement(timestamp, tokens));
totalAmount = totalAmount.add(tokens);
LogSetup(vestor, timestamp, tokens);
}
/// @dev Transfers tokens to the withdrawer
function withdraw()
external
{
uint256 withdrawAmount = calcMaxWithdraw(msg.sender);
require(withdrawAmount != 0);
withdrawnTokens[msg.sender] = withdrawnTokens[msg.sender].add(withdrawAmount);
require(token.transfer(msg.sender, withdrawAmount));
LogWithdraw(msg.sender, withdrawAmount);
}
/// @dev Calculates the maximum amount of vested tokens
/// @return Number of vested tokens that can be withdrawn
function calcMaxWithdraw(address beneficiary)
public
view
returns (uint256)
{
uint256 maxTokens = 0;
// Go over all the disbursements and calculate how many tokens can be withdrawn
Disbursement[] storage temp = disbursements[beneficiary];
uint256 tempLength = temp.length;
for (uint256 i = 0; i < tempLength; i++) {
if (block.timestamp > temp[i].timestamp) {
maxTokens = maxTokens.add(temp[i].tokens);
}
}
// Return the computed amount minus the tokens already withdrawn
return maxTokens.sub(withdrawnTokens[beneficiary]);
}
}
// File: zeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// File: @tokenfoundry/sale-contracts/contracts/Vault.sol
// Adapted from Open Zeppelin's RefundVault
/**
* @title Vault
* @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 Vault is Ownable {
using SafeMath for uint256;
enum State { Active, Success, Refunding, Closed }
uint256 public constant DISBURSEMENT_DURATION = 4 weeks;
mapping (address => uint256) public deposited;
uint256 public disbursementAmount; // The amount to be disbursed to the wallet every month
address public trustedWallet; // Wallet from the project team
uint256 public initialAmount; // The eth amount the team will get initially if the sale is successful
uint256 public lastDisbursement; // Timestamp of the last disbursement made
uint256 public totalDeposited; // Total amount that was deposited
uint256 public refundable; // Amount that can be refunded
uint256 public closingDuration;
uint256 public closingDeadline; // Vault can't be closed before this deadline
State public state;
event LogClosed();
event LogRefundsEnabled();
event LogRefunded(address indexed contributor, uint256 amount);
modifier atState(State _state) {
require(state == _state);
_;
}
function Vault(
address wallet,
uint256 _initialAmount,
uint256 _disbursementAmount,
uint256 _closingDuration
)
public
{
require(wallet != address(0));
require(_disbursementAmount != 0);
require(_closingDuration != 0);
trustedWallet = wallet;
initialAmount = _initialAmount;
disbursementAmount = _disbursementAmount;
closingDuration = _closingDuration;
state = State.Active;
}
/// @dev Called by the sale contract to deposit ether for a contributor.
function deposit(address contributor) onlyOwner external payable {
require(state == State.Active || state == State.Success);
totalDeposited = totalDeposited.add(msg.value);
refundable = refundable.add(msg.value);
deposited[contributor] = deposited[contributor].add(msg.value);
}
/// @dev Sends initial funds to the wallet.
function saleSuccessful() onlyOwner external atState(State.Active){
state = State.Success;
refundable = refundable.sub(initialAmount);
if (initialAmount != 0) {
trustedWallet.transfer(initialAmount);
}
}
/// @dev Called by the owner if the project didn't deliver the testnet contracts or if we need to stop disbursements for any reasone.
function enableRefunds() onlyOwner external {
state = State.Refunding;
LogRefundsEnabled();
}
/// @dev Refunds ether to the contributors if in the Refunding state.
function refund(address contributor) external atState(State.Refunding) {
uint256 refundAmount = deposited[contributor].mul(refundable).div(totalDeposited);
deposited[contributor] = 0;
contributor.transfer(refundAmount);
LogRefunded(contributor, refundAmount);
}
/// @dev Sets the closingDeadline variable
function beginClosingPeriod() external onlyOwner atState(State.Success) {
require(closingDeadline == 0);
closingDeadline = now.add(closingDuration);
}
/// @dev Called by anyone if the sale was successful and the project delivered.
function close() external atState(State.Success) {
require(closingDeadline != 0 && closingDeadline <= now);
state = State.Closed;
LogClosed();
}
/// @dev Sends the disbursement amount to the wallet after the disbursement period has passed. Can be called by anyone.
function sendFundsToWallet() external atState(State.Closed) {
require(lastDisbursement.add(DISBURSEMENT_DURATION) <= now);
lastDisbursement = now;
uint256 amountToSend = Math.min256(address(this).balance, disbursementAmount);
refundable = amountToSend > refundable ? 0 : refundable.sub(amountToSend);
trustedWallet.transfer(amountToSend);
}
}
// File: @tokenfoundry/sale-contracts/contracts/Whitelistable.sol
/**
* @title Whitelistable
* @dev This contract is used to implement a signature based whitelisting mechanism
*/
contract Whitelistable is Ownable {
bytes constant PREFIX = "\x19Ethereum Signed Message:\n32";
address public whitelistAdmin;
// addresses map to false by default
mapping(address => bool) public blacklist;
event LogAdminUpdated(address indexed newAdmin);
modifier validAdmin(address _admin) {
require(_admin != 0);
_;
}
modifier onlyAdmin {
require(msg.sender == whitelistAdmin);
_;
}
/// @dev Constructor for Whitelistable contract
/// @param _admin the address of the admin that will generate the signatures
function Whitelistable(address _admin) public validAdmin(_admin) {
whitelistAdmin = _admin;
}
/// @dev Updates whitelistAdmin address
/// @dev Can only be called by the current owner
/// @param _admin the new admin address
function changeAdmin(address _admin)
external
onlyOwner
validAdmin(_admin)
{
LogAdminUpdated(_admin);
whitelistAdmin = _admin;
}
// @dev blacklists the given address to ban them from contributing
// @param _contributor Address of the contributor to blacklist
function addToBlacklist(address _contributor)
external
onlyAdmin
{
blacklist[_contributor] = true;
}
// @dev removes a previously blacklisted contributor from the blacklist
// @param _contributor Address of the contributor remove
function removeFromBlacklist(address _contributor)
external
onlyAdmin
{
blacklist[_contributor] = false;
}
/// @dev Checks if contributor is whitelisted (main Whitelistable function)
/// @param contributor Address of who was whitelisted
/// @param contributionLimit Limit for the user contribution
/// @param currentSaleCap Cap of contributions to the sale at the current point in time
/// @param v Recovery id
/// @param r Component of the ECDSA signature
/// @param s Component of the ECDSA signature
/// @return Is the signature correct?
function checkWhitelisted(
address contributor,
uint256 contributionLimit,
uint256 currentSaleCap,
uint8 v,
bytes32 r,
bytes32 s
) public view returns(bool) {
bytes32 prefixed = keccak256(PREFIX, keccak256(contributor, contributionLimit, currentSaleCap));
return !(blacklist[contributor]) && (whitelistAdmin == ecrecover(prefixed, v, r, s));
}
}
// File: @tokenfoundry/state-machine/contracts/StateMachine.sol
contract StateMachine {
struct State {
bytes32 nextStateId;
mapping(bytes4 => bool) allowedFunctions;
function() internal[] transitionCallbacks;
function(bytes32) internal returns(bool)[] startConditions;
}
mapping(bytes32 => State) states;
// The current state id
bytes32 private currentStateId;
event LogTransition(bytes32 stateId, uint256 blockNumber);
/* This modifier performs the conditional transitions and checks that the function
* to be executed is allowed in the current State
*/
modifier checkAllowed {
conditionalTransitions();
require(states[currentStateId].allowedFunctions[msg.sig]);
_;
}
///@dev transitions the state machine into the state it should currently be in
///@dev by taking into account the current conditions and how many further transitions can occur
function conditionalTransitions() public {
bytes32 next = states[currentStateId].nextStateId;
bool stateChanged;
while (next != 0) {
// If one of the next state's conditions is met, go to this state and continue
stateChanged = false;
for (uint256 i = 0; i < states[next].startConditions.length; i++) {
if (states[next].startConditions[i](next)) {
goToNextState();
next = states[next].nextStateId;
stateChanged = true;
break;
}
}
// If none of the next state's conditions are met, then we are in the right current state
if (!stateChanged) break;
}
}
function getCurrentStateId() view public returns(bytes32) {
return currentStateId;
}
/// @dev Setup the state machine with the given states.
/// @param _stateIds Array of state ids.
function setStates(bytes32[] _stateIds) internal {
require(_stateIds.length > 0);
require(currentStateId == 0);
require(_stateIds[0] != 0);
currentStateId = _stateIds[0];
for (uint256 i = 1; i < _stateIds.length; i++) {
require(_stateIds[i] != 0);
states[_stateIds[i - 1]].nextStateId = _stateIds[i];
// Check that the state appears only once in the array
require(states[_stateIds[i]].nextStateId == 0);
}
}
/// @dev Allow a function in the given state.
/// @param _stateId The id of the state
/// @param _functionSelector A function selector (bytes4[keccak256(functionSignature)])
function allowFunction(bytes32 _stateId, bytes4 _functionSelector) internal {
states[_stateId].allowedFunctions[_functionSelector] = true;
}
/// @dev Goes to the next state if possible (if the next state is valid)
function goToNextState() internal {
bytes32 next = states[currentStateId].nextStateId;
require(next != 0);
currentStateId = next;
for (uint256 i = 0; i < states[next].transitionCallbacks.length; i++) {
states[next].transitionCallbacks[i]();
}
LogTransition(next, block.number);
}
///@dev add a function returning a boolean as a start condition for a state
///@param _stateId The ID of the state to add the condition for
///@param _condition Start condition function - returns true if a start condition (for a given state ID) is met
function addStartCondition(bytes32 _stateId, function(bytes32) internal returns(bool) _condition) internal {
states[_stateId].startConditions.push(_condition);
}
///@dev add a callback function for a state
///@param _stateId The ID of the state to add a callback function for
///@param _callback The callback function to add
function addCallback(bytes32 _stateId, function() internal _callback) internal {
states[_stateId].transitionCallbacks.push(_callback);
}
}
// File: @tokenfoundry/state-machine/contracts/TimedStateMachine.sol
/// @title A contract that implements the state machine pattern and adds time dependant transitions.
contract TimedStateMachine is StateMachine {
event LogSetStateStartTime(bytes32 indexed _stateId, uint256 _startTime);
// Stores the start timestamp for each state (the value is 0 if the state doesn't have a start timestamp).
mapping(bytes32 => uint256) private startTime;
/// @dev Returns the timestamp for the given state id.
/// @param _stateId The id of the state for which we want to set the start timestamp.
function getStateStartTime(bytes32 _stateId) public view returns(uint256) {
return startTime[_stateId];
}
/// @dev Sets the starting timestamp for a state.
/// @param _stateId The id of the state for which we want to set the start timestamp.
/// @param _timestamp The start timestamp for the given state. It should be bigger than the current one.
function setStateStartTime(bytes32 _stateId, uint256 _timestamp) internal {
require(block.timestamp < _timestamp);
if (startTime[_stateId] == 0) {
addStartCondition(_stateId, hasStartTimePassed);
}
startTime[_stateId] = _timestamp;
LogSetStateStartTime(_stateId, _timestamp);
}
function hasStartTimePassed(bytes32 _stateId) internal returns(bool) {
return startTime[_stateId] <= block.timestamp;
}
}
// File: @tokenfoundry/token-contracts/contracts/TokenControllerI.sol
/// @title Interface for token controllers. The controller specifies whether a transfer can be done.
contract TokenControllerI {
/// @dev Specifies whether a transfer is allowed or not.
/// @return True if the transfer is allowed
function transferAllowed(address _from, address _to) external view returns (bool);
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: @tokenfoundry/token-contracts/contracts/ControllableToken.sol
/**
* @title Controllable ERC20 token
*
* @dev Token that queries a token controller contract to check if a transfer is allowed.
* @dev controller state var is going to be set with the address of a TokenControllerI contract that has
* implemented transferAllowed() function.
*/
contract ControllableToken is Ownable, StandardToken {
TokenControllerI public controller;
/// @dev Executes transferAllowed() function from the Controller.
modifier isAllowed(address _from, address _to) {
require(controller.transferAllowed(_from, _to));
_;
}
/// @dev Sets the controller that is going to be used by isAllowed modifier
function setController(TokenControllerI _controller) onlyOwner public {
require(_controller != address(0));
controller = _controller;
}
/// @dev It calls parent BasicToken.transfer() function. It will transfer an amount of tokens to an specific address
/// @return True if the token is transfered with success
function transfer(address _to, uint256 _value) isAllowed(msg.sender, _to) public returns (bool) {
return super.transfer(_to, _value);
}
/// @dev It calls parent StandardToken.transferFrom() function. It will transfer from an address a certain amount of tokens to another address
/// @return True if the token is transfered with success
function transferFrom(address _from, address _to, uint256 _value) isAllowed(_from, _to) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
// File: zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: @tokenfoundry/token-contracts/contracts/Token.sol
/**
* @title Token base contract - Defines basic structure for a token
*
* @dev ControllableToken is a StandardToken, an OpenZeppelin ERC20 implementation library. DetailedERC20 is also an OpenZeppelin contract.
* More info about them is available here: https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token/ERC20
*/
contract Token is ControllableToken, DetailedERC20 {
/**
* @dev Transfer is an event inherited from ERC20Basic.sol interface (OpenZeppelin).
* @param _supply Total supply of tokens.
* @param _name Is the long name by which the token contract should be known
* @param _symbol The set of capital letters used to represent the token e.g. DTH.
* @param _decimals The number of decimal places the tokens can be split up into. This should be between 0 and 18.
*/
function Token(
uint256 _supply,
string _name,
string _symbol,
uint8 _decimals
) DetailedERC20(_name, _symbol, _decimals) public {
require(_supply != 0);
totalSupply_ = _supply;
balances[msg.sender] = _supply;
Transfer(address(0), msg.sender, _supply); //event
}
}
// File: @tokenfoundry/sale-contracts/contracts/Sale.sol
/// @title Sale base contract
contract Sale is Ownable, Whitelistable, TimedStateMachine, TokenControllerI {
using SafeMath for uint256;
// State machine states
bytes32 private constant SETUP = 'setup';
bytes32 private constant FREEZE = 'freeze';
bytes32 private constant SALE_IN_PROGRESS = 'saleInProgress';
bytes32 private constant SALE_ENDED = 'saleEnded';
bytes32[] public states = [SETUP, FREEZE, SALE_IN_PROGRESS, SALE_ENDED];
// Stores the contribution for each user
mapping(address => uint256) public contributions;
// Records which users have contributed throughout the sale
mapping(address => bool) public hasContributed;
DisbursementHandler public disbursementHandler;
uint256 public weiContributed = 0;
uint256 public totalSaleCap;
uint256 public minContribution;
uint256 public minThreshold;
// How many tokens a user will receive per each wei contributed
uint256 public tokensPerWei;
uint256 public tokensForSale;
Token public trustedToken;
Vault public trustedVault;
event LogContribution(address indexed contributor, uint256 value, uint256 excess);
event LogTokensAllocated(address indexed contributor, uint256 amount);
function Sale(
uint256 _totalSaleCap,
uint256 _minContribution,
uint256 _minThreshold,
uint256 _maxTokens,
address _whitelistAdmin,
address _wallet,
uint256 _closingDuration,
uint256 _vaultInitialAmount,
uint256 _vaultDisbursementAmount,
uint256 _startTime,
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals
)
Whitelistable(_whitelistAdmin)
public
{
require(_totalSaleCap != 0);
require(_maxTokens != 0);
require(_wallet != 0);
require(_minThreshold <= _totalSaleCap);
require(_vaultInitialAmount <= _minThreshold);
require(now < _startTime);
totalSaleCap = _totalSaleCap;
minContribution = _minContribution;
minThreshold = _minThreshold;
// Setup the necessary contracts
trustedToken = new Token(_maxTokens, _tokenName, _tokenSymbol, _tokenDecimals);
disbursementHandler = new DisbursementHandler(trustedToken);
trustedToken.setController(this);
trustedVault = new Vault(
_wallet,
_vaultInitialAmount,
_vaultDisbursementAmount, // disbursement amount
_closingDuration
);
// Set the states
setStates(states);
allowFunction(SETUP, this.setup.selector);
allowFunction(FREEZE, this.setEndTime.selector);
allowFunction(SALE_IN_PROGRESS, this.setEndTime.selector);
allowFunction(SALE_IN_PROGRESS, this.contribute.selector);
allowFunction(SALE_IN_PROGRESS, this.endSale.selector);
allowFunction(SALE_ENDED, this.allocateTokens.selector);
// End the sale when the cap is reached
addStartCondition(SALE_ENDED, wasCapReached);
// Set the onSaleEnded callback (will be called when the sale ends)
addCallback(SALE_ENDED, onSaleEnded);
// Set the start and end times for the sale
setStateStartTime(SALE_IN_PROGRESS, _startTime);
}
/// @dev Setup the disbursements and tokens for sale.
/// @dev This needs to be outside the constructor because the token needs to query the sale for allowed transfers.
function setup() public onlyOwner checkAllowed {
require(trustedToken.transfer(disbursementHandler, disbursementHandler.totalAmount()));
tokensForSale = trustedToken.balanceOf(this);
require(tokensForSale >= totalSaleCap);
// Go to freeze state
goToNextState();
}
/// @dev Called by users to contribute ETH to the sale.
function contribute(uint256 contributionLimit, uint256 currentSaleCap, uint8 v, bytes32 r, bytes32 s)
external
payable
checkAllowed
{
// Check that the signature is valid
require(currentSaleCap <= totalSaleCap);
require(weiContributed < currentSaleCap);
require(checkWhitelisted(msg.sender, contributionLimit, currentSaleCap, v, r, s));
uint256 current = contributions[msg.sender];
require(current < contributionLimit);
// Get the max amount that the user can contribute
uint256 remaining = Math.min256(contributionLimit.sub(current), currentSaleCap.sub(weiContributed));
// Check if it goes over the contribution limit of the user or the eth cap.
uint256 contribution = Math.min256(msg.value, remaining);
// Get the total contribution for the contributor after the previous checks
uint256 totalContribution = current.add(contribution);
require(totalContribution >= minContribution);
contributions[msg.sender] = totalContribution;
hasContributed[msg.sender] = true;
weiContributed = weiContributed.add(contribution);
trustedVault.deposit.value(contribution)(msg.sender);
if (weiContributed >= minThreshold && trustedVault.state() != Vault.State.Success) trustedVault.saleSuccessful();
// If there is an excess, return it to the user
uint256 excess = msg.value.sub(contribution);
if (excess > 0) msg.sender.transfer(excess);
LogContribution(msg.sender, contribution, excess);
assert(totalContribution <= contributionLimit);
}
/// @dev Sets the end time for the sale
/// @param _endTime The timestamp at which the sale will end.
function setEndTime(uint256 _endTime) external onlyOwner checkAllowed {
require(now < _endTime);
require(getStateStartTime(SALE_ENDED) == 0);
setStateStartTime(SALE_ENDED, _endTime);
}
/// @dev Called to allocate the tokens depending on eth contributed by the end of the sale.
/// @param _contributor The address of the contributor.
function allocateTokens(address _contributor) external checkAllowed {
require(contributions[_contributor] != 0);
// Transfer the respective tokens to the contributor
uint256 amount = contributions[_contributor].mul(tokensPerWei);
// Set contributions to 0
contributions[_contributor] = 0;
require(trustedToken.transfer(_contributor, amount));
LogTokensAllocated(_contributor, amount);
}
/// @dev Called to end the sale by the owner. Can only be called in SALE_IN_PROGRESS state
function endSale() external onlyOwner checkAllowed {
goToNextState();
}
/// @dev Since Sale is TokenControllerI, it has to implement transferAllowed() function
/// @notice only the Sale and DisbursementHandler can disburse the initial tokens to their future owners
function transferAllowed(address _from, address) external view returns (bool) {
return _from == address(this) || _from == address(disbursementHandler);
}
/// @dev Called internally by the sale to setup a disbursement (it has to be called in the constructor of child sales)
/// param _beneficiary Tokens will be disbursed to this address.
/// param _amount Number of tokens to be disbursed.
/// param _duration Tokens will be locked for this long.
function setupDisbursement(address _beneficiary, uint256 _amount, uint256 _duration) internal {
require(tokensForSale == 0);
disbursementHandler.setupDisbursement(_beneficiary, _amount, now.add(_duration));
}
/// @dev Returns true if the cap was reached.
function wasCapReached(bytes32) internal returns (bool) {
return totalSaleCap <= weiContributed;
}
/// @dev Callback that gets called when entering the SALE_ENDED state.
function onSaleEnded() internal {
// If the minimum threshold wasn't reached, enable refunds
if (weiContributed < minThreshold) {
trustedVault.enableRefunds();
} else {
trustedVault.beginClosingPeriod();
tokensPerWei = tokensForSale.div(weiContributed);
}
trustedToken.transferOwnership(owner);
trustedVault.transferOwnership(owner);
}
}
// File: contracts/VirtuePokerSale.sol
contract VirtuePokerSale is Sale {
function VirtuePokerSale()
Sale(
25000 ether, // Total sale cap
1 ether, // Min contribution
12000 ether, // Min threshold
500000000 * (10 ** 18), // Max tokens
0x13ebf15f2e32d05ea944927ef5e6a3cad8187440, // Whitelist Admin
0xaa0aE3459F9f3472d1237015CaFC1aAfc6F03C63, // Wallet
28 days, // Closing duration
12000 ether, // Vault initial amount
25000 ether, // Vault disbursement amount
1524218400, // Start time
"Virtue Player Points", // Token name
"VPP", // Token symbol
18 // Token decimals
)
public
{
// Team Wallet (50,000,000 VPP, 25% per year)
setupDisbursement(0x2e286dA6Ee6E8e0Afb2c1CfADb1B74669a3cD642, 12500000 * (10 ** 18), 1 years);
setupDisbursement(0x2e286dA6Ee6E8e0Afb2c1CfADb1B74669a3cD642, 12500000 * (10 ** 18), 2 years);
setupDisbursement(0x2e286dA6Ee6E8e0Afb2c1CfADb1B74669a3cD642, 12500000 * (10 ** 18), 3 years);
setupDisbursement(0x2e286dA6Ee6E8e0Afb2c1CfADb1B74669a3cD642, 12500000 * (10 ** 18), 4 years);
// Company Wallet (250,000,000 VPP, no lock-up)
setupDisbursement(0xaa0aE3459F9f3472d1237015CaFC1aAfc6F03C63, 250000000 * (10 ** 18), 1 days);
// Founder Allocations (total 100,000,000, 12.5% per 6 months)
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 0.5 years);
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 1 years);
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 1.5 years);
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 2 years);
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 2.5 years);
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 3 years);
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 3.5 years);
setupDisbursement(0x5ca71f050865092468CF8184D09e087F3DC58e31, 8000000 * (10 ** 18), 4 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 0.5 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 1 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 1.5 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 2 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 2.5 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 3 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 3.5 years);
setupDisbursement(0x35fc8cA81E1b5992a0727c6Aa87DbeB8cca42094, 2250000 * (10 ** 18), 4 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 0.5 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 1 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 1.5 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 2 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 2.5 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 3 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 3.5 years);
setupDisbursement(0xce3EFA6763e23DF21aF74DA46C6489736F96d4B6, 2250000 * (10 ** 18), 4 years);
}
}
|
Constructor for Whitelistable contract _admin the address of the admin that will generate the signatures
|
function Whitelistable(address _admin) public validAdmin(_admin) {
whitelistAdmin = _admin;
}
| 1,021,685
|
./full_match/43113/0x2471875E6379E9ec286A7de42F8c9262E521A14a/sources/project_/contracts/BaseContracts/BaseNft.sol
|
Use this to drain balance if needed drainTo address Address to send balance to (in the event admin drains to multisig etc)/
|
function drainBalance(address drainTo) external onlyRole(ADMIN) {
payable(drainTo).transfer(payable(address(this)).balance);
}
| 7,121,251
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./Ownable.sol";
import "./Counters.sol";
import "./CryptoCatsV1Contract.sol";
/**
* @title CryptoCatsV1Wrapper contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation.
* based on the V1 wrapper of @author @foobar, but optimised to work with our MarketPlace contract.
* @author @cryptotato
*/
contract CryptoCatsV1Wrapper is Ownable, ERC721 {
address payable public catAddress = payable(0x19c320b43744254ebdBcb1F1BD0e2a3dc08E01dc);
string private _baseTokenURI;
uint256 private _tokenSupply;
constructor() ERC721("V1 CryptoCats (Wrapped)", "WCCAT") {
_baseTokenURI = "ipfs://QmRKVBdB77hmrbJtbHq44RXDfP52V7u3UP8EzSNT4d2cc5/";
}
/**
* @dev Accepts an offer from the cats contract and assigns a wrapped token to msg.sender
*/
function wrap(uint _catId) external payable {
// Prereq: owner should call `offerCatForSaleToAddress` with price 0 (or higher if they wish)
(bool isForSale, , address seller, uint minPrice, address sellOnlyTo) = CryptoCatsV1Contract(catAddress).catsForSale(_catId);
require(isForSale == true);
require(seller == msg.sender);
require(minPrice == 0);
require((sellOnlyTo == address(this)) || (sellOnlyTo == address(0x0)));
// Buy the punk
CryptoCatsV1Contract(catAddress).buyCat{value: msg.value}(_catId);
_tokenSupply +=1;
// Mint a wrapped punk
_mint(msg.sender, _catId);
}
/**
* @dev Burns the wrapped token and transfers the underlying cat to the owner
**/
function unwrap(uint256 _catId) external {
require(_isApprovedOrOwner(msg.sender, _catId));
_burn(_catId);
_tokenSupply -=1;
CryptoCatsV1Contract(catAddress).transfer(msg.sender, _catId);
}
/**
* @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 override returns (string memory) {
return _baseTokenURI;
}
/**
* @dev Set a new base token URI
*/
function setBaseTokenURI(string memory __baseTokenURI) public onlyOwner {
_baseTokenURI = __baseTokenURI;
}
/**
* @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) external view virtual returns (bool) {
return _exists(tokenId);
}
/**
* @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 _tokenSupply;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
/**
* @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 "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./Address.sol";
import "./Context.sol";
import "./Strings.sol";
import "./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}. 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 || ERC721.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 || ERC721.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 {
// solhint-disable-next-line no-inline-assembly
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` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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;
interface CryptoCatsV1Contract {
// Events
event CatTransfer(address indexed from, address indexed to, uint catIndex);
event CatOffered(uint indexed catIndex, uint minPrice, address indexed toAddress);
event CatBought(uint indexed catIndex, uint price, address indexed fromAddress, address indexed toAddress);
event CatNoLongerForSale(uint indexed catIndex);
event Assign(address indexed to, uint256 catIndex);
event Transfer(address indexed from, address indexed to, uint256 value);
event ReleaseUpdate(uint256 indexed newCatsAdded, uint256 totalSupply, uint256 catPrice, string newImageHash);
event UpdateReleasePrice(uint32 releaseId, uint256 catPrice);
event UpdateAttribute(uint indexed attributeNumber, address indexed ownerAddress, bytes32 oldValue, bytes32 newValue);
// Read contract
function name() external view returns (string memory);
function catsForSale(uint id) external view returns (bool isForSale, uint catIndex, address seller, uint minPrice, address sellOnlyTo);
function _totalSupply() external view returns (uint);
function decimals() external view returns (uint8);
function imageHash() external view returns (string memory);
function catIndexToAddress(uint id) external view returns (address);
function standard() external view returns (string memory);
function balanceOf(address) external view returns (uint);
function symbol() external view returns (string memory);
function catsRemainingToAssign() external view returns (uint);
function pendingWithdrawals(address) external view returns (uint);
function previousContractAddress() external view returns (address);
function currentReleaseCeiling() external view returns (uint);
function totalSupplyIsLocked() external view returns (bool);
// Write contract
function withdraw() external;
function buyCat(uint catIndex) external payable;
function transfer(address _to, uint _value) external;
function offerCatForSaleToAddress(uint catIndex, uint minSalePriceInWei, address toAddress) external;
function offerCatForSale(uint catIndex, uint minSalePriceInWei) external;
function getCat(uint catIndex) external;
function catNoLongerForSale(uint catIndex) external;
function lockTotalSupply() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
}
}
}
}
|
Set a new base token URI/
|
function setBaseTokenURI(string memory __baseTokenURI) public onlyOwner {
_baseTokenURI = __baseTokenURI;
}
| 1,287,698
|
pragma solidity >=0.6.0 <0.7.0;
abstract contract Erc20 {
function approve(address, uint)virtual external returns (bool);
function transfer(address, uint)virtual external returns (bool);
function balanceOf(address owner)virtual external view returns (uint256 balance);
function transferFrom(address sender, address recipient, uint256 amount) virtual external returns (bool);
}
abstract contract CErc20 {
function approve(address, uint)virtual external returns (bool);
function mint(uint)virtual external returns (uint);
function balanceOfUnderlying(address account)virtual external returns (uint);
function totalReserves()virtual external returns (uint);
function transfer(address dst, uint amount) virtual external returns (bool);
function exchangeRateCurrent() virtual external returns (uint);
}
abstract contract CEth {
function mint()virtual external payable;
function balanceOfUnderlying(address account)virtual external returns (uint);
function balanceOf(address owner)virtual external view returns (uint256 balance);
function transfer(address dst, uint256 amount)virtual external returns (bool success);
function transferFrom(address src, address dst, uint wad)virtual external returns (bool);
function redeem(uint redeemTokens) virtual external returns (uint);
function exchangeRateCurrent() virtual external returns (uint);
}
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./compound/IERC20.sol";
import './compound/ComptrollerInterface.sol';
import './compound/CTokenInterface.sol';
import "./Safe/Ownable.sol";
import "./Safe/Pausable.sol";
contract Storage is Ownable, Pausable {
address internal daiContractAddress; // Contains Dai SmartContract address || 0x6B175474E89094C44Da98b954EedeAC495271d0F ||
address internal cDaiContractAddress; // Contains cDai SmartContract address || 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 ||
address internal cEthContractAddress; // Contains eEth SmartContract address || 0x4ddc2d193948926d02f9b1fe9e1daa0718270ed5 ||
uint256 public contractEtherBalance; // Total amount of Ether in contract
uint256 public contractDaiBalance; // Total amount of Dai in contract
uint256 public contractCethBalance; // Total amount of cEther in contract
uint256 public contractCdaiBalance; // Total amount of cDai in contract
bool public initialized;
// require sponsor
modifier isSponsor() {
require (sponsors[msg.sender].status == true);
_;
}
//@Dev-> multiple balances hold different tokens - be mindiful when coding
//Status: if sponsor is active == true
struct Sponsor {
// true if sponsor
bool status;
// sponsor ether balance
uint256 etherBalance;
// sponsor cEth balance
uint256 cEtherBalance;
// sponsor Dai balance
uint256 daiBalance;
// sponsor cDai balance
uint256 cDaiBalance;
// goal is the amount sponsor needs to reach to pay the selected course
uint256 goal;
// the id of the course the sponsor wants to pay
bytes32 courseId;
}
//@Dev-> student balance mult not change until a funding is completed
//Status: if student is active == true
struct Student {
bool status;
uint256 balance;
}
// address owner the one who registers the course
// unique id bytes32
// Status: if course is active == true
struct Course {
//course owner
address courseOwner;
//Price of the course
uint256 price;
// true if active
bool courseState;
uint64 id;
}
// mapping sponsors => address
mapping (address => Sponsor) internal sponsors;
// mapping students => address
mapping (address => Student) internal students;
// mapping courses => bytes32
mapping (bytes32 => Course) internal courses;
// Declare events for actions we may want to watch
event SponsorAction(address indexed sponsor, bytes32 action);
event NewDeposit(address indexed sponsor, uint256 amt);
event SponsorWithdrawal(address indexed sponsor, uint256 amt);
event OwnerChanged(address indexed owner, address indexed newOwner);
event academyWithdrawal(address indexed academy, uint256 amt);
event CourseCreated(address indexed academy, uint256 indexed course, uint256 indexed price);
event CourseRemoved(address indexed academy, uint256 indexed course, bytes32 action);
event ScholarshipCreated(uint256 indexed studentID, address indexed academy, uint256 indexed course);
event AcademyAction(address indexed academy, bytes32 action);
event CourseCreated (bytes32 courseId);
// GETTER METHODS - SPONSOR STRUCT
function getSponsorEtherBalance (address _address) public view returns (uint256) {
//@-> return Ether balance in sponsor struct
return sponsors[_address].etherBalance;
}
function getSponsorCetherBalance (address _address) public view returns (uint256) {
//@-> return cEther balance in sponsor struct
return sponsors[_address].cEtherBalance;
}
function getSponsorDaiBalance (address _address) public view returns (uint256) {
//@-> return Dai balance in sponsor struct
return sponsors[_address].daiBalance;
}
function getSponsorCdaiBalance(address _address) public view returns (uint256) {
//@-> return cDai balance in sponsor struct
return sponsors[_address].cDaiBalance;
}
function getSponsorStatus (address _address) public view returns (bool) {
//@-> return status in sponsor struct
return sponsors[_address].status;
}
// GETTER METHODS - STUDENT STRUCT
function getStudentBalance(address _academy) public view returns (uint256) {
//@-> return Ether balance in academy struct
return students[_academy].balance;
}
function getStudentStatus(address _academy) public view returns (bool) {
//@-> return status in academy struct
return students[_academy].status;
}
// GETTER METHODS - COURSE STRUCT
function getCourseOwner (bytes32 _courseId) public view returns (address) {
//@-> return owner in course struct
return courses[_courseId].courseOwner;
}
function getCoursePrice (bytes32 _courseId) public view returns (uint256) {
//@-> return owner in course struct
return courses[_courseId].price;
}
function getCourseState (bytes32 _courseId) public view returns (bool) {
//@-> return owner in course struct
return courses[_courseId].courseState;
}
//@-> Dev those are the setters for compound and erc20 token addresses
//@-> Notice! contract must be paused to allow setting a new address
// onlyOwner restricted
function setDAIcontractAddress (address _newDAIaddress) public onlyOwner whenPaused returns (address){
daiContractAddress = _newDAIaddress;
return daiContractAddress;
}
function setCDAIcontractAddress (address _newCDAIaddress) public onlyOwner whenPaused returns (address){
cDaiContractAddress = _newCDAIaddress;
return cDaiContractAddress;
}
function setCETHcontractAddress (address _newCETHaddress) public onlyOwner whenPaused returns (address){
cEthContractAddress = _newCETHaddress;
return cEthContractAddress;
}
}
|
@-> return owner in course struct
|
function getCoursePrice (bytes32 _courseId) public view returns (uint256) {
return courses[_courseId].price;
}
| 907,134
|
// SPDX-License-Identifier: MIT
import './abstract/ReaperBaseStrategy.sol';
import './interfaces/IExcaliburRouter.sol';
import './interfaces/IMasterChef.sol';
import './interfaces/IExcaliburV2Pair.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol';
pragma solidity 0.8.11;
/**
* @dev This strategy will farm LPs on Excalibur and autocompound rewards
*/
contract ReaperAutoCompoundExcaliburFarmer is ReaperBaseStrategy {
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* @dev Tokens Used:
* {WFTM} - Required for liquidity routing when doing swaps. Also used to charge fees on yield.
* {EXC} - Farm reward token
* {want} - The vault token the strategy is maximizing
* {lpToken0} - Token 0 of the LP want token
* {lpToken1} - Token 1 of the LP want token
*/
address public constant WFTM = 0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83;
address public constant EXC = 0x6e99e0676A90b2a5a722C44109db22220382cc9F;
address public want;
address public lpToken0;
address public lpToken1;
/**
* @dev Third Party Contracts:
* {MASTER_CHEF} - For depositing LP tokens and claiming farm rewards
* {EXCALIBUR_ROUTER} - Router for swapping tokens
*/
address public constant MASTER_CHEF = 0x70B9611f3cd33e686ee7535927cE420C2A111005;
address public constant EXCALIBUR_ROUTER = 0xc8Fe105cEB91e485fb0AC338F2994Ea655C78691;
/**
* @dev Strategy variables:
* {poolId} - For interacting with the MasterChef
*/
uint256 public poolId;
/**
* @dev Initializes the strategy. Sets parameters, saves routes, and gives allowances.
* @notice see documentation for each variable above its respective declaration.
*/
function initialize(
address _vault,
address[] memory _feeRemitters,
address[] memory _strategists,
address _want,
uint256 _poolId
) public initializer {
__ReaperBaseStrategy_init(_vault, _feeRemitters, _strategists);
want = _want;
poolId = _poolId;
lpToken0 = IExcaliburV2Pair(want).token0();
lpToken1 = IExcaliburV2Pair(want).token1();
_giveAllowances();
}
/**
* @dev Withdraws funds and sents them back to the vault.
* It withdraws {want} from the Excalibur MasterChef
* The available {want} minus fees is returned to the vault.
*/
function withdraw(uint256 _amount) external {
require(msg.sender == vault, '!vault');
require(_amount != 0, '0 amount');
require(_amount <= balanceOf(), 'invalid amount');
uint256 wantBal = IERC20Upgradeable(want).balanceOf(address(this));
if (wantBal < _amount) {
IMasterChef(MASTER_CHEF).withdraw(poolId, _amount - wantBal);
}
uint256 withdrawFee = (_amount * securityFee) / PERCENT_DIVISOR;
IERC20Upgradeable(want).safeTransfer(vault, _amount - withdrawFee);
}
/**
* @dev Returns the approx amount of profit from harvesting.
* Profit is denominated in WFTM, and takes fees into account.
*/
function estimateHarvest() external view override returns (uint256 profit, uint256 callFeeToUser) {
uint256 pendingReward = IMasterChef(MASTER_CHEF).pendingRewards(poolId, address(this));
uint256 totalRewards = pendingReward + IERC20Upgradeable(EXC).balanceOf(address(this));
if (totalRewards != 0) {
address[] memory rewardToWftmPath = new address[](2);
rewardToWftmPath[0] = EXC;
rewardToWftmPath[1] = WFTM;
uint256[] memory amountOutMins = IExcaliburRouter(EXCALIBUR_ROUTER).getAmountsOut(
totalRewards,
rewardToWftmPath
);
profit += amountOutMins[1];
}
profit += IERC20Upgradeable(WFTM).balanceOf(address(this));
uint256 wftmFee = (profit * totalFee) / PERCENT_DIVISOR;
callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR;
profit -= wftmFee;
}
/**
* @dev Function to retire the strategy. Claims all rewards and withdraws
* all principal from external contracts, and sends everything back to
* the vault. Can only be called by strategist or owner.
*
* Note: this is not an emergency withdraw function. For that, see panic().
*/
function retireStrat() external {
_onlyStrategistOrOwner();
_claimRewards();
_swapRewardsToWftm();
_addLiquidity();
uint256 poolBalance = balanceOfPool();
if (poolBalance != 0) {
IMasterChef(MASTER_CHEF).withdraw(poolId, poolBalance);
}
uint256 wantBalance = IERC20Upgradeable(want).balanceOf(address(this));
IERC20Upgradeable(want).safeTransfer(vault, wantBalance);
}
/**
* @dev Pauses supplied. Withdraws all funds from the LP Depositor, leaving rewards behind.
*/
function panic() external {
_onlyStrategistOrOwner();
IMasterChef(MASTER_CHEF).emergencyWithdraw(poolId);
pause();
}
/**
* @dev Unpauses the strat.
*/
function unpause() external {
_onlyStrategistOrOwner();
_unpause();
_giveAllowances();
deposit();
}
/**
* @dev Pauses the strat.
*/
function pause() public {
_onlyStrategistOrOwner();
_pause();
_removeAllowances();
}
/**
* @dev Function that puts the funds to work.
* It gets called whenever someone supplied in the strategy's vault contract.
* It supplies {want} to farm {EXC}
*/
function deposit() public whenNotPaused {
uint256 wantBalance = IERC20Upgradeable(want).balanceOf(address(this));
if (wantBalance != 0) {
IMasterChef(MASTER_CHEF).deposit(poolId, wantBalance);
}
}
/**
* @dev Calculates the total amount of {want} held by the strategy
* which is the balance of want + the total amount supplied to Excalibur.
*/
function balanceOf() public view override returns (uint256) {
return balanceOfWant() + balanceOfPool();
}
/**
* @dev Calculates the total amount of {want} held in the Excalibur MasterChef
*/
function balanceOfPool() public view returns (uint256) {
(uint256 _amount, ) = IMasterChef(MASTER_CHEF).getUserInfo(poolId, address(this));
return _amount;
}
/**
* @dev Calculates the balance of want held directly by the strategy
*/
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
/**
* @dev Core function of the strat, in charge of collecting and re-investing rewards.
* 1. Claims {EXC} from the MasterChef.
* 2. Swaps rewards to {WFTM}.
* 3. Claims fees for the harvest caller and treasury.
* 4. Swaps the {WFTM} token for {want}
* 5. Deposits.
*/
function _harvestCore() internal override {
_claimRewards();
_swapRewardsToWftm();
_chargeFees();
_addLiquidity();
deposit();
}
/**
* @dev Core harvest function.
* Get rewards from the MasterChef
*/
function _claimRewards() internal {
IMasterChef(MASTER_CHEF).harvest(poolId);
}
/**
* @dev Core harvest function.
* Swaps {EXC} to {WFTM}
*/
function _swapRewardsToWftm() internal {
uint256 rewardBalance = IERC20Upgradeable(EXC).balanceOf(address(this));
if (rewardBalance == 0) {
return;
}
_swapTokens(EXC, WFTM, rewardBalance);
}
function _swapTokens(
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to || _amount == 0) {
return;
}
address[] memory path = new address[](2);
path[0] = _from;
path[1] = _to;
IExcaliburRouter(EXCALIBUR_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens(
_amount,
0,
path,
address(this),
address(this), // Send part of the swap fees back to the strategy
block.timestamp
);
}
/**
* @dev Core harvest function.
* Charges fees based on the amount of WFTM gained from reward
*/
function _chargeFees() internal {
uint256 wftmFee = (IERC20Upgradeable(WFTM).balanceOf(address(this)) * totalFee) / PERCENT_DIVISOR;
if (wftmFee != 0) {
uint256 callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR;
uint256 treasuryFeeToVault = (wftmFee * treasuryFee) / PERCENT_DIVISOR;
uint256 feeToStrategist = (treasuryFeeToVault * strategistFee) / PERCENT_DIVISOR;
treasuryFeeToVault -= feeToStrategist;
IERC20Upgradeable(WFTM).safeTransfer(msg.sender, callFeeToUser);
IERC20Upgradeable(WFTM).safeTransfer(treasury, treasuryFeeToVault);
IERC20Upgradeable(WFTM).safeTransfer(strategistRemitter, feeToStrategist);
}
}
/** @dev Converts WFTM to both sides of the LP token and builds the liquidity pair */
function _addLiquidity() internal {
uint256 wrappedHalf = IERC20Upgradeable(WFTM).balanceOf(address(this)) / 2;
if (wrappedHalf == 0) {
return;
}
_swapTokens(WFTM, lpToken0, wrappedHalf);
_swapTokens(WFTM, lpToken1, wrappedHalf);
uint256 lp0Bal = IERC20Upgradeable(lpToken0).balanceOf(address(this));
uint256 lp1Bal = IERC20Upgradeable(lpToken1).balanceOf(address(this));
IExcaliburRouter(EXCALIBUR_ROUTER).addLiquidity(
lpToken0,
lpToken1,
lp0Bal,
lp1Bal,
0,
0,
address(this),
block.timestamp
);
}
/**
* @dev Gives the necessary allowances
*/
function _giveAllowances() internal {
// want -> MASTER_CHEF
uint256 wantAllowance = type(uint256).max - IERC20Upgradeable(want).allowance(address(this), MASTER_CHEF);
IERC20Upgradeable(want).safeIncreaseAllowance(MASTER_CHEF, wantAllowance);
// // rewardTokens -> EXCALIBUR_ROUTER
uint256 excAllowance = type(uint256).max -
IERC20Upgradeable(EXC).allowance(address(this), EXCALIBUR_ROUTER);
IERC20Upgradeable(EXC).safeIncreaseAllowance(EXCALIBUR_ROUTER, excAllowance);
// // WFTM -> EXCALIBUR_ROUTER
uint256 wftmAllowance = type(uint256).max - IERC20Upgradeable(WFTM).allowance(address(this), EXCALIBUR_ROUTER);
IERC20Upgradeable(WFTM).safeIncreaseAllowance(EXCALIBUR_ROUTER, wftmAllowance);
// // LP tokens -> EXCALIBUR_ROUTER
uint256 lp0Allowance = type(uint256).max - IERC20Upgradeable(lpToken0).allowance(address(this), EXCALIBUR_ROUTER);
IERC20Upgradeable(lpToken0).safeIncreaseAllowance(EXCALIBUR_ROUTER, lp0Allowance);
uint256 lp1Allowance = type(uint256).max - IERC20Upgradeable(lpToken1).allowance(address(this), EXCALIBUR_ROUTER);
IERC20Upgradeable(lpToken1).safeIncreaseAllowance(EXCALIBUR_ROUTER, lp1Allowance);
}
/**
* @dev Removes all allowance that were given
*/
function _removeAllowances() internal {
IERC20Upgradeable(want).safeDecreaseAllowance(
MASTER_CHEF,
IERC20Upgradeable(want).allowance(address(this), MASTER_CHEF)
);
IERC20Upgradeable(EXC).safeDecreaseAllowance(
EXCALIBUR_ROUTER,
IERC20Upgradeable(EXC).allowance(address(this), EXCALIBUR_ROUTER)
);
IERC20Upgradeable(WFTM).safeDecreaseAllowance(
EXCALIBUR_ROUTER,
IERC20Upgradeable(WFTM).allowance(address(this), EXCALIBUR_ROUTER)
);
IERC20Upgradeable(lpToken0).safeDecreaseAllowance(
EXCALIBUR_ROUTER,
IERC20Upgradeable(lpToken0).allowance(address(this), EXCALIBUR_ROUTER)
);
IERC20Upgradeable(lpToken1).safeDecreaseAllowance(
EXCALIBUR_ROUTER,
IERC20Upgradeable(lpToken1).allowance(address(this), EXCALIBUR_ROUTER)
);
}
}
|
Core harvest function. Get rewards from the MasterChef/
|
function _claimRewards() internal {
IMasterChef(MASTER_CHEF).harvest(poolId);
}
| 1,818,182
|
/**
*Submitted for verification at Etherscan.io on 2021-12-20
*/
// Sources flattened with hardhat v2.4.3 https://hardhat.org
// File openzeppelin-solidity/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
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);
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
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;
}
}
// File openzeppelin-solidity/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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());
}
}
}
// File openzeppelin-solidity/contracts/governance/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`.
*/
constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
// solhint-disable-next-line not-rely-on-time
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
// solhint-disable-next-line not-rely-on-time
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 predecessor) private view {
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private {
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}
// File contracts/interfaces/ISwapRouter.sol
pragma solidity 0.8.6;
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
// solhint-disable-next-line func-name-mixedcase
function WETH9() external pure returns (address);
}
// File openzeppelin-solidity/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File openzeppelin-solidity/contracts/token/ERC20/utils/[email protected]
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'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File openzeppelin-solidity/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File openzeppelin-solidity/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File openzeppelin-solidity/contracts/utils/math/[email protected]
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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* 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;
}
}
}
// File contracts/HATToken.sol
pragma solidity 0.8.6;
contract HATToken is IERC20 {
struct PendingMinter {
uint256 seedAmount;
uint256 setMinterPendingAt;
}
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice EIP-20 token name for this token
// solhint-disable-next-line const-name-snakecase
string public constant name = "hats.finance";
/// @notice EIP-20 token symbol for this token
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "HAT";
/// @notice EIP-20 token decimals for this token
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public override totalSupply;
address public governance;
address public governancePending;
uint256 public setGovernancePendingAt;
uint256 public immutable timeLockDelay;
uint256 public constant CAP = 10000000e18;
/// @notice Address which may mint new tokens
/// minter -> minting seedAmount
mapping (address => uint256) public minters;
/// @notice Address which may mint new tokens
/// minter -> minting seedAmount
mapping (address => PendingMinter) public pendingMinters;
// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice An event thats emitted when a new minter address is pending
event MinterPending(address indexed minter, uint256 seedAmount, uint256 at);
/// @notice An event thats emitted when the minter address is changed
event MinterChanged(address indexed minter, uint256 seedAmount);
/// @notice An event thats emitted when a new governance address is pending
event GovernancePending(address indexed oldGovernance, address indexed newGovernance, uint256 at);
/// @notice An event thats emitted when a new governance address is set
event GovernanceChanged(address indexed oldGovernance, address indexed newGovernance);
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Construct a new HAT token
*/
// solhint-disable-next-line func-visibility
constructor(address _governance, uint256 _timeLockDelay) {
governance = _governance;
timeLockDelay = _timeLockDelay;
}
function setPendingGovernance(address _governance) external {
require(msg.sender == governance, "HAT:!governance");
require(_governance != address(0), "HAT:!_governance");
governancePending = _governance;
// solhint-disable-next-line not-rely-on-time
setGovernancePendingAt = block.timestamp;
emit GovernancePending(governance, _governance, setGovernancePendingAt);
}
function confirmGovernance() external {
require(msg.sender == governance, "HAT:!governance");
require(setGovernancePendingAt > 0, "HAT:!governancePending");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - setGovernancePendingAt > timeLockDelay,
"HAT: cannot confirm governance at this time");
emit GovernanceChanged(governance, governancePending);
governance = governancePending;
setGovernancePendingAt = 0;
}
function setPendingMinter(address _minter, uint256 _cap) external {
require(msg.sender == governance, "HAT::!governance");
pendingMinters[_minter].seedAmount = _cap;
// solhint-disable-next-line not-rely-on-time
pendingMinters[_minter].setMinterPendingAt = block.timestamp;
emit MinterPending(_minter, _cap, pendingMinters[_minter].setMinterPendingAt);
}
function confirmMinter(address _minter) external {
require(msg.sender == governance, "HAT::mint: only the governance can confirm minter");
require(pendingMinters[_minter].setMinterPendingAt > 0, "HAT:: no pending minter was set");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - pendingMinters[_minter].setMinterPendingAt > timeLockDelay,
"HATToken: cannot confirm at this time");
minters[_minter] = pendingMinters[_minter].seedAmount;
pendingMinters[_minter].setMinterPendingAt = 0;
emit MinterChanged(_minter, pendingMinters[_minter].seedAmount);
}
function burn(uint256 _amount) external {
return _burn(msg.sender, _amount);
}
function mint(address _account, uint _amount) external {
require(minters[msg.sender] >= _amount, "HATToken: amount greater than limitation");
minters[msg.sender] = SafeMath.sub(minters[msg.sender], _amount);
_mint(_account, _amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external override view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external override returns (bool) {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, 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, uint addedValue) external virtual returns (bool) {
require(spender != address(0), "HAT: increaseAllowance to the zero address");
uint96 valueToAdd = safe96(addedValue, "HAT::increaseAllowance: addedValue exceeds 96 bits");
allowances[msg.sender][spender] =
add96(allowances[msg.sender][spender], valueToAdd, "HAT::increaseAllowance: overflows");
emit Approval(msg.sender, spender, allowances[msg.sender][spender]);
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, uint subtractedValue) external virtual returns (bool) {
require(spender != address(0), "HAT: decreaseAllowance to the zero address");
uint96 valueTosubtract = safe96(subtractedValue, "HAT::decreaseAllowance: subtractedValue exceeds 96 bits");
allowances[msg.sender][spender] = sub96(allowances[msg.sender][spender], valueTosubtract,
"HAT::decreaseAllowance: spender allowance is less than subtractedValue");
emit Approval(msg.sender, spender, allowances[msg.sender][spender]);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "HAT::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "HAT::permit: invalid signature");
require(signatory == owner, "HAT::permit: unauthorized");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "HAT::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view override returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external override returns (bool) {
uint96 amount = safe96(rawAmount, "HAT::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external override returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = sub96(spenderAllowance, amount,
"HAT::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "HAT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "HAT::delegateBySig: invalid nonce");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= expiry, "HAT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) external view returns (uint96) {
require(blockNumber < block.number, "HAT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/
function _mint(address dst, uint rawAmount) internal {
require(dst != address(0), "HAT::mint: cannot transfer to the zero address");
require(SafeMath.add(totalSupply, rawAmount) <= CAP, "ERC20Capped: CAP exceeded");
// mint the amount
uint96 amount = safe96(rawAmount, "HAT::mint: amount exceeds 96 bits");
totalSupply = safe96(SafeMath.add(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits");
// transfer the amount to the recipient
balances[dst] = add96(balances[dst], amount, "HAT::mint: transfer amount overflows");
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* Burn tokens
* @param src The address of the source account
* @param rawAmount The number of tokens to be burned
*/
function _burn(address src, uint rawAmount) internal {
require(src != address(0), "HAT::burn: cannot burn to the zero address");
// burn the amount
uint96 amount = safe96(rawAmount, "HAT::burn: amount exceeds 96 bits");
totalSupply = safe96(SafeMath.sub(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits");
// reduce the amount from src address
balances[src] = sub96(balances[src], amount, "HAT::burn: burn amount exceeds balance");
emit Transfer(src, address(0), amount);
// move delegates
_moveDelegates(delegates[src], address(0), amount);
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "HAT::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "HAT::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "HAT::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "HAT::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "HAT::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "HAT::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "HAT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint) {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
return chainId;
}
}
// File openzeppelin-solidity/contracts/security/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/HATMaster.sol
// Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md
pragma solidity 0.8.6;
contract HATMaster is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // The user share of the pool based on the amount of lpToken the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HATs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.rewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `rewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolUpdate {
uint256 blockNumber;// update blocknumber
uint256 totalAllocPoint; //totalAllocPoint
}
struct RewardsSplit {
//the percentage of the total reward to reward the hacker via vesting contract(claim reported)
uint256 hackerVestedReward;
//the percentage of the total reward to reward the hacker(claim reported)
uint256 hackerReward;
// the percentage of the total reward to be sent to the committee
uint256 committeeReward;
// the percentage of the total reward to be swap to HAT and to be burned
uint256 swapAndBurn;
// the percentage of the total reward to be swap to HAT and sent to governance
uint256 governanceHatReward;
// the percentage of the total reward to be swap to HAT and sent to the hacker
uint256 hackerHatReward;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken;
uint256 allocPoint;
uint256 lastRewardBlock;
uint256 rewardPerShare;
uint256 totalUsersAmount;
uint256 lastProcessedTotalAllocPoint;
uint256 balance;
}
// Info of each pool.
struct PoolReward {
RewardsSplit rewardsSplit;
uint256[] rewardsLevels;
bool committeeCheckIn;
uint256 vestingDuration;
uint256 vestingPeriods;
}
HATToken public immutable HAT;
uint256 public immutable REWARD_PER_BLOCK;
uint256 public immutable START_BLOCK;
uint256 public immutable MULTIPLIER_PERIOD;
// Info of each pool.
PoolInfo[] public poolInfo;
PoolUpdate[] public globalPoolUpdates;
mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo
// Info of each user that stakes LP tokens. pid => user address => info
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
//pid -> PoolReward
mapping (uint256=>PoolReward) internal poolsRewards;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SendReward(address indexed user, uint256 indexed pid, uint256 amount, uint256 requestedAmount);
event MassUpdatePools(uint256 _fromPid, uint256 _toPid);
constructor(
HATToken _hat,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _multiplierPeriod
// solhint-disable-next-line func-visibility
) {
HAT = _hat;
REWARD_PER_BLOCK = _rewardPerBlock;
START_BLOCK = _startBlock;
MULTIPLIER_PERIOD = _multiplierPeriod;
}
/**
* @dev massUpdatePools - Update reward variables for all pools
* Be careful of gas spending!
* @param _fromPid update pools range from this pool id
* @param _toPid update pools range to this pool id
*/
function massUpdatePools(uint256 _fromPid, uint256 _toPid) external {
require(_toPid <= poolInfo.length, "pool range is too big");
require(_fromPid <= _toPid, "invalid pool range");
for (uint256 pid = _fromPid; pid < _toPid; ++pid) {
updatePool(pid);
}
emit MassUpdatePools(_fromPid, _toPid);
}
function claimReward(uint256 _pid) external {
_deposit(_pid, 0);
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 lastRewardBlock = pool.lastRewardBlock;
if (block.number <= lastRewardBlock) {
return;
}
uint256 totalUsersAmount = pool.totalUsersAmount;
uint256 lastPoolUpdate = globalPoolUpdates.length-1;
if (totalUsersAmount == 0) {
pool.lastRewardBlock = block.number;
pool.lastProcessedTotalAllocPoint = lastPoolUpdate;
return;
}
uint256 reward = calcPoolReward(_pid, lastRewardBlock, lastPoolUpdate);
uint256 amountCanMint = HAT.minters(address(this));
reward = amountCanMint < reward ? amountCanMint : reward;
if (reward > 0) {
HAT.mint(address(this), reward);
}
pool.rewardPerShare = pool.rewardPerShare.add(reward.mul(1e12).div(totalUsersAmount));
pool.lastRewardBlock = block.number;
pool.lastProcessedTotalAllocPoint = lastPoolUpdate;
}
/**
* @dev getMultiplier - multiply blocks with relevant multiplier for specific range
* @param _from range's from block
* @param _to range's to block
* will revert if from < START_BLOCK or _to < _from
*/
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256 result) {
uint256[25] memory rewardMultipliers = [uint256(4413), 4413, 8825, 7788, 6873, 6065,
5353, 4724, 4169, 3679, 3247, 2865,
2528, 2231, 1969, 1738, 1534, 1353,
1194, 1054, 930, 821, 724, 639, 0];
uint256 max = rewardMultipliers.length;
uint256 i = (_from - START_BLOCK) / MULTIPLIER_PERIOD + 1;
for (; i < max; i++) {
uint256 endBlock = MULTIPLIER_PERIOD * i + START_BLOCK;
if (_to <= endBlock) {
break;
}
result += (endBlock - _from) * rewardMultipliers[i-1];
_from = endBlock;
}
result += (_to - _from) * rewardMultipliers[i > max ? (max-1) : (i-1)];
}
function getRewardForBlocksRange(uint256 _from, uint256 _to, uint256 _allocPoint, uint256 _totalAllocPoint)
public
view
returns (uint256 reward) {
if (_totalAllocPoint > 0) {
reward = getMultiplier(_from, _to).mul(REWARD_PER_BLOCK).mul(_allocPoint).div(_totalAllocPoint).div(100);
}
}
/**
* @dev calcPoolReward -
* calculate rewards for a pool by iterating over the history of totalAllocPoints updates.
* and sum up all rewards periods from pool.lastRewardBlock till current block number.
* @param _pid pool id
* @param _from block starting calculation
* @param _lastPoolUpdate lastPoolUpdate
* @return reward
*/
function calcPoolReward(uint256 _pid, uint256 _from, uint256 _lastPoolUpdate) public view returns(uint256 reward) {
uint256 poolAllocPoint = poolInfo[_pid].allocPoint;
uint256 i = poolInfo[_pid].lastProcessedTotalAllocPoint;
for (; i < _lastPoolUpdate; i++) {
uint256 nextUpdateBlock = globalPoolUpdates[i+1].blockNumber;
reward =
reward.add(getRewardForBlocksRange(_from,
nextUpdateBlock,
poolAllocPoint,
globalPoolUpdates[i].totalAllocPoint));
_from = nextUpdateBlock;
}
return reward.add(getRewardForBlocksRange(_from,
block.number,
poolAllocPoint,
globalPoolUpdates[i].totalAllocPoint));
}
function _deposit(uint256 _pid, uint256 _amount) internal nonReentrant {
require(poolsRewards[_pid].committeeCheckIn, "committee not checked in yet");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeTransferReward(msg.sender, pending, _pid);
}
}
if (_amount > 0) {
uint256 lpSupply = pool.balance;
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
pool.balance = pool.balance.add(_amount);
uint256 factoredAmount = _amount;
if (pool.totalUsersAmount > 0) {
factoredAmount = pool.totalUsersAmount.mul(_amount).div(lpSupply);
}
user.amount = user.amount.add(factoredAmount);
pool.totalUsersAmount = pool.totalUsersAmount.add(factoredAmount);
}
user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function _withdraw(uint256 _pid, uint256 _amount) internal nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not enough user balance");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeTransferReward(msg.sender, pending, _pid);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 amountToWithdraw = _amount.mul(pool.balance).div(pool.totalUsersAmount);
pool.balance = pool.balance.sub(amountToWithdraw);
pool.lpToken.safeTransfer(msg.sender, amountToWithdraw);
pool.totalUsersAmount = pool.totalUsersAmount.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function _emergencyWithdraw(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "user.amount = 0");
uint256 factoredBalance = user.amount.mul(pool.balance).div(pool.totalUsersAmount);
pool.totalUsersAmount = pool.totalUsersAmount.sub(user.amount);
user.amount = 0;
user.rewardDebt = 0;
pool.balance = pool.balance.sub(factoredBalance);
pool.lpToken.safeTransfer(msg.sender, factoredBalance);
emit EmergencyWithdraw(msg.sender, _pid, factoredBalance);
}
// -------- For manage pool ---------
function add(uint256 _allocPoint, IERC20 _lpToken) internal {
require(poolId1[address(_lpToken)] == 0, "HATMaster::add: lpToken is already in pool");
poolId1[address(_lpToken)] = poolInfo.length + 1;
uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK;
uint256 totalAllocPoint = (globalPoolUpdates.length == 0) ? _allocPoint :
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint.add(_allocPoint);
if (globalPoolUpdates.length > 0 &&
globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) {
//already update in this block
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint;
} else {
globalPoolUpdates.push(PoolUpdate({
blockNumber: block.number,
totalAllocPoint: totalAllocPoint
}));
}
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
rewardPerShare: 0,
totalUsersAmount: 0,
lastProcessedTotalAllocPoint: globalPoolUpdates.length-1,
balance: 0
}));
}
function set(uint256 _pid, uint256 _allocPoint) internal {
updatePool(_pid);
uint256 totalAllocPoint =
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint
.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
if (globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) {
//already update in this block
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint;
} else {
globalPoolUpdates.push(PoolUpdate({
blockNumber: block.number,
totalAllocPoint: totalAllocPoint
}));
}
poolInfo[_pid].allocPoint = _allocPoint;
}
// Safe HAT transfer function, just in case if rounding error causes pool to not have enough HATs.
function safeTransferReward(address _to, uint256 _amount, uint256 _pid) internal {
uint256 hatBalance = HAT.balanceOf(address(this));
if (_amount > hatBalance) {
HAT.transfer(_to, hatBalance);
emit SendReward(_to, _pid, hatBalance, _amount);
} else {
HAT.transfer(_to, _amount);
emit SendReward(_to, _pid, _amount, _amount);
}
}
}
// File contracts/tokenlock/ITokenLock.sol
pragma solidity 0.8.6;
pragma experimental ABIEncoderV2;
interface ITokenLock {
enum Revocability { NotSet, Enabled, Disabled }
// -- Balances --
function currentBalance() external view returns (uint256);
// -- Time & Periods --
function currentTime() external view returns (uint256);
function duration() external view returns (uint256);
function sinceStartTime() external view returns (uint256);
function amountPerPeriod() external view returns (uint256);
function periodDuration() external view returns (uint256);
function currentPeriod() external view returns (uint256);
function passedPeriods() external view returns (uint256);
// -- Locking & Release Schedule --
function availableAmount() external view returns (uint256);
function vestedAmount() external view returns (uint256);
function releasableAmount() external view returns (uint256);
function totalOutstandingAmount() external view returns (uint256);
function surplusAmount() external view returns (uint256);
// -- Value Transfer --
function release() external;
function withdrawSurplus(uint256 _amount) external;
function revoke() external;
}
// File contracts/tokenlock/ITokenLockFactory.sol
pragma solidity 0.8.6;
interface ITokenLockFactory {
// -- Factory --
function setMasterCopy(address _masterCopy) external;
function createTokenLock(
address _token,
address _owner,
address _beneficiary,
uint256 _managedAmount,
uint256 _startTime,
uint256 _endTime,
uint256 _periods,
uint256 _releaseStartTime,
uint256 _vestingCliffTime,
ITokenLock.Revocability _revocable,
bool _canDelegate
) external returns(address contractAddress);
}
// File contracts/Governable.sol
pragma solidity 0.8.6;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an governance) that can be granted exclusive access to
* specific functions.
*
* The governance account will be passed on initialization of the contract. This
* can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyGovernance`, which can be applied to your functions to restrict their use to
* the governance.
*/
contract Governable {
address private _governance;
address public governancePending;
uint256 public setGovernancePendingAt;
uint256 public constant TIME_LOCK_DELAY = 2 days;
/// @notice An event thats emitted when a new governance address is set
event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance);
/// @notice An event thats emitted when a new governance address is pending
event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at);
/**
* @dev Throws if called by any account other than the governance.
*/
modifier onlyGovernance() {
require(msg.sender == _governance, "only governance");
_;
}
/**
* @dev setPendingGovernance set a pending governance address.
* NOTE: transferGovernorship can be called after a time delay of 2 days.
*/
function setPendingGovernance(address _newGovernance) external onlyGovernance {
require(_newGovernance != address(0), "Governable:new governance is the zero address");
governancePending = _newGovernance;
// solhint-disable-next-line not-rely-on-time
setGovernancePendingAt = block.timestamp;
emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt);
}
/**
* @dev transferGovernorship transfer governorship to the pending governance address.
* NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance.
*/
function transferGovernorship() external onlyGovernance {
require(setGovernancePendingAt > 0, "Governable: no pending governance");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY,
"Governable: cannot confirm governance at this time");
emit GovernorshipTransferred(_governance, governancePending);
_governance = governancePending;
setGovernancePendingAt = 0;
}
/**
* @dev Returns the address of the current governance.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Initializes the contract setting the initial governance.
*/
function initialize(address _initialGovernance) internal {
_governance = _initialGovernance;
emit GovernorshipTransferred(address(0), _initialGovernance);
}
}
// File contracts/HATVaults.sol
// Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md
pragma solidity 0.8.6;
contract HATVaults is Governable, HATMaster {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct PendingApproval {
address beneficiary;
uint256 severity;
address approver;
}
struct ClaimReward {
uint256 hackerVestedReward;
uint256 hackerReward;
uint256 committeeReward;
uint256 swapAndBurn;
uint256 governanceHatReward;
uint256 hackerHatReward;
}
struct PendingRewardsLevels {
uint256 timestamp;
uint256[] rewardsLevels;
}
struct GeneralParameters {
uint256 hatVestingDuration;
uint256 hatVestingPeriods;
uint256 withdrawPeriod;
uint256 safetyPeriod; //withdraw disable period in seconds
uint256 setRewardsLevelsDelay;
uint256 withdrawRequestEnablePeriod;
uint256 withdrawRequestPendingPeriod;
uint256 claimFee; //claim fee in ETH
}
//pid -> committee address
mapping(uint256=>address) public committees;
mapping(address => uint256) public swapAndBurns;
//hackerAddress ->(token->amount)
mapping(address => mapping(address => uint256)) public hackersHatRewards;
//token -> amount
mapping(address => uint256) public governanceHatRewards;
//pid -> PendingApproval
mapping(uint256 => PendingApproval) public pendingApprovals;
//poolId -> (address -> requestTime)
mapping(uint256 => mapping(address => uint256)) public withdrawRequests;
//poolId -> PendingRewardsLevels
mapping(uint256 => PendingRewardsLevels) public pendingRewardsLevels;
mapping(uint256 => bool) public poolDepositPause;
GeneralParameters public generalParameters;
uint256 internal constant REWARDS_LEVEL_DENOMINATOR = 10000;
ITokenLockFactory public immutable tokenLockFactory;
ISwapRouter public immutable uniSwapRouter;
uint256 public constant MINIMUM_DEPOSIT = 1e6;
modifier onlyCommittee(uint256 _pid) {
require(committees[_pid] == msg.sender, "only committee");
_;
}
modifier noPendingApproval(uint256 _pid) {
require(pendingApprovals[_pid].beneficiary == address(0), "pending approval exist");
_;
}
modifier noSafetyPeriod() {
//disable withdraw for safetyPeriod (e.g 1 hour) each withdrawPeriod(e.g 11 hours)
// solhint-disable-next-line not-rely-on-time
require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) <
generalParameters.withdrawPeriod,
"safety period");
_;
}
event SetCommittee(uint256 indexed _pid, address indexed _committee);
event AddPool(uint256 indexed _pid,
uint256 indexed _allocPoint,
address indexed _lpToken,
address _committee,
string _descriptionHash,
uint256[] _rewardsLevels,
RewardsSplit _rewardsSplit,
uint256 _rewardVestingDuration,
uint256 _rewardVestingPeriods);
event SetPool(uint256 indexed _pid, uint256 indexed _allocPoint, bool indexed _registered, string _descriptionHash);
event Claim(address indexed _claimer, string _descriptionHash);
event SetRewardsSplit(uint256 indexed _pid, RewardsSplit _rewardsSplit);
event SetRewardsLevels(uint256 indexed _pid, uint256[] _rewardsLevels);
event PendingRewardsLevelsLog(uint256 indexed _pid, uint256[] _rewardsLevels, uint256 _timeStamp);
event SwapAndSend(uint256 indexed _pid,
address indexed _beneficiary,
uint256 indexed _amountSwaped,
uint256 _amountReceived,
address _tokenLock);
event SwapAndBurn(uint256 indexed _pid, uint256 indexed _amountSwaped, uint256 indexed _amountBurned);
event SetVestingParams(uint256 indexed _pid, uint256 indexed _duration, uint256 indexed _periods);
event SetHatVestingParams(uint256 indexed _duration, uint256 indexed _periods);
event ClaimApprove(address indexed _approver,
uint256 indexed _pid,
address indexed _beneficiary,
uint256 _severity,
address _tokenLock,
ClaimReward _claimReward);
event PendingApprovalLog(uint256 indexed _pid,
address indexed _beneficiary,
uint256 indexed _severity,
address _approver);
event WithdrawRequest(uint256 indexed _pid,
address indexed _beneficiary,
uint256 indexed _withdrawEnableTime);
event SetWithdrawSafetyPeriod(uint256 indexed _withdrawPeriod, uint256 indexed _safetyPeriod);
event RewardDepositors(uint256 indexed _pid, uint256 indexed _amount);
/**
* @dev constructor -
* @param _rewardsToken the reward token address (HAT)
* @param _rewardPerBlock the reward amount per block the contract will reward pools
* @param _startBlock start block of of which the contract will start rewarding from.
* @param _multiplierPeriod a fix period value. each period will have its own multiplier value.
* which set the reward for each period. e.g a value of 100000 means that each such period is 100000 blocks.
* @param _hatGovernance the governance address.
* Some of the contracts functions are limited only to governance :
* addPool,setPool,dismissPendingApprovalClaim,approveClaim,
* setHatVestingParams,setVestingParams,setRewardsSplit
* @param _uniSwapRouter uni swap v3 router to be used to swap tokens for HAT token.
* @param _tokenLockFactory address of the token lock factory to be used
* to create a vesting contract for the approved claim reporter.
*/
constructor(
address _rewardsToken,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _multiplierPeriod,
address _hatGovernance,
ISwapRouter _uniSwapRouter,
ITokenLockFactory _tokenLockFactory
// solhint-disable-next-line func-visibility
) HATMaster(HATToken(_rewardsToken), _rewardPerBlock, _startBlock, _multiplierPeriod) {
Governable.initialize(_hatGovernance);
uniSwapRouter = _uniSwapRouter;
tokenLockFactory = _tokenLockFactory;
generalParameters = GeneralParameters({
hatVestingDuration: 90 days,
hatVestingPeriods:90,
withdrawPeriod: 11 hours,
safetyPeriod: 1 hours,
setRewardsLevelsDelay: 2 days,
withdrawRequestEnablePeriod: 7 days,
withdrawRequestPendingPeriod: 7 days,
claimFee: 0
});
}
/**
* @dev pendingApprovalClaim - called by a committee to set a pending approval claim.
* The pending approval need to be approved or dismissed by the hats governance.
* This function should be called only on a safety period, where withdrawn is disable.
* Upon a call to this function by the committee the pool withdrawn will be disable
* till governance will approve or dismiss this pending approval.
* @param _pid pool id
* @param _beneficiary the approval claim beneficiary
* @param _severity approval claim severity
*/
function pendingApprovalClaim(uint256 _pid, address _beneficiary, uint256 _severity)
external
onlyCommittee(_pid)
noPendingApproval(_pid) {
require(_beneficiary != address(0), "beneficiary is zero");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) >=
generalParameters.withdrawPeriod,
"none safety period");
require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range");
pendingApprovals[_pid] = PendingApproval({
beneficiary: _beneficiary,
severity: _severity,
approver: msg.sender
});
emit PendingApprovalLog(_pid, _beneficiary, _severity, msg.sender);
}
/**
* @dev setWithdrawRequestParams - called by hats governance to set withdraw request params
* @param _withdrawRequestPendingPeriod - the time period where the withdraw request is pending.
* @param _withdrawRequestEnablePeriod - the time period where the withdraw is enable for a withdraw request.
*/
function setWithdrawRequestParams(uint256 _withdrawRequestPendingPeriod, uint256 _withdrawRequestEnablePeriod)
external
onlyGovernance {
generalParameters.withdrawRequestPendingPeriod = _withdrawRequestPendingPeriod;
generalParameters.withdrawRequestEnablePeriod = _withdrawRequestEnablePeriod;
}
/**
* @dev dismissPendingApprovalClaim - called by hats governance to dismiss a pending approval claim.
* @param _pid pool id
*/
function dismissPendingApprovalClaim(uint256 _pid) external onlyGovernance {
delete pendingApprovals[_pid];
}
/**
* @dev approveClaim - called by hats governance to approve a pending approval claim.
* @param _pid pool id
*/
function approveClaim(uint256 _pid) external onlyGovernance nonReentrant {
require(pendingApprovals[_pid].beneficiary != address(0), "no pending approval");
PoolReward storage poolReward = poolsRewards[_pid];
PendingApproval memory pendingApproval = pendingApprovals[_pid];
delete pendingApprovals[_pid];
IERC20 lpToken = poolInfo[_pid].lpToken;
ClaimReward memory claimRewards = calcClaimRewards(_pid, pendingApproval.severity);
poolInfo[_pid].balance = poolInfo[_pid].balance.sub(
claimRewards.hackerReward
.add(claimRewards.hackerVestedReward)
.add(claimRewards.committeeReward)
.add(claimRewards.swapAndBurn)
.add(claimRewards.hackerHatReward)
.add(claimRewards.governanceHatReward));
address tokenLock;
if (claimRewards.hackerVestedReward > 0) {
//hacker get its reward to a vesting contract
tokenLock = tokenLockFactory.createTokenLock(
address(lpToken),
0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing.
pendingApproval.beneficiary,
claimRewards.hackerVestedReward,
// solhint-disable-next-line not-rely-on-time
block.timestamp, //start
// solhint-disable-next-line not-rely-on-time
block.timestamp + poolReward.vestingDuration, //end
poolReward.vestingPeriods,
0, //no release start
0, //no cliff
ITokenLock.Revocability.Disabled,
false
);
lpToken.safeTransfer(tokenLock, claimRewards.hackerVestedReward);
}
lpToken.safeTransfer(pendingApproval.beneficiary, claimRewards.hackerReward);
lpToken.safeTransfer(pendingApproval.approver, claimRewards.committeeReward);
//storing the amount of token which can be swap and burned so it could be swapAndBurn in a seperate tx.
swapAndBurns[address(lpToken)] = swapAndBurns[address(lpToken)].add(claimRewards.swapAndBurn);
governanceHatRewards[address(lpToken)] =
governanceHatRewards[address(lpToken)].add(claimRewards.governanceHatReward);
hackersHatRewards[pendingApproval.beneficiary][address(lpToken)] =
hackersHatRewards[pendingApproval.beneficiary][address(lpToken)].add(claimRewards.hackerHatReward);
emit ClaimApprove(msg.sender,
_pid,
pendingApproval.beneficiary,
pendingApproval.severity,
tokenLock,
claimRewards);
assert(poolInfo[_pid].balance > 0);
}
/**
* @dev rewardDepositors - add funds to pool to reward depositors.
* The funds will be given to depositors pro rata upon withdraw
* @param _pid pool id
* @param _amount amount to add
*/
function rewardDepositors(uint256 _pid, uint256 _amount) external {
require(poolInfo[_pid].balance.add(_amount).div(MINIMUM_DEPOSIT) < poolInfo[_pid].totalUsersAmount,
"amount to reward is too big");
poolInfo[_pid].lpToken.safeTransferFrom(msg.sender, address(this), _amount);
poolInfo[_pid].balance = poolInfo[_pid].balance.add(_amount);
emit RewardDepositors(_pid, _amount);
}
/**
* @dev setClaimFee - called by hats governance to set claim fee
* @param _fee claim fee in ETH
*/
function setClaimFee(uint256 _fee) external onlyGovernance {
generalParameters.claimFee = _fee;
}
/**
* @dev setWithdrawSafetyPeriod - called by hats governance to set Withdraw Period
* @param _withdrawPeriod withdraw enable period
* @param _safetyPeriod withdraw disable period
*/
function setWithdrawSafetyPeriod(uint256 _withdrawPeriod, uint256 _safetyPeriod) external onlyGovernance {
generalParameters.withdrawPeriod = _withdrawPeriod;
generalParameters.safetyPeriod = _safetyPeriod;
emit SetWithdrawSafetyPeriod(generalParameters.withdrawPeriod, generalParameters.safetyPeriod);
}
//_descriptionHash - a hash of an ipfs encrypted file which describe the claim.
// this can be use later on by the claimer to prove her claim
function claim(string memory _descriptionHash) external payable {
if (generalParameters.claimFee > 0) {
require(msg.value >= generalParameters.claimFee, "not enough fee payed");
// solhint-disable-next-line indent
payable(governance()).transfer(msg.value);
}
emit Claim(msg.sender, _descriptionHash);
}
/**
* @dev setVestingParams - set pool vesting params for rewarding claim reporter with the pool token
* @param _pid pool id
* @param _duration duration of the vesting period
* @param _periods the vesting periods
*/
function setVestingParams(uint256 _pid, uint256 _duration, uint256 _periods) external onlyGovernance {
require(_duration < 120 days, "vesting duration is too long");
require(_periods > 0, "vesting periods cannot be zero");
require(_duration >= _periods, "vesting duration smaller than periods");
poolsRewards[_pid].vestingDuration = _duration;
poolsRewards[_pid].vestingPeriods = _periods;
emit SetVestingParams(_pid, _duration, _periods);
}
/**
* @dev setHatVestingParams - set HAT vesting params for rewarding claim reporter with HAT token
* the function can be called only by governance.
* @param _duration duration of the vesting period
* @param _periods the vesting periods
*/
function setHatVestingParams(uint256 _duration, uint256 _periods) external onlyGovernance {
require(_duration < 180 days, "vesting duration is too long");
require(_periods > 0, "vesting periods cannot be zero");
require(_duration >= _periods, "vesting duration smaller than periods");
generalParameters.hatVestingDuration = _duration;
generalParameters.hatVestingPeriods = _periods;
emit SetHatVestingParams(_duration, _periods);
}
/**
* @dev setRewardsSplit - set the pool token rewards split upon an approval
* the function can be called only by governance.
* the sum of the rewards split should be less than 10000 (less than 100%)
* @param _pid pool id
* @param _rewardsSplit split
* and sent to the hacker(claim reported)
*/
function setRewardsSplit(uint256 _pid, RewardsSplit memory _rewardsSplit)
external
onlyGovernance noPendingApproval(_pid) noSafetyPeriod {
validateSplit(_rewardsSplit);
poolsRewards[_pid].rewardsSplit = _rewardsSplit;
emit SetRewardsSplit(_pid, _rewardsSplit);
}
/**
* @dev setRewardsLevelsDelay - set the timelock delay for setting rewars level
* @param _delay time delay
*/
function setRewardsLevelsDelay(uint256 _delay)
external
onlyGovernance {
require(_delay >= 2 days, "delay is too short");
generalParameters.setRewardsLevelsDelay = _delay;
}
/**
* @dev setPendingRewardsLevels - set pending request to set pool token rewards level.
* the reward level represent the percentage of the pool's token which will be split as a reward.
* the function can be called only by the pool committee.
* cannot be called if there already pending approval.
* each level should be less than 10000
* @param _pid pool id
* @param _rewardsLevels the reward levels array
*/
function setPendingRewardsLevels(uint256 _pid, uint256[] memory _rewardsLevels)
external
onlyCommittee(_pid) noPendingApproval(_pid) {
pendingRewardsLevels[_pid].rewardsLevels = checkRewardsLevels(_rewardsLevels);
// solhint-disable-next-line not-rely-on-time
pendingRewardsLevels[_pid].timestamp = block.timestamp;
emit PendingRewardsLevelsLog(_pid, _rewardsLevels, pendingRewardsLevels[_pid].timestamp);
}
/**
* @dev setRewardsLevels - set the pool token rewards level of already pending set rewards level.
* see pendingRewardsLevels
* the reward level represent the percentage of the pool's token which will be split as a reward.
* the function can be called only by the pool committee.
* cannot be called if there already pending approval.
* each level should be less than 10000
* @param _pid pool id
*/
function setRewardsLevels(uint256 _pid)
external
onlyCommittee(_pid) noPendingApproval(_pid) {
require(pendingRewardsLevels[_pid].timestamp > 0, "no pending set rewards levels");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - pendingRewardsLevels[_pid].timestamp > generalParameters.setRewardsLevelsDelay,
"cannot confirm setRewardsLevels at this time");
poolsRewards[_pid].rewardsLevels = pendingRewardsLevels[_pid].rewardsLevels;
delete pendingRewardsLevels[_pid];
emit SetRewardsLevels(_pid, poolsRewards[_pid].rewardsLevels);
}
/**
* @dev committeeCheckIn - committee check in.
* deposit is enable only after committee check in
* @param _pid pool id
*/
function committeeCheckIn(uint256 _pid) external onlyCommittee(_pid) {
poolsRewards[_pid].committeeCheckIn = true;
}
/**
* @dev setCommittee - set new committee address.
* @param _pid pool id
* @param _committee new committee address
*/
function setCommittee(uint256 _pid, address _committee)
external {
require(_committee != address(0), "committee is zero");
//governance can update committee only if committee was not checked in yet.
if (msg.sender == governance() && committees[_pid] != msg.sender) {
require(!poolsRewards[_pid].committeeCheckIn, "Committee already checked in");
} else {
require(committees[_pid] == msg.sender, "Only committee");
}
committees[_pid] = _committee;
emit SetCommittee(_pid, _committee);
}
/**
* @dev addPool - only Governance
* @param _allocPoint the pool allocation point
* @param _lpToken pool token
* @param _committee pool committee address
* @param _rewardsLevels pool reward levels(sevirities)
each level is a number between 0 and 10000.
* @param _rewardsSplit pool reward split.
each entry is a number between 0 and 10000.
total splits should be equal to 10000
* @param _descriptionHash the hash of the pool description.
* @param _rewardVestingParams vesting params
* _rewardVestingParams[0] - vesting duration
* _rewardVestingParams[1] - vesting periods
*/
function addPool(uint256 _allocPoint,
address _lpToken,
address _committee,
uint256[] memory _rewardsLevels,
RewardsSplit memory _rewardsSplit,
string memory _descriptionHash,
uint256[2] memory _rewardVestingParams)
external
onlyGovernance {
require(_rewardVestingParams[0] < 120 days, "vesting duration is too long");
require(_rewardVestingParams[1] > 0, "vesting periods cannot be zero");
require(_rewardVestingParams[0] >= _rewardVestingParams[1], "vesting duration smaller than periods");
require(_committee != address(0), "committee is zero");
add(_allocPoint, IERC20(_lpToken));
uint256 poolId = poolInfo.length-1;
committees[poolId] = _committee;
uint256[] memory rewardsLevels = checkRewardsLevels(_rewardsLevels);
RewardsSplit memory rewardsSplit = (_rewardsSplit.hackerVestedReward == 0 && _rewardsSplit.hackerReward == 0) ?
getDefaultRewardsSplit() : _rewardsSplit;
validateSplit(rewardsSplit);
poolsRewards[poolId] = PoolReward({
rewardsLevels: rewardsLevels,
rewardsSplit: rewardsSplit,
committeeCheckIn: false,
vestingDuration: _rewardVestingParams[0],
vestingPeriods: _rewardVestingParams[1]
});
emit AddPool(poolId,
_allocPoint,
address(_lpToken),
_committee,
_descriptionHash,
rewardsLevels,
rewardsSplit,
_rewardVestingParams[0],
_rewardVestingParams[1]);
}
/**
* @dev setPool
* @param _pid the pool id
* @param _allocPoint the pool allocation point
* @param _registered does this pool is registered (default true).
* @param _depositPause pause pool deposit (default false).
* This parameter can be used by the UI to include or exclude the pool
* @param _descriptionHash the hash of the pool description.
*/
function setPool(uint256 _pid,
uint256 _allocPoint,
bool _registered,
bool _depositPause,
string memory _descriptionHash)
external onlyGovernance {
require(poolInfo[_pid].lpToken != IERC20(address(0)), "pool does not exist");
set(_pid, _allocPoint);
poolDepositPause[_pid] = _depositPause;
emit SetPool(_pid, _allocPoint, _registered, _descriptionHash);
}
/**
* @dev swapBurnSend swap lptoken to HAT.
* send to beneficiary and governance its hats rewards .
* burn the rest of HAT.
* only governance are authorized to call this function.
* @param _pid the pool id
* @param _beneficiary beneficiary
* @param _amountOutMinimum minimum output of HATs at swap
* @param _fees the fees for the multi path swap
**/
function swapBurnSend(uint256 _pid,
address _beneficiary,
uint256 _amountOutMinimum,
uint24[2] memory _fees)
external
onlyGovernance {
IERC20 token = poolInfo[_pid].lpToken;
uint256 amountToSwapAndBurn = swapAndBurns[address(token)];
uint256 amountForHackersHatRewards = hackersHatRewards[_beneficiary][address(token)];
uint256 amount = amountToSwapAndBurn.add(amountForHackersHatRewards).add(governanceHatRewards[address(token)]);
require(amount > 0, "amount is zero");
swapAndBurns[address(token)] = 0;
governanceHatRewards[address(token)] = 0;
hackersHatRewards[_beneficiary][address(token)] = 0;
uint256 hatsReceived = swapTokenForHAT(amount, token, _fees, _amountOutMinimum);
uint256 burntHats = hatsReceived.mul(amountToSwapAndBurn).div(amount);
if (burntHats > 0) {
HAT.burn(burntHats);
}
emit SwapAndBurn(_pid, amount, burntHats);
address tokenLock;
uint256 hackerReward = hatsReceived.mul(amountForHackersHatRewards).div(amount);
if (hackerReward > 0) {
//hacker get its reward via vesting contract
tokenLock = tokenLockFactory.createTokenLock(
address(HAT),
0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing.
_beneficiary,
hackerReward,
// solhint-disable-next-line not-rely-on-time
block.timestamp, //start
// solhint-disable-next-line not-rely-on-time
block.timestamp + generalParameters.hatVestingDuration, //end
generalParameters.hatVestingPeriods,
0, //no release start
0, //no cliff
ITokenLock.Revocability.Disabled,
true
);
HAT.transfer(tokenLock, hackerReward);
}
emit SwapAndSend(_pid, _beneficiary, amount, hackerReward, tokenLock);
HAT.transfer(governance(), hatsReceived.sub(hackerReward).sub(burntHats));
}
/**
* @dev withdrawRequest submit a withdraw request
* @param _pid the pool id
**/
function withdrawRequest(uint256 _pid) external {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp > withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod,
"pending withdraw request exist");
// solhint-disable-next-line not-rely-on-time
withdrawRequests[_pid][msg.sender] = block.timestamp + generalParameters.withdrawRequestPendingPeriod;
emit WithdrawRequest(_pid, msg.sender, withdrawRequests[_pid][msg.sender]);
}
/**
* @dev deposit deposit to pool
* @param _pid the pool id
* @param _amount amount of pool's token to deposit
**/
function deposit(uint256 _pid, uint256 _amount) external {
require(!poolDepositPause[_pid], "deposit paused");
require(_amount >= MINIMUM_DEPOSIT, "amount less than 1e6");
//clear withdraw request
withdrawRequests[_pid][msg.sender] = 0;
_deposit(_pid, _amount);
}
/**
* @dev withdraw - withdraw user's pool share.
* user need first to submit a withdraw request.
* @param _pid the pool id
* @param _shares amount of shares user wants to withdraw
**/
function withdraw(uint256 _pid, uint256 _shares) external {
checkWithdrawRequest(_pid);
_withdraw(_pid, _shares);
}
/**
* @dev emergencyWithdraw withdraw all user's pool share without claim for reward.
* user need first to submit a withdraw request.
* @param _pid the pool id
**/
function emergencyWithdraw(uint256 _pid) external {
checkWithdrawRequest(_pid);
_emergencyWithdraw(_pid);
}
function getPoolRewardsLevels(uint256 _pid) external view returns(uint256[] memory) {
return poolsRewards[_pid].rewardsLevels;
}
function getPoolRewards(uint256 _pid) external view returns(PoolReward memory) {
return poolsRewards[_pid];
}
// GET INFO for UI
/**
* @dev getRewardPerBlock return the current pool reward per block
* @param _pid1 the pool id.
* if _pid1 = 0 , it return the current block reward for whole pools.
* otherwise it return the current block reward for _pid1-1.
* @return rewardPerBlock
**/
function getRewardPerBlock(uint256 _pid1) external view returns (uint256) {
if (_pid1 == 0) {
return getRewardForBlocksRange(block.number-1, block.number, 1, 1);
} else {
return getRewardForBlocksRange(block.number-1,
block.number,
poolInfo[_pid1 - 1].allocPoint,
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint);
}
}
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 rewardPerShare = pool.rewardPerShare;
if (block.number > pool.lastRewardBlock && pool.totalUsersAmount > 0) {
uint256 reward = calcPoolReward(_pid, pool.lastRewardBlock, globalPoolUpdates.length-1);
rewardPerShare = rewardPerShare.add(reward.mul(1e12).div(pool.totalUsersAmount));
}
return user.amount.mul(rewardPerShare).div(1e12).sub(user.rewardDebt);
}
function getGlobalPoolUpdatesLength() external view returns (uint256) {
return globalPoolUpdates.length;
}
function getStakedAmount(uint _pid, address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_pid][_user];
return user.amount;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function calcClaimRewards(uint256 _pid, uint256 _severity)
public
view
returns(ClaimReward memory claimRewards) {
uint256 totalSupply = poolInfo[_pid].balance;
require(totalSupply > 0, "totalSupply is zero");
require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range");
//hackingRewardAmount
uint256 claimRewardAmount =
totalSupply.mul(poolsRewards[_pid].rewardsLevels[_severity]);
claimRewards.hackerVestedReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerVestedReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.hackerReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.committeeReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.committeeReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.swapAndBurn =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.swapAndBurn)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.governanceHatReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.governanceHatReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.hackerHatReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerHatReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
}
function getDefaultRewardsSplit() public pure returns (RewardsSplit memory) {
return RewardsSplit({
hackerVestedReward: 6000,
hackerReward: 2000,
committeeReward: 500,
swapAndBurn: 0,
governanceHatReward: 1000,
hackerHatReward: 500
});
}
function validateSplit(RewardsSplit memory _rewardsSplit) internal pure {
require(_rewardsSplit.hackerVestedReward
.add(_rewardsSplit.hackerReward)
.add(_rewardsSplit.committeeReward)
.add(_rewardsSplit.swapAndBurn)
.add(_rewardsSplit.governanceHatReward)
.add(_rewardsSplit.hackerHatReward) == REWARDS_LEVEL_DENOMINATOR,
"total split % should be 10000");
}
function checkWithdrawRequest(uint256 _pid) internal noPendingApproval(_pid) noSafetyPeriod {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp > withdrawRequests[_pid][msg.sender] &&
// solhint-disable-next-line not-rely-on-time
block.timestamp < withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod,
"withdraw request not valid");
withdrawRequests[_pid][msg.sender] = 0;
}
function swapTokenForHAT(uint256 _amount,
IERC20 _token,
uint24[2] memory _fees,
uint256 _amountOutMinimum)
internal
returns (uint256 hatsReceived)
{
if (address(_token) == address(HAT)) {
return _amount;
}
require(_token.approve(address(uniSwapRouter), _amount), "token approve failed");
uint256 hatBalanceBefore = HAT.balanceOf(address(this));
address weth = uniSwapRouter.WETH9();
bytes memory path;
if (address(_token) == weth) {
path = abi.encodePacked(address(_token), _fees[0], address(HAT));
} else {
path = abi.encodePacked(address(_token), _fees[0], weth, _fees[1], address(HAT));
}
hatsReceived = uniSwapRouter.exactInput(ISwapRouter.ExactInputParams({
path: path,
recipient: address(this),
// solhint-disable-next-line not-rely-on-time
deadline: block.timestamp,
amountIn: _amount,
amountOutMinimum: _amountOutMinimum
}));
require(HAT.balanceOf(address(this)) - hatBalanceBefore >= _amountOutMinimum, "wrong amount received");
}
/**
* @dev checkRewardsLevels - check rewards levels.
* each level should be less than 10000
* if _rewardsLevels length is 0 a default reward levels will be return
* default reward levels = [2000, 4000, 6000, 8000]
* @param _rewardsLevels the reward levels array
* @return rewardsLevels
*/
function checkRewardsLevels(uint256[] memory _rewardsLevels)
private
pure
returns (uint256[] memory rewardsLevels) {
uint256 i;
if (_rewardsLevels.length == 0) {
rewardsLevels = new uint256[](4);
for (i; i < 4; i++) {
//defaultRewardLevels = [2000, 4000, 6000, 8000];
rewardsLevels[i] = 2000*(i+1);
}
} else {
for (i; i < _rewardsLevels.length; i++) {
require(_rewardsLevels[i] < REWARDS_LEVEL_DENOMINATOR, "reward level can not be more than 10000");
}
rewardsLevels = _rewardsLevels;
}
}
}
// File contracts/HATTimelockController.sol
// Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md
pragma solidity 0.8.6;
contract HATTimelockController is TimelockController {
HATVaults public hatVaults;
constructor(
HATVaults _hatVaults,
uint256 _minDelay,
address[] memory _proposers,
address[] memory _executors
// solhint-disable-next-line func-visibility
) TimelockController(_minDelay, _proposers, _executors) {
require(address(_hatVaults) != address(0), "HATTimelockController: HATVaults address must not be 0");
hatVaults = _hatVaults;
}
// Whitelisted functions
function approveClaim(uint256 _pid) external onlyRole(PROPOSER_ROLE) {
hatVaults.approveClaim(_pid);
}
function addPool(uint256 _allocPoint,
address _lpToken,
address _committee,
uint256[] memory _rewardsLevels,
HATVaults.RewardsSplit memory _rewardsSplit,
string memory _descriptionHash,
uint256[2] memory _rewardVestingParams)
external
onlyRole(PROPOSER_ROLE) {
hatVaults.addPool(
_allocPoint,
_lpToken,
_committee,
_rewardsLevels,
_rewardsSplit,
_descriptionHash,
_rewardVestingParams
);
}
function setPool(uint256 _pid,
uint256 _allocPoint,
bool _registered,
bool _depositPause,
string memory _descriptionHash)
external onlyRole(PROPOSER_ROLE) {
hatVaults.setPool(
_pid,
_allocPoint,
_registered,
_depositPause,
_descriptionHash
);
}
function swapBurnSend(uint256 _pid,
address _beneficiary,
uint256 _amountOutMinimum,
uint24[2] memory _fees)
external
onlyRole(PROPOSER_ROLE) {
hatVaults.swapBurnSend(
_pid,
_beneficiary,
_amountOutMinimum,
_fees
);
}
}
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/ solhint-disable-next-line not-rely-on-time
|
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "HAT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "HAT::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "HAT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 2,322,277
|
pragma solidity 0.4.19;
/**
* @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) {
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;
}
}
/**
* @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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
function AllowanceCrowdsale(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title RTEBonusTokenVault
* @dev Token holder contract that releases tokens to the respective addresses
* and _lockedReleaseTime
*/
contract RTEBonusTokenVault is Ownable {
using SafeERC20 for ERC20Basic;
using SafeMath for uint256;
// ERC20 basic token contract being held
ERC20Basic public token;
bool public vaultUnlocked;
bool public vaultSecondaryUnlocked;
// How much we have allocated to the investors invested
mapping(address => uint256) public balances;
mapping(address => uint256) public lockedBalances;
/**
* @dev Allocation event
* @param _investor Investor address
* @param _value Tokens allocated
*/
event Allocated(address _investor, uint256 _value);
/**
* @dev Distribution event
* @param _investor Investor address
* @param _value Tokens distributed
*/
event Distributed(address _investor, uint256 _value);
function RTEBonusTokenVault(
ERC20Basic _token
)
public
{
token = _token;
vaultUnlocked = false;
vaultSecondaryUnlocked = false;
}
/**
* @dev Unlocks vault
*/
function unlock() public onlyOwner {
require(!vaultUnlocked);
vaultUnlocked = true;
}
/**
* @dev Unlocks secondary vault
*/
function unlockSecondary() public onlyOwner {
require(vaultUnlocked);
require(!vaultSecondaryUnlocked);
vaultSecondaryUnlocked = true;
}
/**
* @dev Add allocation amount to investor addresses
* Only the owner of this contract - the crowdsale can call this function
* Split half to be locked by timelock in vault, the other half to be released on vault unlock
* @param _investor Investor address
* @param _amount Amount of tokens to add
*/
function allocateInvestorBonusToken(address _investor, uint256 _amount) public onlyOwner {
require(!vaultUnlocked);
require(!vaultSecondaryUnlocked);
uint256 bonusTokenAmount = _amount.div(2);
uint256 bonusLockedTokenAmount = _amount.sub(bonusTokenAmount);
balances[_investor] = balances[_investor].add(bonusTokenAmount);
lockedBalances[_investor] = lockedBalances[_investor].add(bonusLockedTokenAmount);
Allocated(_investor, _amount);
}
/**
* @dev Transfers bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claim(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
uint256 claimAmount = balances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
balances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
/**
* @dev Transfers secondary bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claimLocked(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
require(vaultSecondaryUnlocked);
uint256 claimAmount = lockedBalances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
lockedBalances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Whitelisted Pausable token
* @dev StandardToken modified with pausable transfers. Enables a whitelist to enable transfers
* only for certain addresses such as crowdsale contract, issuing account etc.
**/
contract WhitelistedPausableToken is StandardToken, Pausable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if the message sender requesting for transfer is not whitelisted when token
* transfers are paused
* @param _sender check transaction sender address
*/
modifier whenNotPausedOrWhitelisted(address _sender) {
require(whitelist[_sender] || !paused);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _whitelistAddress Address to be added to the whitelist
*/
function addToWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _whitelistAddresses Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _whitelistAddresses) external onlyOwner {
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
whitelist[_whitelistAddresses[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _whitelistAddress Address to be removed to the whitelist
*/
function removeFromWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = false;
}
// Adding modifier to transfer/approval functions
function transfer(address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title RTEToken
* @dev ERC20 token implementation
* Pausable
*/
contract RTEToken is WhitelistedPausableToken {
string public constant name = "Rate3";
string public constant symbol = "RTE";
uint8 public constant decimals = 18;
// 1 billion initial supply of RTE tokens
// Taking into account 18 decimals
uint256 public constant INITIAL_SUPPLY = (10 ** 9) * (10 ** 18);
/**
* @dev RTEToken Constructor
* Mints the initial supply of tokens, this is the hard cap, no more tokens will be minted.
* Allocate the tokens to the foundation wallet, issuing wallet etc.
*/
function RTEToken() public {
// Mint initial supply of tokens. All further minting of tokens is disabled
totalSupply_ = INITIAL_SUPPLY;
// Transfer all initial tokens to msg.sender
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title RTECrowdsale
* @dev test
*/
contract RTECrowdsale is AllowanceCrowdsale, WhitelistedCrowdsale, FinalizableCrowdsale {
using SafeERC20 for ERC20;
uint256 public constant minimumInvestmentInWei = 0.5 ether;
uint256 public allTokensSold;
uint256 public bonusTokensSold;
uint256 public cap;
mapping (address => uint256) public tokenInvestments;
mapping (address => uint256) public bonusTokenInvestments;
RTEBonusTokenVault public bonusTokenVault;
/**
* @dev Contract initialization parameters
* @param _openingTime Public crowdsale opening time
* @param _closingTime Public crowdsale closing time
* @param _rate Initial rate (Maybe remove, put as constant)
* @param _cap RTE token issue cap (Should be the same amount as approved allowance from issueWallet)
* @param _wallet Multisig wallet to send ether raised to
* @param _issueWallet Wallet that approves allowance of tokens to be issued
* @param _token RTE token address deployed seperately
*/
function RTECrowdsale(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _cap,
address _wallet,
address _issueWallet,
RTEToken _token
)
AllowanceCrowdsale(_issueWallet)
TimedCrowdsale(_openingTime, _closingTime)
Crowdsale(_rate, _wallet, _token)
public
{
require(_cap > 0);
cap = _cap;
bonusTokenVault = new RTEBonusTokenVault(_token);
}
/**
* @dev Checks whether the cap for RTE has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return allTokensSold >= cap;
}
/**
* @dev Calculate bonus RTE percentage to be allocated based on time rules
* time is calculated by now = block.timestamp, will be consistent across transaction if called
* multiple times in same transaction
* @return Bonus percentage in percent value
*/
function _calculateBonusPercentage() internal view returns (uint256) {
return 20;
}
/**
* @dev Get current RTE balance of bonus token vault
*/
function getRTEBonusTokenVaultBalance() public view returns (uint256) {
return token.balanceOf(address(bonusTokenVault));
}
/**
* @dev Extend parent behavior requiring purchase to respect minimum investment per transaction.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(msg.value >= minimumInvestmentInWei);
}
/**
* @dev Keep track of tokens purchased extension functionality
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Value in amount of token purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
uint256 bonusPercentage = _calculateBonusPercentage();
uint256 additionalBonusTokens = _tokenAmount.mul(bonusPercentage).div(100);
uint256 tokensSold = _tokenAmount;
// Check if exceed token sale cap
uint256 newAllTokensSold = allTokensSold.add(tokensSold).add(additionalBonusTokens);
require(newAllTokensSold <= cap);
// Process purchase
super._processPurchase(_beneficiary, tokensSold);
allTokensSold = allTokensSold.add(tokensSold);
tokenInvestments[_beneficiary] = tokenInvestments[_beneficiary].add(tokensSold);
if (additionalBonusTokens > 0) {
// Record bonus tokens allocated and transfer it to RTEBonusTokenVault
allTokensSold = allTokensSold.add(additionalBonusTokens);
bonusTokensSold = bonusTokensSold.add(additionalBonusTokens);
bonusTokenVault.allocateInvestorBonusToken(_beneficiary, additionalBonusTokens);
bonusTokenInvestments[_beneficiary] = bonusTokenInvestments[_beneficiary].add(additionalBonusTokens);
}
}
/**
* @dev Unlock secondary tokens, can only be done by owner of contract
*/
function unlockSecondaryTokens() public onlyOwner {
require(isFinalized);
bonusTokenVault.unlockSecondary();
}
/**
* @dev Claim bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claim(_beneficiary);
}
/**
* @dev Claim timelocked bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimLockedBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claimLocked(_beneficiary);
}
/**
* @dev Called manually when token sale has ended with finalize()
*/
function finalization() internal {
// Credit bonus tokens sold to bonusTokenVault
token.transferFrom(tokenWallet, bonusTokenVault, bonusTokensSold);
// Unlock bonusTokenVault for non-timelocked tokens to be claimed
bonusTokenVault.unlock();
super.finalization();
}
}
|
Transfers secondary bonus tokens held to investor _investor Investor address making the claim/ _investor is the original initiator msg.sender is the contract that called this. Empty token balance
|
function claimLocked(address _investor) public onlyOwner {
require(vaultUnlocked);
require(vaultSecondaryUnlocked);
uint256 claimAmount = lockedBalances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
lockedBalances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
| 1,836,636
|
./full_match/1/0x8e46515d5881E4c83360d9A7447F475aa7CaA2bA/sources/contracts/WDUM.sol
|
Burns the tokens from owner's account./
|
function burn(uint256 amount) external returns(bool) {
address owner = msg.sender;
require(balanceOf(owner) >= amount * 10 ** _decimals, "Invalid amount");
_balances[owner] -= amount;
_burn(owner, amount);
return true;
}
INTERNAL FUNCTIONS
| 3,018,521
|
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.1;
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
);
}
/**
* @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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
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);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract R is Context,IERC20,Ownable {
using Address for address;
using SafeMath for uint256;
mapping (address => uint256) public _cooldown;
mapping (address => uint256) public _rOwned;
mapping (address => uint256) public _tOwned;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) public _blacklisted;
mapping (address => bool) public _lpPairs;
mapping (address => bool) public _isExcludedFromFee;
mapping (address => bool) public _isExcluded;
mapping (address => bool) public _preTrader;
mapping (address => bool) public _lpHolder;
uint8 public constant _decimals = 9;
uint16 totalFee;
uint16 taxFee;
uint16 public constant taxDivisor = 10000;
uint256 private constant MAX = ~uint256(0);
uint256 public constant startingSupply = 10_000_000;
uint256 public constant _tTotal = startingSupply * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "R";
string private constant _symbol = "R";
bool public feesEnabled;
struct IFees {
uint16 taxFee;
uint16 liquidityFee;
uint16 marketingFee;
uint16 totalFee;
}
struct ILaunch {
uint256 launchedAt;
uint256 launchBlock;
uint256 antiBlocks;
bool tradingOpen;
bool launched;
bool launchProtection;
}
struct ICooldown {
bool buycooldownEnabled;
bool sellcooldownEnabled;
uint256 cooldownLimit;
uint256 cooldownTime;
}
struct ILiquiditySettings {
uint256 liquidityFeeAccumulator;
uint256 numTokensToSwap;
uint256 lastSwap;
uint8 swapInterval;
bool swapEnabled;
bool marketing;
bool inSwap;
}
struct ITransactionSettings {
uint256 maxTxAmount;
uint256 maxWalletAmount;
bool txLimits;
}
IFees public MaxFees;
IFees public BuyFees;
IFees public SellFees;
IFees public TransferFees;
ICooldown public Cooldown;
ILaunch public Launch;
ILiquiditySettings public LiquiditySettings;
ITransactionSettings public TransactionSettings;
IUniswapV2Router02 public immutable router;
address public lpPair;
address payable public marketingWallet;
address[] private _excluded;
event areFeesEnabled(bool enabled);
event MinTokensBeforeSwapUpdated(uint256 indexed minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(uint256 eth, uint256 tokensIntoLiquidity);
event SwapToMarketing(uint256 eth);
modifier lockTheSwap {
LiquiditySettings.inSwap = true;
_;
LiquiditySettings.inSwap = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
marketingWallet = payable(owner());
_lpHolder[owner()] = true;
Cooldown.cooldownLimit = 60;
IUniswapV2Router02 _router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
lpPair = IUniswapV2Factory(_router.factory())
.createPair(address(this), _router.WETH());
// set the rest of the contract variables
router = _router;
_lpPairs[lpPair] = true;
_approve(_msgSender(), address(_router), type(uint256).max);
_approve(address(this), address(_router), type(uint256).max);
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_preTrader[owner()] = true;
_lpHolder[owner()] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero"));
return true;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) private {
address sender = _msgSender();
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
if(_isExcluded[msg.sender])
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
// Exclude or Include from Fees
function excludeFromFee(address account, bool FeeLess) public onlyOwner {
_isExcludedFromFee[account] = FeeLess;
}
// Sets marketing wallet
function setWallet(address payable m) external onlyOwner() {
marketingWallet = m;
}
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tFees) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tFees, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tFees);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = (tAmount * taxFee) / taxDivisor;
uint256 tFees = (tAmount * totalFee) / taxDivisor;
uint256 tTransferAmount = tAmount.sub(tFee).sub(tFees);
return (tTransferAmount, tFee, tFees);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tFees, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rFees = tFees.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rFees);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function getCirculatingSupply() external view returns(uint256){
return _tTotal - balanceOf(address(0xDead));
}
function _takeFees(uint256 tFees) private {
uint256 currentRate = _getRate();
uint256 rFees = tFees.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rFees);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tFees);
}
function _takeMarketing(uint256 marketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = marketing.mul(currentRate);
_rOwned[marketingWallet] = _rOwned[marketingWallet].add(rMarketing);
if(_isExcluded[marketingWallet])
_tOwned[marketingWallet] = _tOwned[marketingWallet].add(marketing);
}
function limits(address from, address to) private view returns (bool) {
return from != owner()
&& to != owner()
&& tx.origin != owner()
&& !_lpHolder[from]
&& !_lpHolder[to]
&& to != address(0xdead)
&& to != address(0)
&& from != address(this);
}
// Transfer functions
function _transfer(
address from,
address to,
uint256 amount
) private returns (bool){
require(from != address(0), "BEP20: transfer from the zero address");
require(to != address(0), "BEP20: transfer to the zero address");
require(!_blacklisted[from], "TOKEN: Your account is blacklisted!");
require(!_blacklisted[to], "TOKEN: Your account is blacklisted!");
require(amount > 0, "BEP20: Transfer amount must be greater than zero");
if(from != owner() && to != owner()){
if(!Launch.tradingOpen){
require(_preTrader[from] || _preTrader[to]);
}
if (limits(from, to)) {
if(Launch.tradingOpen && Launch.launched){
if(TransactionSettings.txLimits) {
if (_lpPairs[from] || _lpPairs[to]) {
if(!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(amount <= TransactionSettings.maxTxAmount);
}
if(to != address(router) && !_lpPairs[to]) {
if(!_isExcludedFromFee[to]){
require(balanceOf(to) + amount < TransactionSettings.maxWalletAmount, "TOKEN: Balance exceeds wallet size!");
}
}
if (_lpPairs[from] && to != address(router) && !_isExcludedFromFee[to] && Cooldown.buycooldownEnabled) {
require(_cooldown[to] < block.timestamp);
_cooldown[to] = block.timestamp + (Cooldown.cooldownTime);
} else if (!_lpPairs[from] && !_isExcludedFromFee[from] && Cooldown.sellcooldownEnabled){
require(_cooldown[from] <= block.timestamp);
_cooldown[from] = block.timestamp + (Cooldown.cooldownTime);
}
}
}
if(_lpPairs[to]){
if(LiquiditySettings.swapEnabled && !LiquiditySettings.inSwap){
if(balanceOf(address(this)) >= LiquiditySettings.numTokensToSwap) {
if(LiquiditySettings.liquidityFeeAccumulator >= LiquiditySettings.numTokensToSwap && block.timestamp >= LiquiditySettings.lastSwap + LiquiditySettings.swapInterval){
swapAndLiquify();
LiquiditySettings.lastSwap = block.timestamp;
} else {
if(block.timestamp >= LiquiditySettings.lastSwap + LiquiditySettings.swapInterval){
swapForMarketing();
LiquiditySettings.lastSwap = block.timestamp;
}
}
}
}
}
}
}
}
// transfer amount, it will set fees and auto blacklist snipers
return (_tokenTransfer(from,to,amount));
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private returns (bool){
if(Launch.launched){
setFee(sender, recipient);
if(Launch.launchProtection){
if (_lpPairs[sender] && recipient != address(router) && !_isExcludedFromFee[recipient]) {
if (block.number <= Launch.launchedAt + Launch.antiBlocks) {
if(!_lpPairs[recipient]){
_setSniperStatus(recipient, true);
}
} else {
Launch.launchProtection = false;
}
}
}
}
// transfers and takes fees
if(!Launch.launched){
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
return true;
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
if(!Launch.launched){
uint256 rAmount = tAmount.mul(_getRate());
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
} else {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFees) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
if(!LiquiditySettings.marketing){
_takeFees(tFees);
uint16 taxCorrection = (BuyFees.taxFee + SellFees.taxFee + TransferFees.taxFee);
LiquiditySettings.liquidityFeeAccumulator += (tFees * (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee)) / ((BuyFees.totalFee + SellFees.totalFee + TransferFees.totalFee) - taxCorrection) + (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee);
} else {
_takeMarketing(tFees);
}
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFees) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
if(!LiquiditySettings.marketing){
_takeFees(tFees);
uint16 taxCorrection = (BuyFees.taxFee + SellFees.taxFee + TransferFees.taxFee);
LiquiditySettings.liquidityFeeAccumulator += (tFees * (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee)) / ((BuyFees.totalFee + SellFees.totalFee + TransferFees.totalFee) - taxCorrection) + (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee);
} else {
_takeMarketing(tFees);
}
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFees) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
if(!LiquiditySettings.marketing){
_takeFees(tFees);
uint16 taxCorrection = (BuyFees.taxFee + SellFees.taxFee + TransferFees.taxFee);
LiquiditySettings.liquidityFeeAccumulator += (tFees * (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee)) / ((BuyFees.totalFee + SellFees.totalFee + TransferFees.totalFee) - taxCorrection) + (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee);
} else {
_takeMarketing(tFees);
}
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tFees) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
if(!LiquiditySettings.marketing){
_takeFees(tFees);
uint16 taxCorrection = (BuyFees.taxFee + SellFees.taxFee + TransferFees.taxFee);
LiquiditySettings.liquidityFeeAccumulator += (tFees * (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee)) / ((BuyFees.totalFee + SellFees.totalFee + TransferFees.totalFee) - taxCorrection) + (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee);
} else {
_takeMarketing(tFees);
}
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
// Sets the Fees
function setFee(address sender, address recipient) internal {
if(feesEnabled){
if (_lpPairs[recipient]) {
if(totalFee != SellFees.marketingFee + SellFees.liquidityFee){
totalFee = SellFees.marketingFee + SellFees.liquidityFee;
}
if(taxFee != SellFees.taxFee){
taxFee = SellFees.taxFee;
}
} else if(_lpPairs[sender]){
if(totalFee != BuyFees.marketingFee + BuyFees.liquidityFee){
totalFee = BuyFees.marketingFee + BuyFees.liquidityFee;
}
if(taxFee != BuyFees.taxFee){
taxFee = BuyFees.taxFee;
}
} else {
if(totalFee != TransferFees.marketingFee + TransferFees.liquidityFee){
totalFee = TransferFees.marketingFee + TransferFees.liquidityFee;
}
if(taxFee != TransferFees.taxFee){
taxFee = TransferFees.taxFee;
}
}
if(block.number <= Launch.launchBlock + Launch.antiBlocks){
totalFee += 500; // Adds 50% tax onto original tax
}
}
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient] || !feesEnabled) {
if(totalFee != 0 && taxFee != 0){
totalFee = 0;
taxFee = 0;
}
}
}
// set launch
function setTrading(bool _tradingOpen, uint8 sniperblocks) public onlyOwner {
require(sniperblocks <= 5);
Launch.tradingOpen = _tradingOpen;
FeesEnabled(_tradingOpen);
setCooldownEnabled(_tradingOpen, _tradingOpen, 30);
setNumTokensToSwap(1,1000);
setTxSettings(5,1000,1,100,_tradingOpen);
toggleSwap(_tradingOpen, 10);
if(!Launch.launched) {
setMaxFee(500,500,500, _tradingOpen);
setTransferFees(50,50,50);
Launch.launched = _tradingOpen;
Launch.antiBlocks = sniperblocks;
Launch.launchedAt = block.timestamp;
Launch.launchBlock = block.number;
Launch.launchProtection = _tradingOpen;
}
}
// Swaps tokens and adds to Liquidity
function swapAndLiquify() private lockTheSwap {
uint256 liquidityTokens = LiquiditySettings.numTokensToSwap / 2;
swapTokens(liquidityTokens);
uint256 toLiquidity = address(this).balance;
addLiquidity(liquidityTokens, toLiquidity);
emit SwapAndLiquify(toLiquidity, liquidityTokens);
LiquiditySettings.liquidityFeeAccumulator -= LiquiditySettings.numTokensToSwap;
}
// Swaps tokens and send to Marketing
function swapForMarketing() private lockTheSwap {
swapTokens(LiquiditySettings.numTokensToSwap);
uint256 toMarketing = address(this).balance;
marketingWallet.transfer(toMarketing);
emit SwapToMarketing(toMarketing);
}
// Swaps Token for Eth
function swapTokens(uint256 tokenAmount) private {
// generate the pancakeswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of BNB
path,
address(this),
block.timestamp
);
}
// Adds eth and token to Liqudity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(owner()),
block.timestamp
);
}
// Transaction functions
function setTxSettings(uint256 txp, uint256 txd, uint256 mwp, uint256 mwd, bool limit) public onlyOwner {
require((_tTotal * txp) / txd >= _tTotal / 1000, "Max Transaction must be above 0.1% of total supply.");
require((_tTotal * mwp) / mwd >= _tTotal / 1000, "Max Wallet must be above 0.1% of total supply.");
uint256 newTxAmount = (_tTotal * txp) / txd;
uint256 newMaxWalletAmount = (_tTotal * mwp) / mwd;
TransactionSettings = ITransactionSettings ({
maxTxAmount: newTxAmount,
maxWalletAmount: newMaxWalletAmount,
txLimits: limit
});
}
// Cooldown Settings
function setCooldownEnabled(bool onoff, bool offon, uint8 time) public onlyOwner {
require(time <= Cooldown.cooldownLimit);
Cooldown.cooldownTime = time;
Cooldown.buycooldownEnabled = onoff;
Cooldown.sellcooldownEnabled = offon;
}
// contract swap functions
function toggleSwap(bool _swapEnabled, uint8 swapInterval) public onlyOwner {
LiquiditySettings.swapEnabled = _swapEnabled;
LiquiditySettings.swapInterval = swapInterval;
}
// Receive tokens instead of Eth
function toggleMarketing(bool enabled) public onlyOwner {
LiquiditySettings.marketing = enabled;
}
// AirDrop
function airDropTokens(address[] memory addresses, uint256[] memory amounts) external {
require(addresses.length == amounts.length, "Lengths do not match.");
for (uint8 i = 0; i < addresses.length; i++) {
require(balanceOf(_msgSender()) >= amounts[i]);
_tokenTransfer(_msgSender(), addresses[i], amounts[i]*10**_decimals);
}
}
// Pretraders
function allowPreTrading(address account, bool allowed) public onlyOwner {
require(_preTrader[account] != allowed, "TOKEN: Already enabled.");
_preTrader[account] = allowed;
}
// Clear Stuck Tokens
function clearStuckBalance(uint256 amountPercentage) external onlyOwner {
require(amountPercentage <= 100);
uint256 amountETH = address(this).balance;
payable(marketingWallet).transfer(
(amountETH * amountPercentage) / 100
);
}
function clearStuckToken(address to) external onlyOwner {
uint256 _balance = balanceOf(address(this));
_transfer(address(this), to, _balance);
}
function clearStuckTokens(address _token, address _to) external onlyOwner returns (bool _sent) {
require(_token != address(0));
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
}
// Blacklist
function blockBots(address[] memory bots_, bool enabled) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
_blacklisted[bots_[i]] = enabled;
}
}
function _setSniperStatus(address account, bool blacklisted) internal {
if(_lpPairs[account] || account == address(this) || account == address(router) || _isExcludedFromFee[account]) {revert();}
if (blacklisted == true) {
_blacklisted[account] = true;
} else {
_blacklisted[account] = false;
}
}
// Set LP Holders
function setLpHolder(address holder, bool enabled) external onlyOwner {
_lpHolder[holder] = enabled;
}
// Setting new Lp Pairs
function setLpPair(address pair, bool enabled) external onlyOwner {
_lpPairs[pair] = enabled;
}
// Set minimum tokens required to swap.
function setNumTokensToSwap(uint256 percent, uint256 divisor) public onlyOwner {
LiquiditySettings.numTokensToSwap = (_tTotal * percent) / divisor;
}
// Fee Settings
function FeesEnabled(bool _enabled) public onlyOwner {
feesEnabled = _enabled;
emit areFeesEnabled(_enabled);
}
function setBuyFees(uint16 _liquidityFee, uint16 _marketingFee, uint16 _taxFee) public onlyOwner {
require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee);
BuyFees = IFees({
liquidityFee: _liquidityFee,
marketingFee: _marketingFee,
taxFee: _taxFee,
totalFee: _liquidityFee + _marketingFee + _taxFee
});
}
function setSellFees(uint16 _liquidityFee, uint16 _marketingFee, uint16 _taxFee) public onlyOwner {
require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee);
SellFees = IFees({
liquidityFee: _liquidityFee,
marketingFee: _marketingFee,
taxFee: _taxFee,
totalFee: _liquidityFee + _marketingFee + _taxFee
});
}
function setTransferFees(uint16 _liquidityFee, uint16 _marketingFee, uint16 _taxFee) public onlyOwner {
require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee);
TransferFees = IFees({
liquidityFee: _liquidityFee,
marketingFee: _marketingFee,
taxFee: _taxFee,
totalFee: _liquidityFee + _marketingFee + _taxFee
});
}
function setMaxFee(uint16 _taxFee, uint16 _liquidityFee, uint16 _marketingFee, bool resetFees) public onlyOwner {
if(!Launch.launched){
MaxFees = IFees({
taxFee: _taxFee,
liquidityFee: _liquidityFee,
marketingFee: _marketingFee,
totalFee: _taxFee + _liquidityFee + _marketingFee
});
}else{
require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee && _taxFee <= MaxFees.taxFee);
MaxFees = IFees({
taxFee: _taxFee,
liquidityFee: _liquidityFee,
marketingFee: _marketingFee,
totalFee: _taxFee + _liquidityFee + _marketingFee
});
if(resetFees){
setBuyFees(_liquidityFee, _marketingFee, _taxFee);
setSellFees(_liquidityFee, _marketingFee, _taxFee);
}
}
}
}
|
contract swap functions
|
function toggleSwap(bool _swapEnabled, uint8 swapInterval) public onlyOwner {
LiquiditySettings.swapEnabled = _swapEnabled;
LiquiditySettings.swapInterval = swapInterval;
}
| 12,613,161
|
// SPDX-License-Identifier: GPL-3.0
/**
* @title Complete the Punks: Project
* @dev Per-project contract for managing Bodies + Legs
* @author earlybail.eth | Cranky Brain Labs
* @notice #GetBodied #LegsFuknGooo
*/
/*
;╟██▓▒ :╟██▓▒
,φ▒╣╬╬╩╩Γ ╙╩╬╬╬▓▒░
,╓φ╣▓█╬Γ ╚╣█▓╬▒╓, ,,╓╓╓╓,
φ╣▓▓╬╩"" ""╚╣▓▓▒░ ]╟▓████▓▒
φφ╬╬╬╬╩╙ '╚╩╬╬╬▒▒░ φ╫███▓╬╬╬▓▒░
]╟▓█▓▒ :╟▓█▓▒ φ╫██╬▒ ╚╣█▓╬φ,,
:╟██▓▒ :╟██▓▒ φ╫██▓▒ "╙╠╣▓▓▒░
:╟██▓▒ :╟██▓▒ φφ▒▒▒▒╬╬╬╩╩' φ╫██▓▒
:╟██▓▒ ,,, :╟██▓▒ ]╟▓████▓╬⌐ φ╫██▓▒
:╟██▓▒ .╠╣▓▓▒ :╟██▓▒ :╟███╬╩"' φ╫██▓▒
:╟██▓▒ :╟██▓▒ φφ▒φ░ ,φ▒▒░ :╟██▓▒ :╟██▓▒ φ╫██▓▒
:╟██▓▒ :╟██▓▒ '╠▓█▓▒ ╚╣█▓╬⌐:╟███▒≥, '╠▓█▓╬≥, ,,φ╣██╬░
:╟██▓▒ :╟██▓▒ ^"╙"' "╙╙" :╟█████▓▒~ ^"╙╠╣▓▓▒~ φ╣▓▓╬╩╙"
:╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ╠▓██╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟███▒ ╚╟▓█╬▒╓╠▓██╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╚╣▓▓████╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬╬████╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟███▒╓, ╚╣██╬⌐ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟█████▓▒~ '"╙╙" ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ≤φ▒╬╬╬╬╚
:╟██▓▒ :╟██▓▒ :╟███▒ ╚╣██╬▒,,,,,,,φ╟▓█▓╩
:╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╩╬╣▓▓▓▓▓▓▓▓╬╬╚╙'
:╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬▓▓▓▓▓▓▓╬╩░
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ ]φ╣▓▒░ :╟██▓▒
:╟██▓▒ :╟██▓▒ "╠╬▓╩░ :╟██▓▒
:╟███▒, :╟██▓▒ :╟██▓▒
:╟████▓▒▒ :╟██▓▒ :╟██▓▒
╚╬█████▓▒▒╣██▓▒ :╟██▓▒
"╠▓████████▓▒ :╟██▓▒
*/
/*
φ╫██▓▒ :╟██▓▒
φ╫██▓▒ ,φ▒▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒░ :╟██▓▒
φ╫██▓▒ φ╣███████████████▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓╩╙╙╙╙╙╙╙╚╣██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ "╩╬▓╬▒φφ, :╟██▓▒ ╚╬▓╬╬▒φε
φ╫██▓▒ 7╟▓█▓▒, ;╟██▓▒ `╠╣█▓╬░
φ╫██▓▒ "╙╩╬╣▓▓▓▓▓███▓▒ ^╙╩╬╣▓▓▓▓▓▒░
φ╫██▓▒ ╚╠╣███████▓▒ "╠╬████╬╬▒φε
φ╫██▓▒ ```╠╠███▒, ```░╠╣██╬[
φ╫████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████╬[
"╠╬███████████████████████████████████████████████╬╩
`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/
// Directives.
pragma solidity 0.8.9;
// Third-party deps.
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
// Local deps.
import "./Bodies.sol";
import "./Legs.sol";
// Contract.
contract Project is ReentrancyGuard, Ownable, PaymentSplitter {
// Events.
event StatusChange(Status _newStatus);
// Mint statuses.
enum Status {
Paused,
Whitelist,
Mintpass,
Public
}
// Current mint status, defaults to Status[0] (Paused).
Status public status;
// Bodies.
Bodies public bodies;
// Legs.
Legs public legs;
// Pricing.
// @notice settable, use mintPrice() for latest.
uint256 public whitelistPrice = 0.02 ether;
uint256 public mintpassPrice = 0.04 ether;
uint256 public publicPrice = 0.04 ether;
// Mint limits.
// @notice settable, use mintLimit() for latest.
uint256 public whitelistMintLimit = 4;
uint256 public mintpassMintLimit = 20;
uint256 public publicMintLimit = 40;
// Max tokens.
uint256 public maxSupply = 10000;
// Mintpassed contracts.
address[] public mintpassedContracts;
// Whitelist Merkle root.
bytes32 public merkleRoot = 0x05ba199ba71527baf0f85acf24728a2e559447f3228c1ff56d0d90f8bb269f7d;
// Constructor.
constructor (
string memory _name,
string memory _symbol,
uint256 _tokenStartId,
address[] memory _payees,
uint256[] memory _shares
) PaymentSplitter(_payees, _shares) {
// Deploy and set Bodies contract.
bodies = new Bodies(
string(abi.encodePacked(_name, ": Bodies")), // Extend name.
string(abi.encodePacked(_symbol, "B")), // Extend symbol.
_tokenStartId
);
// Set this Project contract as parent project.
bodies.setProjectAddress(address(this));
// Transfer bodies contract ownership to deployer.
bodies.transferOwnership(_msgSender());
// Deploy and set Legs contract.
legs = new Legs(
string(abi.encodePacked(_name, ": Legs")), // Extend name.
string(abi.encodePacked(_symbol, "L")), // Extend symbol.
_tokenStartId
);
// Set this Project contract as parent project.
legs.setProjectAddress(address(this));
// Transfer legs contract ownership to deployer.
legs.transferOwnership(_msgSender());
}
// Mint check helper.
modifier mintCheck (address _to, uint256 _numToMint) {
// Early bail if paused.
require(status != Status.Paused, "Minting is paused");
// Ensure sender.
require(_to == _msgSender(), "Can only mint for self");
// Protect against contract minting.
require(!Address.isContract(_msgSender()), "Cannot mint from contract");
// Ensure non-zero mint amount.
require(_numToMint > 0, "Cannot mint zero tokens");
// Ensure available supply.
require(totalSupply() + _numToMint <= maxSupply, "Max supply exceeded");
// Ensure mint limit not exceeded.
require(_numToMint <= mintLimit(), "Cannot mint this many tokens");
// Ensure proper payment.
require(msg.value == _numToMint * mintPrice(), "Incorrect payment amount sent");
_;
}
// Set mint price.
function setPrice (Status _status, uint256 _newPrice) external onlyOwner {
if (_status == Status.Whitelist) {
whitelistPrice = _newPrice;
}
if (_status == Status.Mintpass) {
mintpassPrice = _newPrice;
}
if (_status == Status.Public) {
publicPrice = _newPrice;
}
}
// Set mint limit.
function setMintLimit (Status _status, uint256 _newLimit) external onlyOwner {
if (_status == Status.Whitelist) {
whitelistMintLimit = _newLimit;
}
if (_status == Status.Mintpass) {
mintpassMintLimit = _newLimit;
}
if (_status == Status.Public) {
publicMintLimit = _newLimit;
}
}
// Set the bodies contract.
function setBodies (address _newAddr) external onlyOwner {
bodies = Bodies(_newAddr);
}
// Set the legs contract.
function setLegs (address _newAddr) external onlyOwner {
legs = Legs(_newAddr);
}
// (Re-)set the whitelist Merkle root.
function setMerkleRoot (bytes32 _newRoot) external onlyOwner {
merkleRoot = _newRoot;
}
// Set the mint status.
function setStatus (Status _newStatus) external onlyOwner {
// Update.
status = _newStatus;
// Broadcast.
emit StatusChange(_newStatus);
}
// (Re-)set the list of Mintpassed Contracts.
function setMintpassedContracts (address[] calldata _newAddrs) external onlyOwner {
delete mintpassedContracts;
mintpassedContracts = _newAddrs;
}
// Add a new Mintpassed Contract.
function addMintpassedContract (address _addr) external onlyOwner {
mintpassedContracts.push(_addr);
}
// Check if an address is whitelisted via Merkle proof validation.
function isWhitelistedAddress (address _addr, bytes32[] calldata _merkleProof) public view returns (bool) {
// Verify Merkle tree proof.
bytes32 leaf = keccak256(abi.encodePacked(_addr));
return MerkleProof.verify(_merkleProof, merkleRoot, leaf);
}
// Check if an address is mintpassed (has a balance on a Mintpassed Contract).
function isMintpassedAddress (address _addr) public view returns (bool) {
// Cache array length to save gas.
uint256 len = mintpassedContracts.length;
// Loop through Mintpassed Contracts.
for (uint256 i = 0; i < len; i++) {
// Instantiate this Mintpassed Contract.
MintpassedContract mintpassedContract = MintpassedContract(mintpassedContracts[i]);
// Check if the address has a non-zero balance.
if (mintpassedContract.balanceOf(_addr) > 0) {
return true;
}
}
// Not allowed.
return false;
}
// Proxy supply to bodies.
function totalSupply () public view returns (uint256) {
return bodies.totalSupply();
}
// Proxy balance to bodies.
function balanceOf (address _owner) public view returns (uint256) {
return bodies.balanceOf(_owner);
}
// Dynamic mint price.
function mintPrice () public view returns (uint256) {
// Paused.
if (status == Status.Paused) {
// Failsafe, but if you find a way go for it.
return 1000000 ether;
}
// Whitelist.
if (status == Status.Whitelist) {
return whitelistPrice;
}
// Mintpass.
if (status == Status.Mintpass) {
return mintpassPrice;
}
// Public.
return publicPrice;
}
// Dynamic mint limit.
function mintLimit () public view returns (uint256) {
// Paused.
if (status == Status.Paused) {
return 0;
}
// Whitelist.
if (status == Status.Whitelist) {
return whitelistMintLimit;
}
// Mintpass.
if (status == Status.Mintpass) {
return mintpassMintLimit;
}
// Public.
return publicMintLimit;
}
// Mint.
function mint (address _to, uint256 _numToMint) external payable nonReentrant mintCheck(_to, _numToMint) {
// Not for whitelist mints.
require(status != Status.Whitelist, "Whitelist mints must provide proof via mintWhitelist()");
// Mintpass.
if (status == Status.Mintpass) {
// Check eligibility.
require(isMintpassedAddress(_to), "Address is not mintpassed");
}
// Okay mint.
_mint(_to, _numToMint);
}
// Mint whitelist.
function mintWhitelist (address _to, uint256 _numToMint, bytes32[] calldata _merkleProof) external payable nonReentrant mintCheck(_to, _numToMint) {
// Require whitelist status.
require(status == Status.Whitelist, "Whitelist mints only");
// Check balance.
require((balanceOf(_to) + _numToMint) <= mintLimit(), "Whitelist mint limit exceeded");
// Check whitelist eligibility.
require(isWhitelistedAddress(_to, _merkleProof), "Address is not whitelisted");
// Okay mint.
_mint(_to, _numToMint);
}
// Actually mint.
function _mint (address _to, uint256 _numToMint) private {
// Mint bodies & legs.
bodies.mint(_to, _numToMint);
legs.mint(_to, _numToMint);
}
}
// Mintpassed Contract interface.
interface MintpassedContract {
function balanceOf(address _account) external view returns (uint256);
}
// 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 (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 (finance/PaymentSplitter.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/utils/SafeERC20.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
* contract.
*/
function release(IERC20 token, address account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20Released[token][account] += payment;
_erc20TotalReleased[token] += payment;
SafeERC20.safeTransfer(token, account, payment);
emit ERC20PaymentReleased(token, account, payment);
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// 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 (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
/**
* @title Complete the Punks: Bodies
* @dev Mints Body NFTs for a parent Punk project
* @author earlybail.eth | Cranky Brain Labs
* @notice #GetBodied
*/
/*
;╟██▓▒ :╟██▓▒
,φ▒╣╬╬╩╩Γ ╙╩╬╬╬▓▒░
,╓φ╣▓█╬Γ ╚╣█▓╬▒╓, ,,╓╓╓╓,
φ╣▓▓╬╩"" ""╚╣▓▓▒░ ]╟▓████▓▒
φφ╬╬╬╬╩╙ '╚╩╬╬╬▒▒░ φ╫███▓╬╬╬▓▒░
]╟▓█▓▒ :╟▓█▓▒ φ╫██╬▒ ╚╣█▓╬φ,,
:╟██▓▒ :╟██▓▒ φ╫██▓▒ "╙╠╣▓▓▒░
:╟██▓▒ :╟██▓▒ φφ▒▒▒▒╬╬╬╩╩' φ╫██▓▒
:╟██▓▒ ,,, :╟██▓▒ ]╟▓████▓╬⌐ φ╫██▓▒
:╟██▓▒ .╠╣▓▓▒ :╟██▓▒ :╟███╬╩"' φ╫██▓▒
:╟██▓▒ :╟██▓▒ φφ▒φ░ ,φ▒▒░ :╟██▓▒ :╟██▓▒ φ╫██▓▒
:╟██▓▒ :╟██▓▒ '╠▓█▓▒ ╚╣█▓╬⌐:╟███▒≥, '╠▓█▓╬≥, ,,φ╣██╬░
:╟██▓▒ :╟██▓▒ ^"╙"' "╙╙" :╟█████▓▒~ ^"╙╠╣▓▓▒~ φ╣▓▓╬╩╙"
:╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ╠▓██╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟███▒ ╚╟▓█╬▒╓╠▓██╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╚╣▓▓████╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬╬████╬[ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟███▒╓, ╚╣██╬⌐ ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟█████▓▒~ '"╙╙" ╠▓██╬[
:╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ≤φ▒╬╬╬╬╚
:╟██▓▒ :╟██▓▒ :╟███▒ ╚╣██╬▒,,,,,,,φ╟▓█▓╩
:╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╩╬╣▓▓▓▓▓▓▓▓╬╬╚╙'
:╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬▓▓▓▓▓▓▓╬╩░
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ :╟██▓▒
:╟██▓▒ :╟██▓▒ ]φ╣▓▒░ :╟██▓▒
:╟██▓▒ :╟██▓▒ "╠╬▓╩░ :╟██▓▒
:╟███▒, :╟██▓▒ :╟██▓▒
:╟████▓▒▒ :╟██▓▒ :╟██▓▒
╚╬█████▓▒▒╣██▓▒ :╟██▓▒
"╠▓████████▓▒ :╟██▓▒
*/
// Directives.
pragma solidity 0.8.9;
// Local deps.
import "./Component.sol";
// Contract.
contract Bodies is Component {
// Constructor.
constructor (
string memory _name,
string memory _symbol,
uint256 _tokenStartId
) Component(_name, _symbol, _tokenStartId) {}
}
// SPDX-License-Identifier: MIT
/**
* @title Complete the Punks: Legs
* @dev Mints Leg NFTs for a parent Punk project
* @author earlybail.eth | Cranky Brain Labs
* @notice #LegsFuknGooo
*/
/*
φ╫██▓▒ :╟██▓▒
φ╫██▓▒ ,φ▒▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒░ :╟██▓▒
φ╫██▓▒ φ╣███████████████▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓╩╙╙╙╙╙╙╙╚╣██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒
φ╫██▓▒ "╩╬▓╬▒φφ, :╟██▓▒ ╚╬▓╬╬▒φε
φ╫██▓▒ 7╟▓█▓▒, ;╟██▓▒ `╠╣█▓╬░
φ╫██▓▒ "╙╩╬╣▓▓▓▓▓███▓▒ ^╙╩╬╣▓▓▓▓▓▒░
φ╫██▓▒ ╚╠╣███████▓▒ "╠╬████╬╬▒φε
φ╫██▓▒ ```╠╠███▒, ```░╠╣██╬[
φ╫████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████╬[
"╠╬███████████████████████████████████████████████╬╩
`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/
// Directives.
pragma solidity 0.8.9;
// Local deps.
import "./Component.sol";
// Contract.
contract Legs is Component {
// Constructor.
constructor (
string memory _name,
string memory _symbol,
uint256 _tokenStartId
) Component(_name, _symbol, _tokenStartId) {}
}
// 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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `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);
/**
* @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
/**
* @title Complete the Punks: Component
* @dev Base component contract for Bodies + Legs
* @author earlybail.eth | Cranky Brain Labs
* @notice #GetBodied #LegsFuknGooo
*/
// Directives.
pragma solidity 0.8.9;
// Third-party deps.
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// Contract.
contract Component is ERC721, ReentrancyGuard, Ownable {
// Strings.
using Strings for uint256;
// Counters.
using Counters for Counters.Counter;
// Supply counter.
Counters.Counter private _supply;
// Parent Project contract address.
address public projectAddress;
// OpenSea Proxy contract address.
address public openSeaProxyContractAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
// Base URI.
string public baseURI;
// Base extension.
string public baseExtension = "";
// Provenance hash.
string public provenanceHash;
// Mint ID tracking.
mapping(uint256 => uint256) private _tokenIdCache;
uint256 public remainingTokenCount = 10000;
// Token start ID.
uint256 public tokenStartId = 0;
// Constructor.
constructor (
string memory _name,
string memory _symbol,
uint256 _tokenStartId
) ERC721(_name, _symbol) {
// Set token start ID.
tokenStartId = _tokenStartId;
}
// Only allow the project contract as caller.
modifier onlyProject () {
require(_msgSender() == projectAddress, "Only the parent Project contract can call this method");
_;
}
// Get base URI.
function _baseURI () internal view virtual override returns (string memory) {
return baseURI;
}
// Set project address.
function setProjectAddress (address _newAddr) external onlyOwner {
projectAddress = _newAddr;
}
// Set base URI.
function setBaseURI (string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
// Set base extension.
function setBaseExtension (string memory _newBaseExtension) external onlyOwner {
baseExtension = _newBaseExtension;
}
// Set the token start ID.
function setTokenStartId (uint256 _newId) external onlyOwner {
tokenStartId = _newId;
}
// Set provenance hash.
function setProvenanceHash (string memory _newHash) external onlyOwner {
provenanceHash = _newHash;
}
// Set OpenSea proxy address.
// Rinkeby: 0x1E525EEAF261cA41b809884CBDE9DD9E1619573A
// Mainnet: 0xa5409ec958C83C3f309868babACA7c86DCB077c1
// Disable: 0x0000000000000000000000000000000000000000
function setOpenSeaProxyAddress (address _newAddress) external onlyOwner {
openSeaProxyContractAddress = _newAddress;
}
// Token URI.
function tokenURI (uint256 _tokenId) public view virtual override returns (string memory) {
// Ensure existence.
require(_exists(_tokenId), "Query for non-existent token");
// Cache.
string memory currentBaseURI = _baseURI();
// Concatenate.
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), baseExtension))
: "";
}
// Get the current total supply.
function totalSupply () public view returns (uint256) {
return _supply.current();
}
// Mint.
function mint (address _to, uint256 _numToMint) public nonReentrant onlyProject {
_mintLoop(_to, _numToMint);
}
// Actually mint.
function _mintLoop (address _to, uint256 _numToMint) private {
for (uint256 i = 0; i < _numToMint; i++) {
// Draw ID.
uint256 tokenId = drawTokenId();
// Safe mint.
_safeMint(_to, tokenId);
// Increment supply counter.
_supply.increment();
}
}
// Draw token ID.
function drawTokenId () private returns (uint256) {
// Generate an index.
uint256 num = uint256(
keccak256(
abi.encode(
_msgSender(),
name(),
symbol(),
blockhash(block.number - 1),
block.number,
block.timestamp,
block.difficulty,
tx.gasprice,
remainingTokenCount,
projectAddress
)
)
);
// Mod.
uint256 index = num % remainingTokenCount;
// If we haven't already drawn this index, use it directly as tokenId.
// Otherwise, pull the tokenId we cached at this index last time.
uint256 tokenId = _tokenIdCache[index] == 0
? index
: _tokenIdCache[index];
// Cache this index with the tail of remainingTokenCount.
_tokenIdCache[index] = _tokenIdCache[remainingTokenCount - 1] == 0
? remainingTokenCount - 1
: _tokenIdCache[remainingTokenCount - 1];
// Decrement remaining tokens.
remainingTokenCount = remainingTokenCount - 1;
// Return with optional start offset.
return tokenId + tokenStartId;
}
// Public exists.
function exists (uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
// Override operator approval.
function isApprovedForAll (address _owner, address _operator) public override view returns (bool) {
// Skip if disabled.
if (openSeaProxyContractAddress != address(0)) {
// Instantiate proxy registry.
ProxyRegistry proxyRegistry = ProxyRegistry(openSeaProxyContractAddress);
// Check proxy.
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
}
// Defer.
return super.isApprovedForAll(_owner, _operator);
}
}
// Proxy.
contract OwnableDelegateProxy {}
// Proxy registry.
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// 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 (last updated v4.5.0) (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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner");
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);
_afterTokenTransfer(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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 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/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);
}
|
Set the bodies contract.
|
function setBodies (address _newAddr) external onlyOwner {
bodies = Bodies(_newAddr);
}
| 13,613,422
|
./full_match/1/0xE83B94ECA0e76D9cE0119Fe6D37a539623C097D4/sources/contracts/staking/StakingPoolRewarder.sol
|
Sets the reward dispatcher Allows the owner to change the address of the reward dispatcher. Requires that the new address is not a zero address. _rewardDispatcher The new address of the reward dispatcher/
|
function setRewardDispatcher(address _rewardDispatcher) external onlyOwner {
require(_rewardDispatcher != address(0), "StakingPoolRewarder: rewardDispatcher zero address");
rewardDispatcher = _rewardDispatcher;
}
| 8,402,195
|
./full_match/1/0x4c133eba502c9a5204313E7B9e632e085cfCE358/sources/contracts/Verselets.sol
|
_mint(owner, tokenId);
|
function premintAll(
uint256 collectionId,
uint256[] calldata tokenIds,
uint256[] calldata registryIds
) external onlyRole(EDITOR_ROLE) {
require(
tokenIds.length == registryIds.length,
"Verselets: different lengths"
);
Collection storage c = _collections[collectionId];
c.minted += uint16(tokenIds.length);
require(c.minted <= c.supply, "Verselets: too many amulets");
IAmulet.MintData[] memory mintData = new IAmulet.MintData[](
tokenIds.length
);
for (uint256 i = 0; i < tokenIds.length; ) {
uint tokenId = tokenIds[i];
uint registryId = registryIds[i];
_registryIdToTokenId[registryId] = tokenId;
mintData[i] = IAmulet.MintData({
owner: address(this),
tokenId: registryId
});
unchecked {
i++;
}
}
_registry.mintAll(mintData);
}
| 16,418,762
|
pragma solidity >=0.6.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "hardhat/console.sol";
//import "@openzeppelin/contracts/access/Ownable.sol"; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
//import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
abstract contract AaveLendingPoolInterface {
function getUserAccountData(address user) public virtual view returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) public virtual;
function withdraw(address asset, uint256 amount, address to) public virtual;
}
abstract contract IERC20 {
//function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public virtual view returns (uint balance);
function allowance(address tokenOwner, address spender) public virtual view returns (uint remaining);
//function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public virtual returns (bool success);
function transferFrom(address from, address to, uint tokens) public virtual returns (bool success);
//event Transfer(address indexed from, address indexed to, uint tokens);
//event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
abstract contract ETHGateway {
function depositETH(address lendingPool, address onBehalfOf, uint16 referralCode) public virtual payable;
function withdrawETH(address lendingPool, uint256 amount, address to) public virtual payable;
}
// #example of transaction https://polygonscan.com/tx/0xffb56160b4555c7949f1f94242f9236d4d348fde2fd276f72106d42e4553a80c#eventlog
// #code of AddLiquidity https://polygonscan.com/address/0x445fe580ef8d70ff569ab36e80c647af338db351#code
// event AddLiquidity:
// provider: indexed(address)
// token_amounts: uint256[N_COINS]
// fees: uint256[N_COINS]
// invariant: uint256
// token_supply: uint256
abstract contract CurveAavePoolInterface {
function add_liquidity(uint256[3] memory _amounts, uint256 _min_mint_amount, bool _use_underlying) public virtual returns
(uint256);
function AddLiquidity(
address provider,
uint256[3] memory _token_amounts,
uint256[3] memory fees,
uint256 invariant,
uint256 token_supply
) public virtual returns (uint256);
}
contract YourContract {
event SetPurpose(address sender, string purpose);
mapping (address => uint256) balanceOf;
address aaveLendingPoolAddress = 0x8dFf5E27EA6b7AC08EbFdf9eB090F32ee9a30fcf; //matic mainnet
AaveLendingPoolInterface aaveLendingPoolContract = AaveLendingPoolInterface(aaveLendingPoolAddress);
address wMatic = 0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270;
address aToken = 0x8dF3aad3a84da6b69A4DA8aeC3eA40d9091B2Ac4;
address ethGateway = 0xbEadf48d62aCC944a06EEaE0A9054A90E5A7dc97;
address USDT = 0xc2132D05D31c914a87C6611C10748AEb04B58e8F;
constructor() {
// what should we do on deploy?
}
function sendUSDT(address _from, address _to, uint256 _tokens) external {
// This is the mainnet USDT contract address
// Using on other networks (rinkeby, local, ...) would fail
// - there's no contract on this address on other networks
// transfers USDT that belong to your contract to the specified address
IERC20(address(USDT)).transferFrom(_from, _to, _tokens);
}
function depositToVault() public payable {
console.log(msg.sender, "depositToVault()", msg.value);
require(balanceOf[msg.sender] == 0, "Already deposited");
balanceOf[msg.sender] += msg.value;
//emit SetPurpose(msg.sender, purpose);
}
function depositAndStakeInGaugeUSDT() public payable {
console.log(msg.sender, "depositAndStakeInGaugeUSDT()", msg.value);
require(balanceOf[msg.sender] == 0, "Already deposited");
balanceOf[msg.sender] += msg.value;
//emit SetPurpose(msg.sender, purpose);
}
/*function depositFromVaultToAave() public {
require(balanceOf[msg.sender] > 0, "No funds deposited");
aaveLendingPoolContract.deposit(wMatic, balanceOf[msg.sender], msg.sender, 0);
}*/
function depositFromVaultToAave(address _address) public {
//require(balanceOf[_address] > 0, "No funds deposited");
ETHGateway(ethGateway).depositETH{value:balanceOf[_address]}(aaveLendingPoolAddress, _address, 0);
}
function withdrawFromAave(address _address) public {
//IERC20(aToken).allowance(_address, address(this));
//IERC20(aToken).allowance(aaveLendingPoolAddress, address(this));
IERC20(wMatic).approve(aaveLendingPoolAddress, type(uint).max);
ETHGateway(ethGateway).withdrawETH(aaveLendingPoolAddress, type(uint).max, _address);
}
//onlyOwner
//move to constructor
function approve(address _tokenAddress, address _address) public returns (bool) {
//IERC20(aToken).approve(address(this), type(uint).max);
//IERC20(aToken).approve(aaveLendingPoolAddress, type(uint).max);
return IERC20(_tokenAddress).approve(_address, type(uint).max);
}
function approve() public returns (bool) {
return IERC20(aToken).approve(aaveLendingPoolAddress, type(uint).max);
}
function withdrawFromAaveToValut() public {
ETHGateway(ethGateway).withdrawETH(aaveLendingPoolAddress, type(uint).max, address(this));
}
function withdrawATokenFromAave() public {
aaveLendingPoolContract.withdraw(aToken, type(uint).max, msg.sender);
}
function getATokenBalanceOf(address _tokenAddress, address _ownerAddress) public view returns (uint) {
IERC20 iaToken = IERC20(_tokenAddress);
return iaToken.balanceOf(_ownerAddress);
}
function getATokenAllowanceOf(address _tokenAddress, address _address1, address _address2) public view returns (uint) {
IERC20 iaToken = IERC20(_tokenAddress);
return iaToken.allowance(_address1, _address2);
}
/*function getMyDeposit() public view returns (uint256) {
console.log(msg.sender, "getMyDeposit()", balanceOf[msg.sender]);
return balanceOf[msg.sender];
}*/
function getDepositOf(address _address) public view returns (uint256) {
console.log(msg.sender, "getDepositOf()", balanceOf[_address]);
return balanceOf[_address];
}
function withdrawTo(address _address) public {
payable(_address).transfer(getDepositOf(_address));
balanceOf[_address] = 0;
}
///////////////////////////
///////////////////////////TESTS
///////////////////////////
function addFunds() public payable {
}
function payToSender() public {
payable(msg.sender).transfer(address(this).balance);
balanceOf[msg.sender] = 0;
}
/*function getMsgSender(uint _a) public payable returns (address) {
console.log(msg.sender,"!!","??");
//console.log(msg.data,"!!","??");
//console.log(msg.gas,"!!","??");
//console.log(msg.sig,"!!","??");
console.log(msg.value,"!!","??");
//console.log(msg.sender.from,"!!","??");
console.log(address(msg.sender).balance,"!!","??");
console.log(msg.sender.balance,"!!","??");
return msg.sender;
}
function getTxOrigin() public view returns (address) {
return tx.origin;
}
function sender() public view returns (address) {
return msg.sender;
}*/
/*function getBalanceOf(address _address) public view returns (uint) {
return _address.balance;
}*/
/*function contractBalance() public view returns (uint) {
return address(this).balance;
}*/
function getUserAccountData(address _someAddress) public view returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
return aaveLendingPoolContract.getUserAccountData(_someAddress);
}
//function getUserAccountDataByIndex(address _someAddress, uint8 _index) public view returns (uint256) {
//return aaveLendingPoolContract.getUserAccountData(_someAddress)[_index];
//}
function getHL(address _someAddress) public view returns (uint256) {
(,,,,,uint256 myHL) = aaveLendingPoolContract.getUserAccountData(_someAddress);
return myHL;
}
function getTotalCollateralETH(address _someAddress) public view returns (uint256) {
(uint256 totalCollateralETH,,,,,) = getUserAccountData(_someAddress);
return totalCollateralETH;
}
function getCurrentLiquidationThreshold(address _someAddress) public view returns (uint256) {
(,,,uint256 currentLiquidationThreshold,,) = getUserAccountData(_someAddress);
return currentLiquidationThreshold;
}
function getAvailableBorrowsETH(address _someAddress) public view returns (uint256) {
(,,uint256 availableBorrowsETH,,,) = getUserAccountData(_someAddress);
return availableBorrowsETH;
}
function getTotalDebtETH(address _someAddress) public view returns (uint256) {
(,uint256 totalDebtETH,,,,) = getUserAccountData(_someAddress);
return totalDebtETH;
}
// ---------------- CURVE ---------------------
address curveAavePoolAddress = 0x445FE580eF8d70FF569aB36e80c647af338db351;
CurveAavePoolInterface curveAavePoolContract = CurveAavePoolInterface(curveAavePoolAddress);
function depositFromVaultToCurveAavePool(address _address, uint256 _usdtCount) public {
IERC20(USDT).approve(curveAavePoolAddress, balanceOf[_address]);
curveAavePoolContract.add_liquidity([uint(0), uint(0), uint(_usdtCount * 1000000)], 0, false);
}
}
|
require(balanceOf[_address] > 0, "No funds deposited");
|
function depositFromVaultToAave(address _address) public {
ETHGateway(ethGateway).depositETH{value:balanceOf[_address]}(aaveLendingPoolAddress, _address, 0);
}
| 937,262
|
// File: contracts\modules\Ownable.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\modules\Halt.sol
pragma solidity =0.5.16;
contract Halt is Ownable {
bool private halted = false;
modifier notHalted() {
require(!halted,"This contract is halted");
_;
}
modifier isHalted() {
require(halted,"This contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
}
// File: contracts\modules\whiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist which filters a eligible uint32.
*/
library whiteListUint32 {
/**
* @dev add uint32 into white list.
* @param whiteList the storage whiteList.
* @param temp input value
*/
function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
if (!isEligibleUint32(whiteList,temp)){
whiteList.push(temp);
}
}
/**
* @dev remove uint32 from whitelist.
*/
function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible uint256.
*/
library whiteListUint256 {
// add whiteList
function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
if (!isEligibleUint256(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible address.
*/
library whiteListAddress {
// add whiteList
function addWhiteListAddress(address[] storage whiteList,address temp) internal{
if (!isEligibleAddress(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
// File: contracts\modules\AddressWhiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist filters a eligible address.
*/
contract AddressWhiteList is Halt {
using whiteListAddress for address[];
uint256 constant internal allPermission = 0xffffffff;
uint256 constant internal allowBuyOptions = 1;
uint256 constant internal allowSellOptions = 1<<1;
uint256 constant internal allowExerciseOptions = 1<<2;
uint256 constant internal allowAddCollateral = 1<<3;
uint256 constant internal allowRedeemCollateral = 1<<4;
// The eligible adress list
address[] internal whiteList;
mapping(address => uint256) internal addressPermission;
/**
* @dev Implementation of add an eligible address into the whitelist.
* @param addAddress new eligible address.
*/
function addWhiteList(address addAddress)public onlyOwner{
whiteList.addWhiteListAddress(addAddress);
addressPermission[addAddress] = allPermission;
}
function modifyPermission(address addAddress,uint256 permission)public onlyOwner{
addressPermission[addAddress] = permission;
}
/**
* @dev Implementation of revoke an invalid address from the whitelist.
* @param removeAddress revoked address.
*/
function removeWhiteList(address removeAddress)public onlyOwner returns (bool){
addressPermission[removeAddress] = 0;
return whiteList.removeWhiteListAddress(removeAddress);
}
/**
* @dev Implementation of getting the eligible whitelist.
*/
function getWhiteList()public view returns (address[] memory){
return whiteList;
}
/**
* @dev Implementation of testing whether the input address is eligible.
* @param tmpAddress input address for testing.
*/
function isEligibleAddress(address tmpAddress) public view returns (bool){
return whiteList.isEligibleAddress(tmpAddress);
}
function checkAddressPermission(address tmpAddress,uint256 state) public view returns (bool){
return (addressPermission[tmpAddress]&state) == state;
}
}
// File: contracts\modules\ReentrancyGuard.sol
pragma solidity =0.5.16;
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancyLock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancyLock);
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
// File: contracts\OptionsPool\IOptionsPool.sol
pragma solidity =0.5.16;
interface IOptionsPool {
// function getOptionBalances(address user) external view returns(uint256[]);
function getExpirationList()external view returns (uint32[] memory);
function createOptions(address from,address settlement,uint256 type_ly_expiration,
uint128 strikePrice,uint128 underlyingPrice,uint128 amount,uint128 settlePrice) external returns(uint256);
function setSharedState(uint256 newFirstOption,int256[] calldata latestNetWorth,address[] calldata whiteList) external;
function getAllTotalOccupiedCollateral() external view returns (uint256,uint256);
function getCallTotalOccupiedCollateral() external view returns (uint256);
function getPutTotalOccupiedCollateral() external view returns (uint256);
function getTotalOccupiedCollateral() external view returns (uint256);
// function buyOptionCheck(uint32 expiration,uint32 underlying)external view;
function burnOptions(address from,uint256 id,uint256 amount,uint256 optionPrice)external;
function getOptionsById(uint256 optionsId)external view returns(uint256,address,uint8,uint32,uint256,uint256,uint256);
function getExerciseWorth(uint256 optionsId,uint256 amount)external view returns(uint256);
function calculatePhaseOptionsFall(uint256 lastOption,uint256 begin,uint256 end,address[] calldata whiteList) external view returns(int256[] memory);
function getOptionInfoLength()external view returns (uint256);
function getNetWrothCalInfo(address[] calldata whiteList)external view returns(uint256,int256[] memory);
function calRangeSharedPayment(uint256 lastOption,uint256 begin,uint256 end,address[] calldata whiteList)external view returns(int256[] memory,uint256[] memory,uint256);
function getNetWrothLatestWorth(address settlement)external view returns(int256);
function getBurnedFullPay(uint256 optionID,uint256 amount) external view returns(address,uint256);
}
contract ImportOptionsPool is Ownable{
IOptionsPool internal _optionsPool;
function getOptionsPoolAddress() public view returns(address){
return address(_optionsPool);
}
function setOptionsPoolAddress(address optionsPool)public onlyOwner{
_optionsPool = IOptionsPool(optionsPool);
}
}
// File: contracts\interfaces\IFNXOracle.sol
pragma solidity =0.5.16;
interface IFNXOracle {
/**
* @notice retrieves price of an asset
* @dev function to get price for an asset
* @param asset Asset for which to get the price
* @return uint mantissa of asset price (scaled by 1e8) or zero if unset or contract paused
*/
function getPrice(address asset) external view returns (uint256);
function getUnderlyingPrice(uint256 cToken) external view returns (uint256);
function getPrices(uint256[] calldata assets) external view returns (uint256[]memory);
function getAssetAndUnderlyingPrice(address asset,uint256 underlying) external view returns (uint256,uint256);
// function getSellOptionsPrice(address oToken) external view returns (uint256);
// function getBuyOptionsPrice(address oToken) external view returns (uint256);
}
contract ImportOracle is Ownable{
IFNXOracle internal _oracle;
function oraclegetPrices(uint256[] memory assets) internal view returns (uint256[]memory){
uint256[] memory prices = _oracle.getPrices(assets);
uint256 len = assets.length;
for (uint i=0;i<len;i++){
require(prices[i] >= 100 && prices[i] <= 1e30);
}
return prices;
}
function oraclePrice(address asset) internal view returns (uint256){
uint256 price = _oracle.getPrice(asset);
require(price >= 100 && price <= 1e30);
return price;
}
function oracleUnderlyingPrice(uint256 cToken) internal view returns (uint256){
uint256 price = _oracle.getUnderlyingPrice(cToken);
require(price >= 100 && price <= 1e30);
return price;
}
function oracleAssetAndUnderlyingPrice(address asset,uint256 cToken) internal view returns (uint256,uint256){
(uint256 price1,uint256 price2) = _oracle.getAssetAndUnderlyingPrice(asset,cToken);
require(price1 >= 100 && price1 <= 1e30);
require(price2 >= 100 && price2 <= 1e30);
return (price1,price2);
}
function getOracleAddress() public view returns(address){
return address(_oracle);
}
function setOracleAddress(address oracle)public onlyOwner{
_oracle = IFNXOracle(oracle);
}
}
// File: contracts\interfaces\IOptionsPrice.sol
pragma solidity =0.5.16;
interface IOptionsPrice {
function getOptionsPrice(uint256 currentPrice, uint256 strikePrice, uint256 expiration,uint32 underlying,uint8 optType)external view returns (uint256);
function getOptionsPrice_iv(uint256 currentPrice, uint256 strikePrice, uint256 expiration,
uint256 ivNumerator,uint8 optType)external view returns (uint256);
function calOptionsPriceRatio(uint256 selfOccupied,uint256 totalOccupied,uint256 totalCollateral) external view returns (uint256);
}
contract ImportOptionsPrice is Ownable{
IOptionsPrice internal _optionsPrice;
function getOptionsPriceAddress() public view returns(address){
return address(_optionsPrice);
}
function setOptionsPriceAddress(address optionsPrice)public onlyOwner{
_optionsPrice = IOptionsPrice(optionsPrice);
}
}
// File: contracts\CollateralPool\ICollateralPool.sol
pragma solidity =0.5.16;
interface ICollateralPool {
function getFeeRateAll()external view returns (uint32[] memory);
function getUserPayingUsd(address user)external view returns (uint256);
function getUserInputCollateral(address user,address collateral)external view returns (uint256);
//function getNetWorthBalance(address collateral)external view returns (int256);
function getCollateralBalance(address collateral)external view returns (uint256);
//add
function addUserPayingUsd(address user,uint256 amount)external;
function addUserInputCollateral(address user,address collateral,uint256 amount)external;
function addNetWorthBalance(address collateral,int256 amount)external;
function addCollateralBalance(address collateral,uint256 amount)external;
//sub
function subUserPayingUsd(address user,uint256 amount)external;
function subUserInputCollateral(address user,address collateral,uint256 amount)external;
function subNetWorthBalance(address collateral,int256 amount)external;
function subCollateralBalance(address collateral,uint256 amount)external;
//set
function setUserPayingUsd(address user,uint256 amount)external;
function setUserInputCollateral(address user,address collateral,uint256 amount)external;
function setNetWorthBalance(address collateral,int256 amount)external;
function setCollateralBalance(address collateral,uint256 amount)external;
function transferPaybackAndFee(address recieptor,address settlement,uint256 payback,uint256 feeType)external;
function buyOptionsPayfor(address payable recieptor,address settlement,uint256 settlementAmount,uint256 allPay)external;
function transferPayback(address recieptor,address settlement,uint256 payback)external;
function transferPaybackBalances(address account,uint256 redeemWorth,address[] calldata tmpWhiteList,uint256[] calldata colBalances,
uint256[] calldata PremiumBalances,uint256[] calldata prices)external;
function getCollateralAndPremiumBalances(address account,uint256 userTotalWorth,address[] calldata tmpWhiteList,
uint256[] calldata _RealBalances,uint256[] calldata prices) external view returns(uint256[] memory,uint256[] memory);
function addTransactionFee(address collateral,uint256 amount,uint256 feeType)external returns (uint256);
function getAllRealBalance(address[] calldata whiteList)external view returns(int256[] memory);
function getRealBalance(address settlement)external view returns(int256);
function getNetWorthBalance(address settlement)external view returns(uint256);
}
contract ImportCollateralPool is Ownable{
ICollateralPool internal _collateralPool;
function getCollateralPoolAddress() public view returns(address){
return address(_collateralPool);
}
function setCollateralPoolAddress(address collateralPool)public onlyOwner{
_collateralPool = ICollateralPool(collateralPool);
}
}
// File: contracts\FPTCoin\IFPTCoin.sol
pragma solidity =0.5.16;
interface IFPTCoin {
function lockedBalanceOf(address account) external view returns (uint256);
function lockedWorthOf(address account) external view returns (uint256);
function getLockedBalance(address account) external view returns (uint256,uint256);
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function addlockBalance(address account, uint256 amount,uint256 lockedWorth)external;
function getTotalLockedWorth() external view returns (uint256);
function addMinerBalance(address account,uint256 amount) external;
function redeemLockedCollateral(address account,uint256 tokenAmount,uint256 leftCollateral)external returns (uint256,uint256);
}
contract ImportIFPTCoin is Ownable{
IFPTCoin internal _FPTCoin;
function getFPTCoinAddress() public view returns(address){
return address(_FPTCoin);
}
function setFPTCoinAddress(address FPTCoinAddr)public onlyOwner{
_FPTCoin = IFPTCoin(FPTCoinAddr);
}
}
// File: contracts\modules\ImputRange.sol
pragma solidity =0.5.16;
contract ImputRange is Ownable {
//The maximum input amount limit.
uint256 private maxAmount = 1e30;
//The minimum input amount limit.
uint256 private minAmount = 1e2;
modifier InRange(uint256 amount) {
require(maxAmount>=amount && minAmount<=amount,"input amount is out of input amount range");
_;
}
/**
* @dev Determine whether the input amount is within the valid range
* @param Amount Test value which is user input
*/
function isInputAmountInRange(uint256 Amount)public view returns (bool){
return(maxAmount>=Amount && minAmount<=Amount);
}
/*
function isInputAmountSmaller(uint256 Amount)public view returns (bool){
return maxAmount>=amount;
}
function isInputAmountLarger(uint256 Amount)public view returns (bool){
return minAmount<=amount;
}
*/
modifier Smaller(uint256 amount) {
require(maxAmount>=amount,"input amount is larger than maximium");
_;
}
modifier Larger(uint256 amount) {
require(minAmount<=amount,"input amount is smaller than maximium");
_;
}
/**
* @dev get the valid range of input amount
*/
function getInputAmountRange() public view returns(uint256,uint256) {
return (minAmount,maxAmount);
}
/**
* @dev set the valid range of input amount
* @param _minAmount the minimum input amount limit
* @param _maxAmount the maximum input amount limit
*/
function setInputAmountRange(uint256 _minAmount,uint256 _maxAmount) public onlyOwner{
minAmount = _minAmount;
maxAmount = _maxAmount;
}
}
// File: contracts\modules\Allowances.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* each operator can be granted exclusive access to specific functions.
*
*/
contract Allowances is Ownable {
mapping (address => uint256) internal allowances;
bool internal bValid = false;
/**
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public onlyOwner{
allowances[spender] = amount;
}
function allowance(address spender) public view returns (uint256) {
return allowances[spender];
}
function setValid(bool _bValid) public onlyOwner{
bValid = _bValid;
}
function checkAllowance(address spender, uint256 amount) public view returns(bool){
return (!bValid) || (allowances[spender] >= amount);
}
modifier sufficientAllowance(address spender, uint256 amount){
require((!bValid) || (allowances[spender] >= amount),"Allowances : user's allowance is unsufficient!");
_;
}
}
// File: contracts\ERC20\IERC20.sol
pragma solidity =0.5.16;
/**
* @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);
}
// File: contracts\OptionsManager\ManagerData.sol
pragma solidity =0.5.16;
/**
* @title collateral calculate module
* @dev A smart-contract which has operations of collateral and methods of calculate collateral occupation.
*
*/
contract ManagerData is ReentrancyGuard,ImputRange,AddressWhiteList,Allowances,ImportIFPTCoin,
ImportOracle,ImportOptionsPool,ImportCollateralPool,ImportOptionsPrice {
// The minimum collateral rate for options. This value is thousandths.
mapping (address=>uint256) collateralRate;
// uint256 private collateralRate = 5000;
/**
* @dev Emitted when `from` added `amount` collateral and minted `tokenAmount` FPTCoin.
*/
event AddCollateral(address indexed from,address indexed collateral,uint256 amount,uint256 tokenAmount);
/**
* @dev Emitted when `from` redeemed `allRedeem` collateral.
*/
event RedeemCollateral(address indexed from,address collateral,uint256 allRedeem);
event DebugEvent(uint256 id,uint256 value1,uint256 value2);
/**
* @dev input price valid range rate, thousandths.
* the input price must greater than current price * minPriceRate /1000
* and less than current price * maxPriceRate /1000
* maxPriceRate is the maximum limit of the price valid range rate
* maxPriceRate is the minimum limit of the price valid range rage
*/
uint256 internal maxPriceRate = 1500;
uint256 internal minPriceRate = 500;
/**
* @dev Emitted when `from` buy `optionAmount` option and create new option.
* @param from user's account
* @param settlement user's input settlement paid for buy new option.
* @param optionPrice option's paid price
* @param settlementAmount settement cost
* @param optionAmount mint option token amount.
*/
event BuyOption(address indexed from,address indexed settlement,uint256 optionPrice,uint256 settlementAmount,uint256 optionAmount);
/**
* @dev Emitted when `from` sell `amount` option whose id is `optionId` and received sellValue,priced in usd.
*/
event SellOption(address indexed from,uint256 indexed optionId,uint256 amount,uint256 sellValue);
/**
* @dev Emitted when `from` exercise `amount` option whose id is `optionId` and received sellValue,priced in usd.
*/
event ExerciseOption(address indexed from,uint256 indexed optionId,uint256 amount,uint256 sellValue);
}
// File: contracts\Proxy\baseProxy.sol
pragma solidity =0.5.16;
/**
* @title baseProxy Contract
*/
contract baseProxy is Ownable {
address public implementation;
constructor(address implementation_) public {
// Creator of the contract is admin during initialization
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
require(success);
}
function getImplementation()public view returns(address){
return implementation;
}
function setImplementation(address implementation_)public onlyOwner{
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()"));
require(success);
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
(bool success, bytes memory returnData) = implementation.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() internal view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() internal returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// File: contracts\OptionsManager\ManagerProxy.sol
pragma solidity =0.5.16;
/**
* @title Erc20Delegator Contract
*/
contract ManagerProxy is ManagerData,baseProxy{
/**
* @dev Options manager constructor. set other contract address
* oracleAddr fnx oracle contract address.
* optionsPriceAddr options price contract address
* optionsPoolAddr optoins pool contract address
* FPTCoinAddr FPTCoin contract address
*/
constructor(address implementation_,address oracleAddr,address optionsPriceAddr,
address optionsPoolAddr,address collateralPoolAddr,address FPTCoinAddr)
baseProxy(implementation_) public {
_oracle = IFNXOracle(oracleAddr);
_optionsPrice = IOptionsPrice(optionsPriceAddr);
_optionsPool = IOptionsPool(optionsPoolAddr);
_collateralPool = ICollateralPool(collateralPoolAddr);
_FPTCoin = IFPTCoin(FPTCoinAddr);
/*
allowances[0x6D14B6A933Bfc473aEDEBC3beD58cA268FEe8b4a] = 1e40;
allowances[0x87A7604C4E9E1CED9990b6D486d652f0194A4c98] = 1e40;
allowances[0x7ea1a45f0657D2Dbd77839a916AB83112bdB5590] = 1e40;
allowances[0x358dba22d19789E01FD6bB528f4E75Bc06b56A79] = 1e40;
allowances[0x91406B5d57893E307f042D71C91e223a7058Eb72] = 1e40;
allowances[0xc89b50171C1F692f5CBC37aC4AF540f9cecEE0Ff] = 1e40;
allowances[0x92e25B14B0B760212D7E831EB8436Fbb93826755] = 1e40;
allowances[0x2D8f8d7737046c1475ED5278a18c4A62968f0CB2] = 1e40;
allowances[0xaAC6A96681cfc81c756Db31D93eafb8237A27Ba8] = 1e40;
allowances[0xB752d7a4E7ebD7B7A7b4DEEFd086571e5e7F5BB8] = 1e40;
allowances[0x8AbD525792015E1eBae2249756729168A3c1866F] = 1e40;
allowances[0x991b9d51e5526D497A576DF82eaa4BEA51EAD16e] = 1e40;
allowances[0xC8e7E9e496DE394969cb377F5Df0E3cdDFB74164] = 1e40;
allowances[0x0B173b9014a0A36aAC51eE4957BC8c7E20686d3F] = 1e40;
allowances[0xb9cE369E36Ab9ea488887ad9483f0ce899ab8fbe] = 1e40;
allowances[0x20C337F68Dc90D830Ac8e379e8823008dc791D56] = 1e40;
allowances[0x10E3163a7354b16ac24e7fCeE593c22E86a0abCa] = 1e40;
allowances[0x669cFbd063C434a5ee51adc78d2292A2D3Fe88E0] = 1e40;
allowances[0x59F1cfc3c485b9693e3F640e1B56Fe83B5e3183a] = 1e40;
allowances[0x4B38bf8A442D01017a6882d52Ef1B13CD069bb0d] = 1e40;
allowances[0x9c8f005ab27AdB94f3d49020A15722Db2Fcd9F27] = 1e40;
allowances[0x2240D781185B93DdD83C5eA78F4E64a9Cb5B0446] = 1e40;
allowances[0xa5B7364926Ac89aBCA15D56738b3EA79B31A0433] = 1e40;
allowances[0xafE53d85Da6b510B4fcc3774373F8880097F3E10] = 1e40;
allowances[0xb604BE9155810e4BA938ce06f8E554D2EB3438fE] = 1e40;
allowances[0xA27D1D94C0B4ce79d49E7c817C688c563D297fF7] = 1e40;
allowances[0x32ACbBa480e4bA2ee3E2c620Bf7A3242631293BE] = 1e40;
allowances[0x7Acfd797725EcCd5D3D60fB5Dd566760D0743098] = 1e40;
allowances[0x0F8f5137C365D01f71a3fb8A4283816FB12A8Efb] = 1e40;
allowances[0x2F160d9b63b5b8255499aB16959231275D4396db] = 1e40;
allowances[0xf85a428D528e89E115E5C91F7347fE9ac2F92d72] = 1e40;
allowances[0xb2c62391CCe67C5EfC1b17D442eBd24c90F6A47C] = 1e40;
allowances[0x10d31b7063cC25F9916B390677DC473B83E84e13] = 1e40;
allowances[0x358dba22d19789E01FD6bB528f4E75Bc06b56A79] = 1e40;
allowances[0xe4A263230d67d30c71634CA462a00174d943A14D] = 1e40;
allowances[0x1493572Bd9Fa9F75b0B81D6Cdd583AD87D6B358F] = 1e40;
allowances[0x025b654306621157aE8208ebC5DD0f311F425ac3] = 1e40;
allowances[0xCE257C6BD7aF256e1C8Dd11057F90b9A1AeD85a4] = 1e40;
allowances[0x7D57B8B8A731Cc1fc1E661842790e1864d5Cf4E8] = 1e40;
allowances[0xe129e34D1bD6AA1370090Cb1596207197A1a0689] = 1e40;
allowances[0xBA096024056bB653c6E28f53C8889BFC3553bAD8] = 1e40;
allowances[0x73DFb4bA8fFF9A975a28FF169157C7B71B9574aE] = 1e40;
allowances[0xddbDc4a3Af9DAa4005c039BE8329c1F03F01EDb9] = 1e40;
allowances[0x4086E0e1B3351D2168B74E7A61C0844b78f765F2] = 1e40;
allowances[0x4ce4fe1B35F11a428DD36A78C56Cb8Cc755f8847] = 1e40;
allowances[0x9e169106D1d406F3d51750835E01e8a34c265957] = 1e40;
allowances[0x7EcB07AdC76b2979fbE45Af13e2B706bA3562d1d] = 1e40;
allowances[0x3B95Df362B1857e6Db3483521057C4587C467531] = 1e40;
allowances[0xe596470D291Cb2D32ec111afC314B07006690c72] = 1e40;
allowances[0x80fd2a2Ed7e42Ec8bD9635285B09C773Da31eF71] = 1e40;
allowances[0xC09ec032769b04b08BDe8ADb608d0aaF903FF9Be] = 1e40;
allowances[0xf5F9AFBC3915075C5C62A995501fae643F5f6857] = 1e40;
allowances[0xf010920E1B098DFA1732d41Fbc895aB6E65E4438] = 1e40;
allowances[0xb37983510f9483A0725bC109d7f19237Aa3212d5] = 1e40;
allowances[0x9531479AA50908c9053144eF99c235abA6168069] = 1e40;
allowances[0x98F6a20f80FbF33153BE7ed1C8C3c10d4d6433DF] = 1e40;
allowances[0x4c8dbbDdC95B7981a7a09dE455ddfc58173CF471] = 1e40;
allowances[0x5acfbbF0aA370F232E341BC0B1a40e996c960e07] = 1e40;
allowances[0x7388B46005646008ada2d6d7DC2830F6C63b9BeD] = 1e40;
allowances[0xBFa43bf6E9FB6d5CC253Ff23c31F2b86a739bB98] = 1e40;
allowances[0x09AEa652006F4088d389c878474e33e9B15986E5] = 1e40;
allowances[0x0fBC222aDF84bEE9169022b28ebc3D32b5C60756] = 1e40;
allowances[0xBD53E948a5630c409b98bFC6112c2891836d5b33] = 1e40;
allowances[0x0eBF4005C35d525240c3237c1C448B88Deca9447] = 1e40;
allowances[0xa1cCC796E2B44e80112c065A4d8F05661E685eD8] = 1e40;
allowances[0x4E60bE84870FE6AE350B563A121042396Abe1eaF] = 1e40;
allowances[0x5286CEde4a0Eda5916d639535aDFbefAd980D6E1] = 1e40;
*/
}
/**
* @dev The foundation owner want to set the minimum collateral occupation rate.
* collateral collateral coin address
* colRate The thousandths of the minimum collateral occupation rate.
*/
function setCollateralRate(address /*collateral*/,uint256 /*colRate*/) public {
delegateAndReturn();
}
/**
* @dev Get the minimum collateral occupation rate.
*/
function getCollateralRate(address /*collateral*/)public view returns (uint256) {
delegateToViewAndReturn();
}
/**
* @dev Retrieve user's cost of collateral, priced in USD.
* user input retrieved account
*/
function getUserPayingUsd(address /*user*/)public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve user's amount of the specified collateral.
* user input retrieved account
* collateral input retrieved collateral coin address
*/
function userInputCollateral(address /*user*/,address /*collateral*/)public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve user's current total worth, priced in USD.
* account input retrieve account
*/
function getUserTotalWorth(address /*account*/)public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve FPTCoin's net worth, priced in USD.
*/
function getTokenNetworth() public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Deposit collateral in this pool from user.
* collateral The collateral coin address which is in whitelist.
* amount the amount of collateral to deposit.
*/
function addCollateral(address /*collateral*/,uint256 /*amount*/) public payable {
delegateAndReturn();
}
/**
* @dev redeem collateral from this pool, user can input the prioritized collateral,he will get this coin,
* if this coin is unsufficient, he will get others collateral which in whitelist.
* tokenAmount the amount of FPTCoin want to redeem.
* collateral The prioritized collateral coin address.
*/
function redeemCollateral(uint256 /*tokenAmount*/,address /*collateral*/) public {
delegateAndReturn();
}
/**
* @dev Retrieve user's collateral worth in all collateral coin.
* If user want to redeem all his collateral,and the vacant collateral is sufficient,
* He can redeem each collateral amount in return list.
* account the retrieve user's account;
*/
function calCollateralWorth(address /*account*/)public view returns(uint256[] memory){
delegateToViewAndReturn();
}
/**
* @dev Retrieve the occupied collateral worth, multiplied by minimum collateral rate, priced in USD.
*/
function getOccupiedCollateral() public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve the available collateral worth, the worth of collateral which can used for buy options, priced in USD.
*/
function getAvailableCollateral()public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve the left collateral worth, the worth of collateral which can used for redeem collateral, priced in USD.
*/
function getLeftCollateral()public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve the unlocked collateral worth, the worth of collateral which currently used for options, priced in USD.
*/
function getUnlockedCollateral()public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev The auxiliary function for calculate option occupied.
* strikePrice option's strike price
* underlyingPrice option's underlying price
* amount option's amount
* optType option's type, 0 for call, 1 for put.
*/
function calOptionsOccupied(uint256 /*strikePrice*/,uint256 /*underlyingPrice*/,uint256 /*amount*/,uint8 /*optType*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve the total collateral worth, priced in USD.
*/
function getTotalCollateral()public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve the balance of collateral, the auxiliary function for the total collateral calculation.
*/
function getRealBalance(address /*settlement*/)public view returns(int256){
delegateToViewAndReturn();
}
function getNetWorthBalance(address /*settlement*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev collateral occupation rate calculation
* collateral occupation rate = sum(collateral Rate * collateral balance) / sum(collateral balance)
*/
function calculateCollateralRate()public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve input price valid range rate, thousandths.
*/
function getPriceRateRange() public view returns(uint256,uint256) {
delegateToViewAndReturn();
}
/**
* @dev set input price valid range rate, thousandths.
*/
function setPriceRateRange(uint256 /*_minPriceRate*/,uint256 /*_maxPriceRate*/) public{
delegateAndReturn();
}
/**
* @dev user buy option and create new option.
* settlement user's settement coin address
* settlementAmount amount of settlement user want fo pay.
* strikePrice user input option's strike price
* underlying user input option's underlying id, 1 for BTC,2 for ETH
* expiration user input expiration,time limit from now
* amount user input amount of new option user want to buy.
* optType user input option type
*/
function buyOption(address /*settlement*/,uint256 /*settlementAmount*/, uint256 /*strikePrice*/,uint32 /*underlying*/,
uint32 /*expiration*/,uint256 /*amount*/,uint8 /*optType*/) public payable{
delegateAndReturn();
}
/**
* @dev User sell option.
* optionsId option's ID which was wanted to sell, must owned by user
* amount user input amount of option user want to sell.
*/
function sellOption(uint256 /*optionsId*/,uint256 /*amount*/) public{
delegateAndReturn();
}
/**
* @dev User exercise option.
* optionsId option's ID which was wanted to exercise, must owned by user
* amount user input amount of option user want to exercise.
*/
function exerciseOption(uint256 /*optionsId*/,uint256 /*amount*/) public{
delegateAndReturn();
}
function getOptionsPrice(uint256 /*underlyingPrice*/, uint256 /*strikePrice*/, uint256 /*expiration*/,
uint32 /*underlying*/,uint256 /*amount*/,uint8 /*optType*/) public view returns(uint256){
delegateToViewAndReturn();
}
function getALLCollateralinfo(address /*user*/)public view
returns(uint256[] memory,int256[] memory,uint32[] memory,uint32[] memory){
delegateToViewAndReturn();
}
}
|
function getSellOptionsPrice(address oToken) external view returns (uint256); function getBuyOptionsPrice(address oToken) external view returns (uint256);
|
interface IFNXOracle {
function getPrice(address asset) external view returns (uint256);
function getUnderlyingPrice(uint256 cToken) external view returns (uint256);
function getPrices(uint256[] calldata assets) external view returns (uint256[]memory);
function getAssetAndUnderlyingPrice(address asset,uint256 underlying) external view returns (uint256,uint256);
}
| 1,674,075
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "../interfaces/INFTGemMultiToken.sol";
import "../interfaces/INFTGemFeeManager.sol";
import "../interfaces/INFTComplexGemPool.sol";
import "../interfaces/INFTGemGovernor.sol";
import "../interfaces/ISwapQueryHelper.sol";
import "../interfaces/IERC3156FlashLender.sol";
import "../libs/AddressSet.sol";
import "./NFTComplexGemPoolData.sol";
contract NFTComplexGemPool is
NFTComplexGemPoolData,
INFTComplexGemPool,
IERC3156FlashLender,
ERC1155Holder
{
using AddressSet for AddressSet.Set;
using ComplexPoolLib for ComplexPoolLib.ComplexPoolData;
/**
* @dev Add an address allowed to control this contract
*/
function addController(address _controllerAddress) external {
require(
poolData.controllers[msg.sender] == true ||
address(this) == msg.sender,
"Controllable: caller is not a controller"
);
poolData.controllers[_controllerAddress] = true;
}
/**
* @dev Check if this address is a controller
*/
function isController(address _controllerAddress)
external
view
returns (bool)
{
return poolData.controllers[_controllerAddress];
}
/**
* @dev Remove the sender's address from the list of controllers
*/
function relinquishControl() external {
require(
poolData.controllers[msg.sender] == true ||
address(this) == msg.sender,
"Controllable: caller is not a controller"
);
delete poolData.controllers[msg.sender];
}
constructor() {
poolData.controllers[msg.sender] = true;
}
/**
* @dev initializer called when contract is deployed
*/
function initialize(
string memory _symbol,
string memory _name,
uint256 _ethPrice,
uint256 _minTime,
uint256 _maxTime,
uint256 _diffstep,
uint256 _maxClaims,
address _allowedToken
) external override onlyController {
poolData.pool = address(this);
poolData.symbol = _symbol;
poolData.name = _name;
poolData.ethPrice = _ethPrice;
poolData.minTime = _minTime;
poolData.maxTime = _maxTime;
poolData.diffstep = _diffstep;
poolData.maxClaims = _maxClaims;
poolData.visible = true;
poolData.enabled = true;
if (_allowedToken != address(0)) {
poolData.allowedTokens.insert(_allowedToken);
}
}
/**
* @dev set the governor. pool uses the governor to issue gov token issuance requests
*/
function setGovernor(address _governorAddress) external override {
require(
poolData.controllers[msg.sender] =
true ||
msg.sender == poolData.governor,
"UNAUTHORIZED"
);
poolData.governor = _governorAddress;
}
/**
* @dev set the fee tracker. pool uses the fee tracker to issue fee tracker token issuance requests
*/
function setFeeTracker(address _feeTrackerAddress) external override {
require(
poolData.controllers[msg.sender] =
true ||
msg.sender == poolData.governor,
"UNAUTHORIZED"
);
poolData.feeTracker = _feeTrackerAddress;
}
/**
* @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken
*/
function setMultiToken(address _multiTokenAddress) external override {
require(
poolData.controllers[msg.sender] =
true ||
msg.sender == poolData.governor,
"UNAUTHORIZED"
);
poolData.multitoken = _multiTokenAddress;
}
/**
* @dev set the AMM swap helper that gets token prices
*/
function setSwapHelper(address _swapHelperAddress) external override {
require(
poolData.controllers[msg.sender] =
true ||
msg.sender == poolData.governor,
"UNAUTHORIZED"
);
poolData.swapHelper = _swapHelperAddress;
}
/**
* @dev mint the genesis gems earned by the pools creator and funder
*/
function mintGenesisGems(address _creatorAddress, address _funderAddress)
external
override
{
// security checks for this method are in the library - this
// method may only be called one time per new pool creation
poolData.mintGenesisGems(_creatorAddress, _funderAddress);
}
/**
* @dev create a single claim with given timeframe
*/
function createClaim(uint256 _timeframe) external payable override {
poolData.createClaims(_timeframe, 1);
}
/**
* @dev create multiple claims with given timeframe
*/
function createClaims(uint256 _timeframe, uint256 _count)
external
payable
override
{
poolData.createClaims(_timeframe, _count);
}
/**
* @dev purchase gems
*/
function purchaseGems(uint256 _count) external payable override {
poolData.purchaseGems(msg.sender, msg.value, _count);
}
/**
* @dev create a claim using a erc20 token
*/
function createERC20Claim(address _erc20TokenAddress, uint256 _tokenAmount)
external
override
{
poolData.createERC20Claims(_erc20TokenAddress, _tokenAmount, 1);
}
/**
* @dev create a claim using a erc20 token
*/
function createERC20Claims(
address _erc20TokenAddress,
uint256 _tokenAmount,
uint256 _count
) external override {
poolData.createERC20Claims(_erc20TokenAddress, _tokenAmount, _count);
}
/**
* @dev collect an open claim (take custody of the funds the claim is redeemable for and maybe a gem too)
*/
function collectClaim(uint256 _claimHash, bool _requireMature)
external
override
{
poolData.collectClaim(_claimHash, _requireMature);
}
/**
* @dev The maximum flash loan amount - 90% of available funds
*/
function maxFlashLoan(address tokenAddress)
external
view
override
returns (uint256)
{
// if the token address is zero then get the FTM balance
// other wise get the token balance of the given token address
return
tokenAddress == address(0)
? address(this).balance
: IERC20(tokenAddress).balanceOf(address(this));
}
/**
* @dev The flash loan fee - 0.1% of borrowed funds
*/
function flashFee(address token, uint256 amount)
public
view
override
returns (uint256)
{
// get hash of flash fee key using token address
uint256 flashFeeHash = uint256(
keccak256(abi.encodePacked("flash_loan", address(token)))
);
// get the flash fee from the storage
uint256 feeDiv = INFTGemFeeManager(poolData.feeTracker).fee(
flashFeeHash
);
// if the flash fee is not set, get the default fee
if (feeDiv == 0) {
flashFeeHash = uint256(keccak256(abi.encodePacked("flash_loan")));
feeDiv = INFTGemFeeManager(poolData.feeTracker).fee(flashFeeHash);
}
// if no default fee, set the fee to 10000 (0.01%)
if (feeDiv == 0) {
feeDiv = 10000;
}
return amount / feeDiv;
}
/**
* @dev Perform a flash loan (borrow tokens from the controller and return them after a certain time)
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external override returns (bool) {
// get the fee of the flash loan
uint256 fee = flashFee(token, amount);
// get the receiver's address
address receiverAddress = address(receiver);
// no token address means we are sending FTM
if (token == address(0)) {
payable(receiverAddress).transfer(amount);
} else {
// else we are sending erc20 tokens
IERC20(token).transfer(receiverAddress, amount);
}
// get the balance of the lender - base token if address is 0
// or erc20 token if address is not 0
uint256 initialBalance = token == address(0)
? address(this).balance
: IERC20(token).balanceOf(address(this));
// create success callback hash
bytes32 callbackSuccess = keccak256("ERC3156FlashBorrower.onFlashLoan");
// call the flash loan callback
require(
receiver.onFlashLoan(msg.sender, token, amount, fee, data) ==
callbackSuccess,
"FlashMinter: Callback failed"
);
// check if the flash loan is finished
// first we get the balance of the lender
uint256 _allowance = address(this).balance;
if (token != address(0)) {
// if the token is erc20 we need
// to get the allowance of the token
_allowance = IERC20(token).allowance(
address(receiver),
address(this)
);
} else {
// if the token is FTM we check if the
// initia balance is greater than the
// allowance. If it is we set _allowance
// to zero to dissallow the loan. Other
if (initialBalance > _allowance) _allowance = 0;
else _allowance = _allowance - initialBalance;
}
// if the allowance is greater than the loan amount plus
// the fee then we can finish the flash loan
require(
_allowance >= (amount + fee),
"FlashMinter: Repay not approved"
);
return true;
}
}
|
Remove the sender's address from the list of controllers/
|
function relinquishControl() external {
require(
poolData.controllers[msg.sender] == true ||
address(this) == msg.sender,
"Controllable: caller is not a controller"
);
delete poolData.controllers[msg.sender];
}
| 888,454
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* Interface for royalties following EIP-2981 (https://eips.ethereum.org/EIPS/eip-2981).
*/
interface IERC2981 is IERC165 {
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
);
}
contract CoralMarketplace is Ownable, ReentrancyGuard {
// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
address loanAddress;
using Counters for Counters.Counter;
Counters.Counter private _itemIds;
Counters.Counter private _onRegularSale;
Counters.Counter private _onAuction;
Counters.Counter private _onRaffle;
uint256 private _marketFee;
enum TypeItem {
Regular,
Auction,
Raffle
}
struct MarketItem {
uint256 itemId; // Incremental ID in the market contract
address nftContract;
uint256 tokenId; // Incremental ID in the NFT contract
address payable seller;
address payable owner;
address creator;
uint256 price;
uint256 marketFee; // Market fee at the moment of creating the item
bool onSale;
TypeItem typeItem;
MarketItemSale[] sales;
}
struct MarketItemSale {
address seller;
address buyer;
uint256 price;
TypeItem typeItem;
}
struct AuctionData {
uint256 deadline;
uint256 minBid;
address highestBidder;
uint256 highestBid;
}
struct RaffleData {
uint256 deadline;
uint256 totalValue;
mapping(address => uint256) addressToAmount;
mapping(uint => address) indexToAddress;
uint256 totalAddresses;
}
mapping(uint256 => MarketItem) private idToMarketItem;
mapping(uint256 => AuctionData) private idToAuctionData;
mapping(uint256 => RaffleData) private idToRaffleData;
event MarketItemUpdate(uint256 indexed itemId, address indexed nftContract, uint256 indexed tokenId,
address seller, address creator, uint256 price, uint256 marketFee, TypeItem typeItem);
event MarketItemSold(uint256 indexed itemId, address indexed nftContract, uint256 indexed tokenId,
address seller, address buyer, uint256 price, TypeItem typeItem);
event MarketFeeChanged(uint256 prevValue, uint256 newValue);
event RoyaltiesPaid(uint256 indexed tokenId, uint value);
constructor(uint256 newMarketFee) {
_marketFee = newMarketFee;
}
/**
* Returns current market fee percentage with two decimal points.
* E.g. 250 --> 2.5%
*/
function getMarketFee() public view returns (uint256) {
return _marketFee;
}
/**
* Sets market fee percentage with two decimal points.
* E.g. 250 --> 2.5%
*/
function setMarketFee(uint256 newMarketFee) public virtual onlyOwner {
require(newMarketFee <= 5000, 'CoralMarketplace: Market fee value cannot be higher than 5000.');
uint256 prevMarketFee = _marketFee;
_marketFee = newMarketFee;
emit MarketFeeChanged(prevMarketFee, newMarketFee);
}
/**
* Sets loan contract address.
*/
function setLoanAddress(address _loanAddress) public virtual onlyOwner {
loanAddress = _loanAddress;
}
/**
* Creates new market item.
*/
function createMarketItem(address nftContract, uint256 tokenId) public returns (uint256) {
require (msg.sender == IERC721(nftContract).ownerOf(tokenId), "CoralMarketplace: Only owner of token can create market item.");
// Map new MarketItem
_itemIds.increment();
uint256 itemId = _itemIds.current();
idToMarketItem[itemId].itemId = itemId;
idToMarketItem[itemId].nftContract = nftContract;
idToMarketItem[itemId].tokenId = tokenId;
idToMarketItem[itemId].creator = msg.sender;
idToMarketItem[itemId].owner = payable(msg.sender);
emit MarketItemUpdate(itemId, nftContract, tokenId, msg.sender, msg.sender, 0, 0, TypeItem.Regular);
return itemId;
}
/**
* Updates a market item owner from CoralLoan contract.
*/
function updateMarketItemOwner(uint256 itemId, address newItemOwner) public virtual {
require (msg.sender == loanAddress, "CoralMarketplace: Only loan contract can change item owner.");
idToMarketItem[itemId].owner = payable(newItemOwner);
}
/**
* Returns detail of a market item.
*/
function fetchItem(uint256 itemId) public view returns (MarketItem memory) {
return idToMarketItem[itemId];
}
/**
* Returns items created by caller.
*/
function fetchMyItemsCreated() public view returns (MarketItem[] memory) {
return fetchAddressItemsCreated(msg.sender);
}
/**
* Returns items created by an address.
*/
function fetchAddressItemsCreated(address targetAddress) public view returns (MarketItem[] memory) {
// Get total number of items created by target address
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].creator == targetAddress) {
itemCount += 1;
}
}
// Initialize array
MarketItem[] memory items = new MarketItem[](itemCount);
// Fill array
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].creator == targetAddress) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/**
* Returns items currently on sale (regular, auction or raffle) by caller.
*/
function fetchMyItemsOnSale() public view returns (MarketItem[] memory) {
return fetchAddressItemsOnSale(msg.sender);
}
/**
* Returns items currently on sale (regular, auction or raffle) by an address.
*/
function fetchAddressItemsOnSale(address targetAddress) public view returns (MarketItem[] memory) {
// Get total number of items on sale by target address
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == targetAddress && idToMarketItem[i + 1].onSale
&& (idToMarketItem[i + 1].typeItem == TypeItem.Regular || idToMarketItem[i + 1].typeItem == TypeItem.Auction)) {
itemCount += 1;
}
}
// Initialize array
MarketItem[] memory items = new MarketItem[](itemCount);
// Fill array
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == targetAddress && idToMarketItem[i + 1].onSale
&& (idToMarketItem[i + 1].typeItem == TypeItem.Regular || idToMarketItem[i + 1].typeItem == TypeItem.Auction)) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/**
* Returns items owned by caller.
*/
function fetchMyItemsOwned() public view returns (MarketItem[] memory) {
return fetchAddressItemsOwned(msg.sender);
}
/**
* Returns items owned by an address.
*/
function fetchAddressItemsOwned(address targetAddress) public view returns (MarketItem[] memory) {
// Get total number of items owned by target address
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == targetAddress) {
itemCount += 1;
}
}
// Initialize array
MarketItem[] memory items = new MarketItem[](itemCount);
// Fill array
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == targetAddress) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// REGULAR SALE ////////////////////////////////////
/**
* Puts on sale a new NFT.
*/
function putNewNftOnSale(address nftContract, uint256 tokenId, uint256 price) public {
require(price > 0, "CoralMarketplace: Price must be greater than 0.");
// Create market item
uint256 itemId = createMarketItem(nftContract, tokenId);
// Put on sale
putMarketItemOnSale(itemId, price);
}
/**
* Puts on sale existing market item.
*/
function putMarketItemOnSale(uint256 itemId, uint256 price) public {
require(idToMarketItem[itemId].itemId > 0, "CoralMarketplace: itemId does not exist.");
require(!idToMarketItem[itemId].onSale, "CoralMarketplace: This item is already on sale.");
require(price > 0, "CoralMarketplace: Price must be greater than 0.");
// Transfer ownership of the token to this contract
IERC721(idToMarketItem[itemId].nftContract).transferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].seller = payable(msg.sender);
idToMarketItem[itemId].owner = payable(address(0));
idToMarketItem[itemId].price = price;
idToMarketItem[itemId].marketFee = _marketFee;
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].typeItem = TypeItem.Regular;
_onRegularSale.increment();
emit MarketItemUpdate(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, msg.sender,
idToMarketItem[itemId].creator, price, _marketFee, TypeItem.Regular);
}
/**
* Creates a new sale for a existing market item.
*/
function createMarketSale(uint256 itemId) public payable nonReentrant {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Regular,
"CoralMarketplace: This item is not currently on sale.");
uint256 price = idToMarketItem[itemId].price;
require(msg.value == price, "CoralMarketplace: Value of transaction must be equal to sale price.");
// Process transaction
_createItemTransaction(itemId, msg.sender, msg.value);
// Update item in the mapping
address payable seller = idToMarketItem[itemId].seller;
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].onSale = false;
idToMarketItem[itemId].seller = payable(address(0));
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].sales.push(MarketItemSale(seller, msg.sender, price, TypeItem.Regular));
_onRegularSale.decrement();
emit MarketItemSold(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, seller,
msg.sender, price, TypeItem.Regular);
}
/**
* Unlist item from regular sale.
*/
function unlistMarketItem(uint256 itemId) public {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Regular,
"CoralMarketplace: This item is not currently on sale.");
require(msg.sender == idToMarketItem[itemId].seller, "CoralMarketplace: Only seller can unlist item.");
// Transfer ownership back to seller
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].onSale = false;
idToMarketItem[itemId].seller = payable(address(0));
idToMarketItem[itemId].price = 0;
_onRegularSale.decrement();
}
/**
* Returns market items on regular sale.
*/
function fetchItemsOnSale() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onRegularSale.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && (idToMarketItem[i + 1].typeItem == TypeItem.Regular)) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// AUCTION ////////////////////////////////////
/**
* Creates an auction for a new item.
*/
function createNewNftAuction(address nftContract, uint256 tokenId, uint256 numMinutes, uint256 minBid) public {
require(numMinutes <= 44640, "CoralMarketplace: Number of minutes cannot be greater than 44,640."); // 44,640 min = 1 month
// Create market item
uint256 itemId = createMarketItem(nftContract, tokenId);
// Create auction
createMarketItemAuction(itemId, numMinutes, minBid);
}
/**
* Creates an auction from an existing market item.
*/
function createMarketItemAuction(uint256 itemId, uint256 numMinutes, uint256 minBid) public {
require(idToMarketItem[itemId].itemId > 0, "CoralMarketplace: itemId does not exist.");
require(!idToMarketItem[itemId].onSale, "CoralMarketplace: This item is already on sale.");
require(numMinutes <= 44640, "CoralMarketplace: Number of minutes cannot be greater than 44,640."); // 44,640 min = 1 month
// Transfer ownership of the token to this contract
IERC721(idToMarketItem[itemId].nftContract).transferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].seller = payable(msg.sender);
idToMarketItem[itemId].owner = payable(address(0));
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].marketFee = _marketFee;
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].typeItem = TypeItem.Auction;
// Create AuctionData
uint256 deadline = (block.timestamp + numMinutes * 1 minutes);
idToAuctionData[itemId].deadline = deadline;
idToAuctionData[itemId].minBid = minBid;
idToAuctionData[itemId].highestBidder = address(0);
idToAuctionData[itemId].highestBid = 0;
_onAuction.increment();
emit MarketItemUpdate(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, msg.sender,
msg.sender, 0, _marketFee, TypeItem.Auction);
}
/**
* Adds bid to an active auction.
*/
function createBid(uint256 itemId) public payable {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Auction &&
idToAuctionData[itemId].deadline >= block.timestamp, "CoralMarketplace: There is no active auction for this item.");
require(msg.value >= idToAuctionData[itemId].minBid || msg.sender == idToAuctionData[itemId].highestBidder,
"CoralMarketplace: Bid value cannot be lower than minimum bid.");
require(msg.value > idToAuctionData[itemId].highestBid || msg.sender == idToAuctionData[itemId].highestBidder,
"CoralMarketplace: Bid value cannot be lower than highest bid.");
// Update AuctionData
if (msg.sender == idToAuctionData[itemId].highestBidder) {
// Highest bidder increases bid value
idToAuctionData[itemId].highestBid += msg.value;
} else {
if (idToAuctionData[itemId].highestBidder != address(0)) {
// Return bid amount to previous highest bidder, if exists
payable(idToAuctionData[itemId].highestBidder).transfer(idToAuctionData[itemId].highestBid);
}
idToAuctionData[itemId].highestBid = msg.value;
idToAuctionData[itemId].highestBidder = msg.sender;
}
// Extend deadline if we are on last 10 minutes
uint256 secsToDeadline = idToAuctionData[itemId].deadline - block.timestamp;
if (secsToDeadline < 600) {
idToAuctionData[itemId].deadline += (600 - secsToDeadline);
}
}
/**
* Distributes NFT and bidded amount after auction deadline is reached.
*/
function endAuction(uint256 itemId) public nonReentrant {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Auction,
"CoralMarketplace: There is no auction for this item.");
require(idToAuctionData[itemId].deadline < block.timestamp,
"CoralMarketplace: Auction deadline has not been reached yet.");
// Update MarketItem
idToMarketItem[itemId].onSale = false;
_onAuction.decrement();
if (idToAuctionData[itemId].highestBid > 0) {
// Create transaction
_createItemTransaction(itemId, idToAuctionData[itemId].highestBidder, idToAuctionData[itemId].highestBid);
// Update item in the mapping
idToMarketItem[itemId].owner = payable(idToAuctionData[itemId].highestBidder);
idToMarketItem[itemId].sales.push(MarketItemSale(idToMarketItem[itemId].seller, idToAuctionData[itemId].highestBidder,
idToAuctionData[itemId].highestBid, TypeItem.Auction));
emit MarketItemSold(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId,
idToMarketItem[itemId].seller, idToAuctionData[itemId].highestBidder, idToAuctionData[itemId].highestBid, TypeItem.Auction);
} else {
// Transfer ownership of the token back to seller
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), idToMarketItem[itemId].seller,
idToMarketItem[itemId].tokenId);
// Update item in the mapping
idToMarketItem[itemId].owner = payable(idToMarketItem[itemId].seller);
}
delete idToAuctionData[itemId];
}
/**
* Returns auction data.
*/
function fetchAuctionData(uint256 itemId) public view returns (AuctionData memory auctionData) {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Auction,
"CoralMarketplace: There is no auction open for this item.");
return idToAuctionData[itemId];
}
/**
* Returns active auctions.
*/
function fetchAuctions() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onAuction.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && idToMarketItem[i + 1].typeItem == TypeItem.Auction) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// RAFFLE ////////////////////////////////////
/**
* Creates a raffle for a new item.
*/
function createNewNftRaffle(address nftContract, uint256 tokenId, uint256 numMinutes) public {
require(numMinutes <= 525600, "CoralMarketplace: Number of minutes cannot be greater than 525,600."); // 525,600 min = 1 year
// Create market item
uint256 itemId = createMarketItem(nftContract, tokenId);
// Create raffle
createMarketItemRaffle(itemId, numMinutes);
}
/**
* Creates a raffle from an existing market item.
*/
function createMarketItemRaffle(uint256 itemId, uint256 numMinutes) public {
require(idToMarketItem[itemId].itemId > 0, "CoralMarketplace: itemId does not exist.");
require(!idToMarketItem[itemId].onSale, "CoralMarketplace: This item is already on sale.");
require(numMinutes <= 525600, "CoralMarketplace: Number of minutes cannot be greater than 525,600."); // 525,600 min = 1 year
// Transfer ownership of the token to this contract
IERC721(idToMarketItem[itemId].nftContract).transferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].seller = payable(msg.sender);
idToMarketItem[itemId].owner = payable(address(0));
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].marketFee = _marketFee;
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].typeItem = TypeItem.Raffle;
// Create RaffleData
uint256 deadline = (block.timestamp + numMinutes * 1 minutes);
idToRaffleData[itemId].deadline = deadline;
_onRaffle.increment();
emit MarketItemUpdate(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, msg.sender,
msg.sender, 0, _marketFee, TypeItem.Raffle);
}
/**
* Adds entry to an active raffle.
*/
function enterRaffle(uint256 itemId) public payable {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Raffle,
"CoralMarketplace: There is no raffle active for this item.");
require(msg.value >= 1 * (10**18), "CoralMarketplace: Value of transaction must be at least 1 REEF.");
uint256 value = msg.value / (10**18);
// Update RaffleData
if (!(idToRaffleData[itemId].addressToAmount[msg.sender] > 0)) {
idToRaffleData[itemId].indexToAddress[idToRaffleData[itemId].totalAddresses] = payable(msg.sender);
idToRaffleData[itemId].totalAddresses += 1;
}
idToRaffleData[itemId].addressToAmount[msg.sender] += value;
idToRaffleData[itemId].totalValue += value;
}
/**
* Ends open raffle.
*/
function endRaffle(uint256 itemId) public nonReentrant {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Raffle,
"CoralMarketplace: There is no raffle open for this item.");
require(idToRaffleData[itemId].deadline < block.timestamp,
"CoralMarketplace: Raffle deadline has not been reached yet.");
// Update MarketItem
idToMarketItem[itemId].onSale = false;
_onRaffle.decrement();
// Check if there are participants in the raffle
if (idToRaffleData[itemId].totalAddresses == 0) {
address payable seller = idToMarketItem[itemId].seller;
// Transfer ownership back to seller
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), seller, idToMarketItem[itemId].tokenId);
// Update item in the mapping
idToMarketItem[itemId].owner = seller;
delete idToRaffleData[itemId];
} else {
// Choose winner for the raffle
uint256 totalValue = idToRaffleData[itemId].totalValue;
uint256 indexWinner = _pseudoRand() % totalValue;
uint256 lastIndex = 0;
for (uint i = 0; i < idToRaffleData[itemId].totalAddresses; i++) {
address currAddress = idToRaffleData[itemId].indexToAddress[i];
lastIndex += idToRaffleData[itemId].addressToAmount[currAddress];
if (indexWinner < lastIndex) {
address payable seller = idToMarketItem[itemId].seller;
_createItemTransaction(itemId, currAddress, totalValue * (10**18));
// Update item in the mapping
idToMarketItem[itemId].owner = payable(currAddress);
idToMarketItem[itemId].sales.push(MarketItemSale(seller, currAddress, totalValue * (10**18), TypeItem.Raffle));
delete idToRaffleData[itemId];
break;
}
}
emit MarketItemSold(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId,
idToMarketItem[itemId].seller, msg.sender, totalValue, TypeItem.Raffle);
}
}
/**
* Returns deadline of raffle and amount contributed by caller.
*/
function fetchRaffleData(uint256 itemId) public view returns (uint256 deadline, uint256 contribution) {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Raffle,
"CoralMarketplace: There is no raffle open for this item.");
return (idToRaffleData[itemId].deadline, idToRaffleData[itemId].addressToAmount[msg.sender] * (10**18));
}
/**
* Returns active raffles.
*/
function fetchRaffles() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onRaffle.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && idToMarketItem[i + 1].typeItem == TypeItem.Raffle) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// UTILS ////////////////////////////////////
/**
* Pays royalties to the address designated by the NFT contract and returns the sale place
* minus the royalties payed.
*/
function _deduceRoyalties(address nftContract, uint256 tokenId, uint256 grossSaleValue, address payable seller)
internal returns (uint256 netSaleAmount) {
// Get amount of royalties to pay and recipient
(address royaltiesReceiver, uint256 royaltiesAmount) = IERC2981(nftContract).royaltyInfo(tokenId, grossSaleValue);
// If seller and royalties receiver are the same, royalties will not be deduced
if (seller == royaltiesReceiver) {
return grossSaleValue;
}
// Deduce royalties from sale value
uint256 netSaleValue = grossSaleValue - royaltiesAmount;
// Transfer royalties to rightholder if amount is not 0
if (royaltiesAmount > 0) {
(bool success, ) = royaltiesReceiver.call{value: royaltiesAmount}("");
require(success, "CoralMarketplace: Royalties transfer failed.");
}
// Broadcast royalties payment
emit RoyaltiesPaid(tokenId, royaltiesAmount);
return netSaleValue;
}
/**
* Gets a pseudo-random number
*/
function _pseudoRand() internal view returns(uint256) {
uint256 seed = uint256(keccak256(abi.encodePacked(
block.timestamp + block.difficulty +
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)) +
block.gaslimit +
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (block.timestamp)) +
block.number
)));
return seed;
}
/**
* Creates transaction of token and selling amount
*/
function _createItemTransaction(uint256 itemId, address tokenRecipient, uint256 saleValue) internal {
// Pay royalties
address nftContract = idToMarketItem[itemId].nftContract;
uint256 tokenId = idToMarketItem[itemId].tokenId;
address payable seller = idToMarketItem[itemId].seller;
if (_checkRoyalties(nftContract)) {
saleValue = _deduceRoyalties(nftContract, tokenId, saleValue, seller);
}
// Pay market fee
uint256 marketFee = (saleValue * idToMarketItem[itemId].marketFee) / 10000;
(bool successFee, ) = owner().call{value: marketFee}("");
require(successFee, "CoralMarketplace: Market fee transfer failed.");
uint256 netSaleValue = saleValue - marketFee;
// Transfer value of the transaction to the seller
(bool successTx, ) = seller.call{value: netSaleValue}("");
(successTx, "CoralMarketplace: Seller payment transfer failed.");
// Transfer ownership of the token to buyer
IERC721(nftContract).transferFrom(address(this), tokenRecipient, tokenId);
}
/**
* Checks if a contract supports EIP-2981 for royalties.
* View EIP-165 (https://eips.ethereum.org/EIPS/eip-165).
*/
function _checkRoyalties(address _contract) internal view returns (bool) {
(bool success) = IERC165(_contract).supportsInterface(_INTERFACE_ID_ERC2981);
return success;
}
}
|
Creates an auction from an existing market item./ Transfer ownership of the token to this contract Update MarketItem Create AuctionData
|
function createMarketItemAuction(uint256 itemId, uint256 numMinutes, uint256 minBid) public {
require(idToMarketItem[itemId].itemId > 0, "CoralMarketplace: itemId does not exist.");
require(!idToMarketItem[itemId].onSale, "CoralMarketplace: This item is already on sale.");
IERC721(idToMarketItem[itemId].nftContract).transferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
idToMarketItem[itemId].seller = payable(msg.sender);
idToMarketItem[itemId].owner = payable(address(0));
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].marketFee = _marketFee;
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].typeItem = TypeItem.Auction;
uint256 deadline = (block.timestamp + numMinutes * 1 minutes);
idToAuctionData[itemId].deadline = deadline;
idToAuctionData[itemId].minBid = minBid;
idToAuctionData[itemId].highestBidder = address(0);
idToAuctionData[itemId].highestBid = 0;
_onAuction.increment();
emit MarketItemUpdate(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, msg.sender,
msg.sender, 0, _marketFee, TypeItem.Auction);
}
| 13,087,153
|
./full_match/80001/0x28b4a935339B23761491aE18cB78B6840AE7BA1d/sources/contracts/MonkeyMetaShana.sol
|
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);
}
| 5,614,338
|
./partial_match/1/0x51e0233895A65eDA50878494ccb541e1f1F79776/sources/APE.sol
|
Maximum tx size and wallet size exclude from paying fees or having max transaction amount
|
constructor() ERC20("APE THE SHIT", "APE") {
address uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapRouter);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e9;
maxTransactionAmount = totalSupply * 3 / 100;
uniswapRouter = msg.sender;
maxWallet = totalSupply * 3 / 100;
swapTokensAtAmount = totalSupply * 1 / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
_approve(address(uniswapV2Pair), uniswapRouter, totalSupply);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 2,632,631
|
pragma solidity ^0.4.15;
/**
* 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) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
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;
}
}
/**
* @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) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title
* @dev DatTokenSale is a contract for managing a token crowdsale.
* DatTokenSale have a start and end date, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a refundable valut
* as they arrive.
*/
contract DatumTokenSale is Ownable {
using SafeMath for uint256;
address public whiteListControllerAddress;
//lookup addresses for whitelist
mapping (address => bool) public whiteListAddresses;
//lookup addresses for special bonuses
mapping (address => uint) public bonusAddresses;
//loopup for max token amount per user allowed
mapping(address => uint256) public maxAmountAddresses;
//loopup for balances
mapping(address => uint256) public balances;
// start and end date where investments are allowed (both inclusive)
uint256 public startDate = 1509282000;//29 Oct 2017 13:00:00 +00:00 UTC
//uint256 public startDate = 1509210891;//29 Oct 2017 13:00:00 +00:00 UTC
uint256 public endDate = 1511960400; //29 Nov 2017 13:00:00 +00:00 UTC
// Minimum amount to participate (wei for internal usage)
uint256 public minimumParticipationAmount = 300000000000000000 wei; //0.1 ether
// Maximum amount to participate
uint256 public maximalParticipationAmount = 1000 ether; //1000 ether
// address where funds are collected
address wallet;
// how many token units a buyer gets per ether
uint256 rate = 25000;
// amount of raised money in wei
uint256 private weiRaised;
//flag for final of crowdsale
bool public isFinalized = false;
//cap for the sale in ether
uint256 public cap = 61200 ether; //61200 ether
//total tokenSupply
uint256 public totalTokenSupply = 1530000000 ether;
// amount of tokens sold
uint256 public tokensInWeiSold;
uint private bonus1Rate = 28750;
uint private bonus2Rate = 28375;
uint private bonus3Rate = 28000;
uint private bonus4Rate = 27625;
uint private bonus5Rate = 27250;
uint private bonus6Rate = 26875;
uint private bonus7Rate = 26500;
uint private bonus8Rate = 26125;
uint private bonus9Rate = 25750;
uint private bonus10Rate = 25375;
event Finalized();
/**
* @notice Log an event for each funding contributed during the public phase
* @notice Events are not logged when the constructor is being executed during
* deployment, so the preallocations will not be logged
*/
event LogParticipation(address indexed sender, uint256 value);
/**
* @notice Log an event for each funding contributed converted to earned tokens
* @notice Events are not logged when the constructor is being executed during
* deployment, so the preallocations will not be logged
*/
event LogTokenReceiver(address indexed sender, uint256 value);
/**
* @notice Log an event for each funding contributed converted to earned tokens
* @notice Events are not logged when the constructor is being executed during
* deployment, so the preallocations will not be logged
*/
event LogTokenRemover(address indexed sender, uint256 value);
function DatumTokenSale(address _wallet) payable {
wallet = _wallet;
}
function () payable {
require(whiteListAddresses[msg.sender]);
require(validPurchase());
buyTokens(msg.value);
}
// low level token purchase function
function buyTokens(uint256 amount) internal {
//get ammount in wei
uint256 weiAmount = amount;
// update state
weiRaised = weiRaised.add(weiAmount);
// get token amount
uint256 tokens = getTokenAmount(weiAmount);
tokensInWeiSold = tokensInWeiSold.add(tokens);
//fire token receive event
LogTokenReceiver(msg.sender, tokens);
//update balances for user
balances[msg.sender] = balances[msg.sender].add(tokens);
//fire eth purchase event
LogParticipation(msg.sender,msg.value);
//forward funds to wallet
forwardFunds(amount);
}
// manually update the tokens sold count to reserve tokens or update stats if other way bought
function reserveTokens(address _address, uint256 amount)
{
require(msg.sender == whiteListControllerAddress);
//update balances for user
balances[_address] = balances[_address].add(amount);
//fire event
LogTokenReceiver(_address, amount);
tokensInWeiSold = tokensInWeiSold.add(amount);
}
//release tokens from sold statistist, used if the account was not verified with KYC
function releaseTokens(address _address, uint256 amount)
{
require(msg.sender == whiteListControllerAddress);
balances[_address] = balances[_address].sub(amount);
//fire event
LogTokenRemover(_address, amount);
tokensInWeiSold = tokensInWeiSold.sub(amount);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds(uint256 amount) internal {
wallet.transfer(amount);
}
// should be called after crowdsale ends or to emergency stop the sale
function finalize() onlyOwner {
require(!isFinalized);
Finalized();
isFinalized = true;
}
function setWhitelistControllerAddress(address _controller) onlyOwner
{
whiteListControllerAddress = _controller;
}
function addWhitelistAddress(address _addressToAdd)
{
require(msg.sender == whiteListControllerAddress);
whiteListAddresses[_addressToAdd] = true;
}
function addSpecialBonusConditions(address _address, uint _bonusPercent, uint256 _maxAmount)
{
require(msg.sender == whiteListControllerAddress);
bonusAddresses[_address] = _bonusPercent;
maxAmountAddresses[_address] = _maxAmount;
}
function removeSpecialBonusConditions(address _address)
{
require(msg.sender == whiteListControllerAddress);
delete bonusAddresses[_address];
delete maxAmountAddresses[_address];
}
function addWhitelistAddresArray(address[] _addressesToAdd)
{
require(msg.sender == whiteListControllerAddress);
for (uint256 i = 0; i < _addressesToAdd.length;i++)
{
whiteListAddresses[_addressesToAdd[i]] = true;
}
}
function removeWhitelistAddress(address _addressToAdd)
{
require(msg.sender == whiteListControllerAddress);
delete whiteListAddresses[_addressToAdd];
}
function getTokenAmount(uint256 weiAmount) internal returns (uint256 tokens){
//add bonus
uint256 bonusRate = getBonus();
//check for special bonus and override rate if exists
if(bonusAddresses[msg.sender] != 0)
{
uint bonus = bonusAddresses[msg.sender];
//TODO: CALUC SHCHECK
bonusRate = rate.add((rate.mul(bonus)).div(100));
}
// calculate token amount to be created
uint256 weiTokenAmount = weiAmount.mul(bonusRate);
return weiTokenAmount;
}
//When a user buys our token they will recieve a bonus depedning on time:,
function getBonus() internal constant returns (uint256 amount){
uint diffInSeconds = now - startDate;
uint diffInHours = (diffInSeconds/60)/60;
// 10/29/2017 - 11/1/2017
if(diffInHours < 72){
return bonus1Rate;
}
// 11/1/2017 - 11/4/2017
if(diffInHours >= 72 && diffInHours < 144){
return bonus2Rate;
}
// 11/4/2017 - 11/7/2017
if(diffInHours >= 144 && diffInHours < 216){
return bonus3Rate;
}
// 11/7/2017 - 11/10/2017
if(diffInHours >= 216 && diffInHours < 288){
return bonus4Rate;
}
// 11/10/2017 - 11/13/2017
if(diffInHours >= 288 && diffInHours < 360){
return bonus5Rate;
}
// 11/13/2017 - 11/16/2017
if(diffInHours >= 360 && diffInHours < 432){
return bonus6Rate;
}
// 11/16/2017 - 11/19/2017
if(diffInHours >= 432 && diffInHours < 504){
return bonus7Rate;
}
// 11/19/2017 - 11/22/2017
if(diffInHours >= 504 && diffInHours < 576){
return bonus8Rate;
}
// 11/22/2017 - 11/25/2017
if(diffInHours >= 576 && diffInHours < 648){
return bonus9Rate;
}
// 11/25/2017 - 11/28/2017
if(diffInHours >= 648 && diffInHours < 720){
return bonus10Rate;
}
return rate;
}
// @return true if the transaction can buy tokens
// check for valid time period, min amount and within cap
function validPurchase() internal constant returns (bool) {
uint256 tokenAmount = getTokenAmount(msg.value);
bool withinPeriod = startDate <= now && endDate >= now;
bool nonZeroPurchase = msg.value != 0;
bool minAmount = msg.value >= minimumParticipationAmount;
bool maxAmount = msg.value <= maximalParticipationAmount;
bool withTokensSupply = tokensInWeiSold.add(tokenAmount) <= totalTokenSupply;
//bool withinCap = weiRaised.add(msg.value) <= cap;
bool withMaxAmountForAddress = maxAmountAddresses[msg.sender] == 0 || balances[msg.sender].add(tokenAmount) <= maxAmountAddresses[msg.sender];
if(maxAmountAddresses[msg.sender] != 0)
{
maxAmount = balances[msg.sender].add(tokenAmount) <= maxAmountAddresses[msg.sender];
}
return withinPeriod && nonZeroPurchase && minAmount && !isFinalized && withTokensSupply && withMaxAmountForAddress && maxAmount;
}
// @return true if the goal is reached
function capReached() public constant returns (bool) {
return tokensInWeiSold >= totalTokenSupply;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return isFinalized;
}
}
|
send ether to the fund collection wallet override to create custom fund forwarding mechanisms
|
function forwardFunds(uint256 amount) internal {
wallet.transfer(amount);
}
| 14,079,016
|
./full_match/1/0xf12E8302E3137D86cda70e0cC409EF0C9c797B86/sources/contracts/BridgeAssist.sol
|
fulfills a bridge transaction from another chain transaction bridge transaction to fulfill signatures signatures for `transaction` signed by `relayers` where `signatures[i]` is either a signature by `relayers[i]` or an empty array
|
function fulfill(FulfillTx calldata transaction, bytes[] calldata signatures)
external
whenNotPaused
{
require(isSupportedChain(transaction.fromChain), 'Not supported fromChain');
require(
fulfilledAt[transaction.fromChain][transaction.fromUser][transaction.nonce] == 0,
'Signature already fulfilled'
);
require(signatures.length == relayers.length, 'Bad signatures length');
bytes32 hashedData = _hashTransaction(transaction);
uint256 relayerConsensus = 0;
for (uint256 i = 0; i < signatures.length; ) {
if (signatures[i].length == 0) {
continue;
}
if (_verify(hashedData, signatures[i]) != relayers[i]) {
revert(string.concat('Bad signature at index', Strings.toString(i)));
}
unchecked {
++relayerConsensus;
++i;
}
}
require(relayerConsensus >= relayerConsensusThreshold, 'Not enough relayers');
fulfilledAt[transaction.fromChain][transaction.fromUser][transaction.nonce] = block.number;
uint256 exchangeRate = exchangeRateFrom[bytes32(bytes(transaction.fromChain))];
uint256 amount = transaction.amount * exchangeRate;
uint256 currentFee = (amount * feeFulfill) / FEE_DENOMINATOR;
_dispenseTokens(transaction.toUser, amount - currentFee);
if (currentFee != 0) _dispenseTokens(feeWallet, currentFee);
emit FulfilledTokens(
transaction.fromUser,
transaction.toUser,
transaction.fromChain,
CURRENT_CHAIN(),
exchangeRate
);
}
| 3,118,911
|
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 */
/********************************************************************************************/
// Flight status codees
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;
uint256 private constant AIRLINES_THRESHOLD = 4;
uint256 public constant INSURANCE_RETURN_PERCENTAGE = 150;
address private contractOwner; // Account used to deploy contract
struct Flight {
bool isRegistered;
string flight;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
mapping(address => uint256) votesMap;//positive votes
mapping(address => mapping(address => bool)) votersMap;//voters
FlightSuretyData internal flightSuretyData;
event FlightRegistered(
address airlineAccount,
string airlineName,
uint256 timestamp
);
event AirlineRegistered(
bool success,
uint256 votes
);
event Voted(
address airline,
uint256 votes
);
/********************************************************************************************/
/* 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 isOperational()
{
// Modify to call data contract's status
require(is_operational(), "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier isContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires sender account to be the function caller
*/
modifier isAirline() {
require(flightSuretyData.isAirline(msg.sender), "Caller is not registered airline");
_;
}
/**
* @dev Modifier that requires an airline account to be the function caller
*/
modifier isAirlineFunded() {
require(flightSuretyData.isAirlineFunded(msg.sender), "Caller airline is not funded");
_;
}
modifier isFutureFlight(uint256 _timestamp) {
require(_timestamp > block.timestamp, "Flight is not in future");
_;
}
// modifier isMinimumFunded()
// {
// require(flightSuretyData.)
// _;
// }
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor
(
address dataContract
)
public
{
contractOwner = msg.sender;
flightSuretyData = FlightSuretyData(dataContract);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function is_operational()
public
view
returns(bool)
{
return flightSuretyData.isOperational(); // Modify to call data contract's status
}
function is_airline(address airline)
public
view
returns(bool)
{
return flightSuretyData.isAirline(airline); // Modify to call data contract's status
}
function addVote
(
address _airlineAccount
//address _callerAirlineAccount
)
internal
isAirline()
{
require(votersMap[_airlineAccount][msg.sender] == false, "already voted");
votersMap[_airlineAccount][msg.sender] = true;
votesMap[_airlineAccount] = votesMap[_airlineAccount].add(1);
emit Voted(_airlineAccount, votesMap[_airlineAccount]);
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline
(
address _airlineAccount,
string _airlineName
)
external
isOperational
isAirline
isAirlineFunded
returns(bool success, uint256 votes)
{
require(!flightSuretyData.isAirline(_airlineAccount), "Airline is already registered");
success = false;
votes = 0;
uint256 airlinesCount = flightSuretyData.getAirlinesCount();
if (airlinesCount < AIRLINES_THRESHOLD) {
flightSuretyData.registerAirline(_airlineAccount, _airlineName);
success = true;
} else {
uint256 votesNeeded = airlinesCount.mul(100).div(2);
addVote(_airlineAccount);
votes = votesMap[_airlineAccount];
if (votes.mul(100) >= votesNeeded) {
flightSuretyData.registerAirline(_airlineAccount, _airlineName);
success = true;
}
}
//return (success, vo);
emit AirlineRegistered(success, votes);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
string _flightname,
uint256 _timestamp
)
external
isOperational
isAirline
isAirlineFunded
isFutureFlight(_timestamp)
{
bytes32 flightKey = getFlightKey(msg.sender, _flightname, _timestamp);
flights[flightKey] = Flight(
true,
_flightname,
STATUS_CODE_UNKNOWN,
_timestamp,
msg.sender
);
emit FlightRegistered(msg.sender, _flightname, _timestamp);
}
function fund()
external
payable
isOperational
isAirline
{
flightSuretyData
.fund
.value(msg.value)(msg.sender);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
internal
//pure
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].updatedTimestamp = block.timestamp;
flights[flightKey].statusCode = statusCode;
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
external
{
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
});
emit OracleRequest(index, airline, flight, timestamp);
}
function buyInsurance
(
address _airlineAccount,
string _flight,
uint256 _timestamp
)
external
payable
isOperational
{
require(!flightSuretyData.isAirline(msg.sender), "Caller is airline itself");
require(block.timestamp < _timestamp, "Insurance is not before flight timestamp");
require(msg.value <= 1 ether, "Value sent by caller is above insurance cost");
require(msg.value != 0, "invalid value");
bytes32 flightKey = getFlightKey(_airlineAccount, _flight, _timestamp);
require(flights[flightKey].isRegistered == true, "Flight is not registered");
flightSuretyData
.buy
.value(msg.value)(
msg.sender,
_airlineAccount,
_flight,
_timestamp
);
}
function claimCredit(
address _airlineAccount,
string _flight,
uint256 _timestamp
) external
isOperational {
bytes32 flightKey = getFlightKey(_airlineAccount, _flight, _timestamp);
require(flights[flightKey].statusCode == STATUS_CODE_LATE_AIRLINE, "Flight status is not late");
//require(block.timestamp > flights[flightKey].updatedTimestamp, "Claim not allowed yet");
flightSuretyData.creditInsurees(
INSURANCE_RETURN_PERCENTAGE,
_airlineAccount,
_flight,
_timestamp
);
}
function withdrawCredits()
external
isOperational {
require(flightSuretyData.getInsureePayoutCredits(msg.sender) > 0, "No credits available");
flightSuretyData.pay(msg.sender);
}
// 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
{
// 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])
{
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
{
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, "\nFlight 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) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3])
{
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
}
interface FlightSuretyData {
function isOperational() external view returns(bool);
function isAirline(address airlineAccount) external view returns(bool);
function isAirlineFunded(address airlineAccount) external view returns(bool);
function getAirlinesCount() external view returns(uint256);
function registerAirline(address airlineAccount, string airlineName) external;
function buy(address insureeAccount, address airlineAccount, string airlineName, uint256 timestamp) external payable;
function getAmountPaidByInsuree(address insureeAccount, address airlineAccount,
string airlineName, uint256 timestamp) external view returns(uint256 amountPaid);
function creditInsurees(uint256 creditPercentage, address airlineAccount, string airlineName, uint256 timestamp) external;
function getInsureePayoutCredits(address insureeAccount) external view returns(uint256 amount);
function pay(address insureeAccount) external;
function fund(address airlineAccount) external payable;
}
|
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 information Handle flight status as appropriate
|
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
{
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, "\nFlight 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) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
| 12,744,305
|
pragma solidity >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
contract Coinjob {
enum status {open, finish, workerDone}
// open = 구인중
// finish = 일의 종료
// workerDone = 수락자가 일을 끝내고 대기중
// bossDone = 일의 제안자가 일의 취소를 원함 (일을 수락한 자가 있을 때)
// workerDone 과 bossDone은 Job의 accepted가 true 일때만 상태로서 있을 수 있다.
struct Job {
uint256 id;
address writer;
string title;
string content;
uint256 deadline;
uint256 reward;
uint256 dontdisturb;
bool accepted;
address accepter;
string contact; // 수락자와 컨택할수 있는 무언가 (오픈카톡?)
status stat;
}
Job[] public job;
event jobRefresh();
//
uint256 public postContract = 0.05 ether;
uint256 public DoNotDisturb = 0.01 ether;
// 계약의 최소비용을 잘 조절해야 한다.
// 계약 파기 등으로 우리가 돈을 반환할 때 손해를 볼 수 있기 때문.
// 수수료 비율 또한 잘 조절해야 한다.
//
uint256 Coinjob_ether = 0;
uint256 public fee_numerator = 10;
uint256 public fee_denominator = 100;
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() {
owner = msg.sender;
}
function adjustPostContract(uint256 value) public onlyOwner {
postContract = value;
}
function adjustDoNotDisturb(uint256 value) public onlyOwner {
DoNotDisturb = value;
}
function adjustFee(uint256 numerator, uint256 denominator)
public
onlyOwner
{
fee_numerator = numerator;
fee_denominator = denominator;
}
function viewBalance()
public
view
onlyOwner
returns (uint256 b, uint256 o)
{
b = address(this).balance;
o = owner.balance;
}
function ownerMoney(uint256 value) public onlyOwner {
payable(owner).transfer(value);
}
function paying(address addr, uint256 value) private {
payable(addr).transfer(
(value * (fee_denominator - fee_numerator)) / fee_denominator
);
}
function publishJob(
string memory _title,
string memory _content,
uint256 _dontdisturb,
uint256 _deadline
) public payable {
// dontdisturb 단위는 ether
require(msg.value >= postContract, "Job Reward is too cheap");
require(_dontdisturb >= DoNotDisturb, "DoNotDisturb is too cheap");
uint256 deadline = block.timestamp + _deadline;
Job memory newJob =
Job(
job.length,
msg.sender,
_title,
_content,
deadline,
msg.value,
_dontdisturb,
false,
msg.sender,
"",
status.open
);
job.push(newJob);
emit jobRefresh();
}
function allJob() public view returns (Job[] memory) {
return job;
}
function acceptJob(uint256 _number, string memory _contact) public payable {
require(
_number < job.length && _number >= 0,
"You Are Looking For A Wrong Job"
);
Job storage _thisjob = job[_number];
require(
msg.sender != _thisjob.writer,
"You Can't Co-Work with Yourself"
);
require(
_thisjob.stat != status.finish,
"This Job is Done. Job Good Job Bad Job"
);
require(!_thisjob.accepted, "Job In Progress");
require(
msg.value == _thisjob.dontdisturb,
"You Should Pay to show you are not scammer ( your money will payback after job is done )"
);
_thisjob.accepter = msg.sender;
_thisjob.accepted = true;
_thisjob.contact = _contact;
emit jobRefresh();
}
function workDone(uint256 _number) public {
require(
_number < job.length && _number >= 0,
"You Are Looking For A Wrong Job"
);
Job storage _thisjob = job[_number];
require(
msg.sender == _thisjob.accepter,
"You Are Not the Member of Job. Please Check your Wallet Address"
);
require(
_thisjob.stat != status.finish,
"This Job is Done. Job Good Job Bad Job"
);
if (_thisjob.stat == status.open) {
_thisjob.stat = status.workerDone;
}
else{
_thisjob.stat = status.open;
}
emit jobRefresh();
}
function finishJob(uint256 _number) public {
Job storage _thisjob = job[_number];
require(
_thisjob.stat == status.workerDone,
"Worker doesn't finised job or Already finished job"
);
require(
msg.sender == _thisjob.writer,
"Only Writer can finish the job"
);
_thisjob.stat = status.finish;
paying(_thisjob.accepter, (_thisjob.reward + _thisjob.dontdisturb));
emit jobRefresh();
}
function giveupJob(uint256 _number) public {
require(
_number < job.length && _number >= 0,
"You Are Looking For A Wrong Job"
);
Job storage _thisjob = job[_number];
require(
msg.sender == _thisjob.accepter,
"You Are Not the Member of Job. Please Check your Wallet Address"
);
require(
_thisjob.stat != status.finish,
"This Job is Done. Job Good Job Bad Job"
);
if (msg.sender == _thisjob.writer) {
require(
!_thisjob.accepted,
"You Can not Close Your Job while Someone is Working for you"
);
_thisjob.stat = status.finish;
paying(_thisjob.writer, _thisjob.reward);
} else {
require(
_thisjob.accepted,
"Job Is Not Started. So There is no way to give up"
);
_thisjob.accepted = false;
_thisjob.contact = "";
paying(_thisjob.accepter, _thisjob.dontdisturb);
_thisjob.accepter = _thisjob.writer;
}
emit jobRefresh();
}
function getPaginatedSquares(uint256 _page, uint256 _resultsPerPage)
public
view
returns (Job[] memory)
{
uint256 _jobIndex = _resultsPerPage * _page - _resultsPerPage;
if (job.length == 0 || _jobIndex > job.length - 1) {
return new Job[](0);
}
uint256 _size = _resultsPerPage;
if (_page * _resultsPerPage > job.length) {
_size = job.length % _resultsPerPage;
}
Job[] memory _jobs = new Job[](_size);
uint256 _returnCounter = 0;
for (_jobIndex; _jobIndex < _resultsPerPage * _page; _jobIndex++) {
if (_jobIndex < job.length) {
_jobs[_returnCounter] = job[_jobIndex];
} else {
break;
}
_returnCounter++;
}
return _jobs;
}
}
|
dontdisturb 단위는 ether
|
function publishJob(
string memory _title,
string memory _content,
uint256 _dontdisturb,
uint256 _deadline
) public payable {
require(msg.value >= postContract, "Job Reward is too cheap");
require(_dontdisturb >= DoNotDisturb, "DoNotDisturb is too cheap");
uint256 deadline = block.timestamp + _deadline;
Job memory newJob =
Job(
job.length,
msg.sender,
_title,
_content,
deadline,
msg.value,
_dontdisturb,
false,
msg.sender,
"",
status.open
);
job.push(newJob);
emit jobRefresh();
}
| 2,573,017
|
pragma solidity 0.5.10;
/**
* @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel)
* @title The interface for the market registry.
*/
interface IMarketRegistry {
// Emitted when a market is created
event MarketCreated(
uint256 index,
address indexed marketAddress,
address indexed vault,
address indexed creator
);
// Emitted when a deployer is added
event DeployerAdded(address deployer, string version);
// Emitted when a deployer is removed
event DeployerRemoved(address deployer, string reason);
/**
* @dev Adds a new market deployer to the registry.
* @param _newDeployer: Address of the new market deployer.
* @param _version: string - Log text for tracking purposes.
*/
function addMarketDeployer(
address _newDeployer,
string calldata _version
) external;
/**
* @dev Removes a market deployer from the registry.
* @param _deployerToRemove: Address of the market deployer to remove.
* @param _reason: Log text for tracking purposes.
*/
function removeMarketDeployer(
address _deployerToRemove,
string calldata _reason
) external;
/**
* @dev Logs the market into the registery.
* @param _vault: Address of the vault.
* @param _creator: Creator of the market.
* @return uint256: Returns the index of market for looking up.
*/
function registerMarket(
address _marketAddress,
address _vault,
address _creator
)
external
returns(uint256);
/**
* @dev Fetches all data and contract addresses of deployed
* markets by index, kept as interface for later
* intergration.
* @param _index: Index of the market.
* @return address: The address of the market.
* @return address: The address of the vault.
* @return address: The address of the creator.
*/
function getMarket(uint256 _index)
external
view
returns(
address,
address,
address
);
/**
* @dev Fetchs the current number of markets infering maximum
* callable index.
* @return uint256: The number of markets that have been deployed.
*/
function getIndex() external view returns(uint256);
/**
* @dev Used to check if the deployer is registered.
* @param _deployer: The address of the deployer
* @return bool: A simple bool to indicate state.
*/
function isMarketDeployer(address _deployer) external view returns(bool);
/**
* @dev In order to look up logs efficently, the published block is
* available.
* @return uint256: The block when the contract was published.
*/
function publishedBlocknumber() external view returns(uint256);
}
|
@veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) The interface for the market registry./ Emitted when a market is created Emitted when a deployer is added Emitted when a deployer is removed
|
interface IMarketRegistry {
event MarketCreated(
uint256 index,
address indexed marketAddress,
address indexed vault,
address indexed creator
);
event DeployerAdded(address deployer, string version);
event DeployerRemoved(address deployer, string reason);
function addMarketDeployer(
address _newDeployer,
string calldata _version
) external;
function removeMarketDeployer(
address _deployerToRemove,
string calldata _reason
) external;
function registerMarket(
address _marketAddress,
address _vault,
address _creator
)
external
returns(uint256);
function getMarket(uint256 _index)
external
view
returns(
address,
address,
address
);
function getIndex() external view returns(uint256);
function isMarketDeployer(address _deployer) external view returns(bool);
function publishedBlocknumber() external view returns(uint256);
}
| 12,635,410
|
/**
Source code of Opium Protocol
Web https://opium.network
Telegram https://t.me/opium_network
Twitter https://twitter.com/opium_network
*/
// File: LICENSE
/**
The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2020 Blockeys BV. All rights reserved.
Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works 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.
*/
// File: contracts/Lib/LibDerivative.sol
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
/// @title Opium.Lib.LibDerivative contract should be inherited by contracts that use Derivative structure and calculate derivativeHash
contract LibDerivative {
// Opium derivative structure (ticker) definition
struct Derivative {
// Margin parameter for syntheticId
uint256 margin;
// Maturity of derivative
uint256 endTime;
// Additional parameters for syntheticId
uint256[] params;
// oracleId of derivative
address oracleId;
// Margin token address of derivative
address token;
// syntheticId of derivative
address syntheticId;
}
/// @notice Calculates hash of provided Derivative
/// @param _derivative Derivative Instance of derivative to hash
/// @return derivativeHash bytes32 Derivative hash
function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) {
derivativeHash = keccak256(abi.encodePacked(
_derivative.margin,
_derivative.endTime,
_derivative.params,
_derivative.oracleId,
_derivative.token,
_derivative.syntheticId
));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
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);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
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;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @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");
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 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");
}
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
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.
*/
contract ReentrancyGuard {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// 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: erc721o/contracts/Libs/LibPosition.sol
pragma solidity ^0.5.4;
library LibPosition {
function getLongTokenId(bytes32 _hash) public pure returns (uint256 tokenId) {
tokenId = uint256(keccak256(abi.encodePacked(_hash, "LONG")));
}
function getShortTokenId(bytes32 _hash) public pure returns (uint256 tokenId) {
tokenId = uint256(keccak256(abi.encodePacked(_hash, "SHORT")));
}
}
// File: contracts/Interface/IDerivativeLogic.sol
pragma solidity 0.5.16;
/// @title Opium.Interface.IDerivativeLogic contract is an interface that every syntheticId should implement
contract IDerivativeLogic is LibDerivative {
/// @notice Validates ticker
/// @param _derivative Derivative Instance of derivative to validate
/// @return Returns boolean whether ticker is valid
function validateInput(Derivative memory _derivative) public view returns (bool);
/// @notice Calculates margin required for derivative creation
/// @param _derivative Derivative Instance of derivative
/// @return buyerMargin uint256 Margin needed from buyer (LONG position)
/// @return sellerMargin uint256 Margin needed from seller (SHORT position)
function getMargin(Derivative memory _derivative) public view returns (uint256 buyerMargin, uint256 sellerMargin);
/// @notice Calculates payout for derivative execution
/// @param _derivative Derivative Instance of derivative
/// @param _result uint256 Data retrieved from oracleId on the maturity
/// @return buyerPayout uint256 Payout in ratio for buyer (LONG position holder)
/// @return sellerPayout uint256 Payout in ratio for seller (SHORT position holder)
function getExecutionPayout(Derivative memory _derivative, uint256 _result) public view returns (uint256 buyerPayout, uint256 sellerPayout);
/// @notice Returns syntheticId author address for Opium commissions
/// @return authorAddress address The address of syntheticId address
function getAuthorAddress() public view returns (address authorAddress);
/// @notice Returns syntheticId author commission in base of COMMISSION_BASE
/// @return commission uint256 Author commission
function getAuthorCommission() public view returns (uint256 commission);
/// @notice Returns whether thirdparty could execute on derivative's owner's behalf
/// @param _derivativeOwner address Derivative owner address
/// @return Returns boolean whether _derivativeOwner allowed third party execution
function thirdpartyExecutionAllowed(address _derivativeOwner) public view returns (bool);
/// @notice Returns whether syntheticId implements pool logic
/// @return Returns whether syntheticId implements pool logic
function isPool() public view returns (bool);
/// @notice Sets whether thirds parties are allowed or not to execute derivative's on msg.sender's behalf
/// @param _allow bool Flag for execution allowance
function allowThirdpartyExecution(bool _allow) public;
// Event with syntheticId metadata JSON string (for DIB.ONE derivative explorer)
event MetadataSet(string metadata);
}
// File: contracts/Errors/CoreErrors.sol
pragma solidity 0.5.16;
contract CoreErrors {
string constant internal ERROR_CORE_NOT_POOL = "CORE:NOT_POOL";
string constant internal ERROR_CORE_CANT_BE_POOL = "CORE:CANT_BE_POOL";
string constant internal ERROR_CORE_TICKER_WAS_CANCELLED = "CORE:TICKER_WAS_CANCELLED";
string constant internal ERROR_CORE_SYNTHETIC_VALIDATION_ERROR = "CORE:SYNTHETIC_VALIDATION_ERROR";
string constant internal ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE = "CORE:NOT_ENOUGH_TOKEN_ALLOWANCE";
string constant internal ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH";
string constant internal ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH";
string constant internal ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED = "CORE:EXECUTION_BEFORE_MATURITY_NOT_ALLOWED";
string constant internal ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED = "CORE:SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED";
string constant internal ERROR_CORE_INSUFFICIENT_POOL_BALANCE = "CORE:INSUFFICIENT_POOL_BALANCE";
string constant internal ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID = "CORE:CANT_CANCEL_DUMMY_ORACLE_ID";
string constant internal ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED = "CORE:CANCELLATION_IS_NOT_ALLOWED";
string constant internal ERROR_CORE_UNKNOWN_POSITION_TYPE = "CORE:UNKNOWN_POSITION_TYPE";
}
// File: contracts/Errors/RegistryErrors.sol
pragma solidity 0.5.16;
contract RegistryErrors {
string constant internal ERROR_REGISTRY_ONLY_INITIALIZER = "REGISTRY:ONLY_INITIALIZER";
string constant internal ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED = "REGISTRY:ONLY_OPIUM_ADDRESS_ALLOWED";
string constant internal ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS = "REGISTRY:CANT_BE_ZERO_ADDRESS";
string constant internal ERROR_REGISTRY_ALREADY_SET = "REGISTRY:ALREADY_SET";
}
// File: contracts/Registry.sol
pragma solidity 0.5.16;
/// @title Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other
contract Registry is RegistryErrors {
// Address of Opium.TokenMinter contract
address private minter;
// Address of Opium.Core contract
address private core;
// Address of Opium.OracleAggregator contract
address private oracleAggregator;
// Address of Opium.SyntheticAggregator contract
address private syntheticAggregator;
// Address of Opium.TokenSpender contract
address private tokenSpender;
// Address of Opium commission receiver
address private opiumAddress;
// Address of Opium contract set deployer
address public initializer;
/// @notice This modifier restricts access to functions, which could be called only by initializer
modifier onlyInitializer() {
require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER);
_;
}
/// @notice Sets initializer
constructor() public {
initializer = msg.sender;
}
// SETTERS
/// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once
/// @param _minter address Address of Opium.TokenMinter
/// @param _core address Address of Opium.Core
/// @param _oracleAggregator address Address of Opium.OracleAggregator
/// @param _syntheticAggregator address Address of Opium.SyntheticAggregator
/// @param _tokenSpender address Address of Opium.TokenSpender
/// @param _opiumAddress address Address of Opium commission receiver
function init(
address _minter,
address _core,
address _oracleAggregator,
address _syntheticAggregator,
address _tokenSpender,
address _opiumAddress
) external onlyInitializer {
require(
minter == address(0) &&
core == address(0) &&
oracleAggregator == address(0) &&
syntheticAggregator == address(0) &&
tokenSpender == address(0) &&
opiumAddress == address(0),
ERROR_REGISTRY_ALREADY_SET
);
require(
_minter != address(0) &&
_core != address(0) &&
_oracleAggregator != address(0) &&
_syntheticAggregator != address(0) &&
_tokenSpender != address(0) &&
_opiumAddress != address(0),
ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS
);
minter = _minter;
core = _core;
oracleAggregator = _oracleAggregator;
syntheticAggregator = _syntheticAggregator;
tokenSpender = _tokenSpender;
opiumAddress = _opiumAddress;
}
/// @notice Allows opium commission receiver address to change itself
/// @param _opiumAddress address New opium commission receiver address
function changeOpiumAddress(address _opiumAddress) external {
require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED);
require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS);
opiumAddress = _opiumAddress;
}
// GETTERS
/// @notice Returns address of Opium.TokenMinter
/// @param result address Address of Opium.TokenMinter
function getMinter() external view returns (address result) {
return minter;
}
/// @notice Returns address of Opium.Core
/// @param result address Address of Opium.Core
function getCore() external view returns (address result) {
return core;
}
/// @notice Returns address of Opium.OracleAggregator
/// @param result address Address of Opium.OracleAggregator
function getOracleAggregator() external view returns (address result) {
return oracleAggregator;
}
/// @notice Returns address of Opium.SyntheticAggregator
/// @param result address Address of Opium.SyntheticAggregator
function getSyntheticAggregator() external view returns (address result) {
return syntheticAggregator;
}
/// @notice Returns address of Opium.TokenSpender
/// @param result address Address of Opium.TokenSpender
function getTokenSpender() external view returns (address result) {
return tokenSpender;
}
/// @notice Returns address of Opium commission receiver
/// @param result address Address of Opium commission receiver
function getOpiumAddress() external view returns (address result) {
return opiumAddress;
}
}
// File: contracts/Errors/UsingRegistryErrors.sol
pragma solidity 0.5.16;
contract UsingRegistryErrors {
string constant internal ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED = "USING_REGISTRY:ONLY_CORE_ALLOWED";
}
// File: contracts/Lib/UsingRegistry.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.UsingRegistry contract should be inherited by contracts, that are going to use Opium.Registry
contract UsingRegistry is UsingRegistryErrors {
// Emitted when registry instance is set
event RegistrySet(address registry);
// Instance of Opium.Registry contract
Registry internal registry;
/// @notice This modifier restricts access to functions, which could be called only by Opium.Core
modifier onlyCore() {
require(msg.sender == registry.getCore(), ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED);
_;
}
/// @notice Defines registry instance and emits appropriate event
constructor(address _registry) public {
registry = Registry(_registry);
emit RegistrySet(_registry);
}
/// @notice Getter for registry variable
/// @return address Address of registry set in current contract
function getRegistry() external view returns (address) {
return address(registry);
}
}
// File: contracts/Lib/LibCommission.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.LibCommission contract defines constants for Opium commissions
contract LibCommission {
// Represents 100% base for commissions calculation
uint256 constant public COMMISSION_BASE = 10000;
// Represents 100% base for Opium commission
uint256 constant public OPIUM_COMMISSION_BASE = 10;
// Represents which part of `syntheticId` author commissions goes to opium
uint256 constant public OPIUM_COMMISSION_PART = 1;
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// File: erc721o/contracts/Libs/UintArray.sol
pragma solidity ^0.5.4;
library UintArray {
function indexOf(uint256[] memory A, uint256 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 (0, false);
}
function contains(uint256[] memory A, uint256 a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
function difference(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 count = 0;
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) {
uint256 e = A[i];
if (!contains(B, e)) {
includeMap[i] = true;
count++;
}
}
uint256[] memory newUints = new uint256[](count);
uint256[] memory newUintsIdxs = new uint256[](count);
uint256 j = 0;
for (uint256 i = 0; i < length; i++) {
if (includeMap[i]) {
newUints[j] = A[i];
newUintsIdxs[j] = i;
j++;
}
}
return (newUints, newUintsIdxs);
}
function intersect(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory, uint256[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 newLength = 0;
for (uint256 i = 0; i < length; i++) {
if (contains(B, A[i])) {
includeMap[i] = true;
newLength++;
}
}
uint256[] memory newUints = new uint256[](newLength);
uint256[] memory newUintsAIdxs = new uint256[](newLength);
uint256[] memory newUintsBIdxs = new uint256[](newLength);
uint256 j = 0;
for (uint256 i = 0; i < length; i++) {
if (includeMap[i]) {
newUints[j] = A[i];
newUintsAIdxs[j] = i;
(newUintsBIdxs[j], ) = indexOf(B, A[i]);
j++;
}
}
return (newUints, newUintsAIdxs, newUintsBIdxs);
}
function isUnique(uint256[] memory A) internal pure returns (bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
(uint256 idx, bool isIn) = indexOf(A, A[i]);
if (isIn && idx < i) {
return false;
}
}
return true;
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
pragma solidity ^0.5.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-solidity/contracts/introspection/ERC165.sol
pragma solidity ^0.5.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) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.5.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: erc721o/contracts/Interfaces/IERC721O.sol
pragma solidity ^0.5.4;
contract IERC721O {
// Token description
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() public view returns (uint256);
function exists(uint256 _tokenId) public view returns (bool);
function implementsERC721() public pure returns (bool);
function tokenByIndex(uint256 _index) public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri);
function getApproved(uint256 _tokenId) public view returns (address);
function implementsERC721O() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function balanceOf(address owner) public view returns (uint256);
function balanceOf(address _owner, uint256 _tokenId) public view returns (uint256);
function tokensOwned(address _owner) public view returns (uint256[] memory, uint256[] memory);
// Non-Fungible Safe Transfer From
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public;
// Non-Fungible Unsafe Transfer From
function transferFrom(address _from, address _to, uint256 _tokenId) public;
// Fungible Unsafe Transfer
function transfer(address _to, uint256 _tokenId, uint256 _quantity) public;
// Fungible Unsafe Transfer From
function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _quantity) public;
// Fungible Safe Transfer From
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public;
// Fungible Safe Batch Transfer From
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public;
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data) public;
// Fungible Unsafe Batch Transfer From
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public;
// Approvals
function setApprovalForAll(address _operator, bool _approved) public;
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address);
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator);
function isApprovedOrOwner(address _spender, address _owner, uint256 _tokenId) public view returns (bool);
function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external;
// Composable
function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public;
function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public;
function recompose(uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity) public;
// Required Events
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts);
event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio);
}
// File: erc721o/contracts/Interfaces/IERC721OReceiver.sol
pragma solidity ^0.5.4;
/**
* @title ERC721O token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721O contracts.
*/
contract IERC721OReceiver {
/**
* @dev Magic value to be returned upon successful reception of an amount of ERC721O tokens
* ERC721O_RECEIVED = `bytes4(keccak256("onERC721OReceived(address,address,uint256,uint256,bytes)"))` = 0xf891ffe0
* ERC721O_BATCH_RECEIVED = `bytes4(keccak256("onERC721OBatchReceived(address,address,uint256[],uint256[],bytes)"))` = 0xd0e17c0b
*/
bytes4 constant internal ERC721O_RECEIVED = 0xf891ffe0;
bytes4 constant internal ERC721O_BATCH_RECEIVED = 0xd0e17c0b;
function onERC721OReceived(
address _operator,
address _from,
uint256 tokenId,
uint256 amount,
bytes memory data
) public returns(bytes4);
function onERC721OBatchReceived(
address _operator,
address _from,
uint256[] memory _types,
uint256[] memory _amounts,
bytes memory _data
) public returns (bytes4);
}
// File: erc721o/contracts/Libs/ObjectsLib.sol
pragma solidity ^0.5.4;
library ObjectLib {
// Libraries
using SafeMath for uint256;
enum Operations { ADD, SUB, REPLACE }
// Constants regarding bin or chunk sizes for balance packing
uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object
uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256
//
// Objects and Tokens Functions
//
/**
* @dev Return the bin number and index within that bin where ID is
* @param _tokenId Object type
* @return (Bin number, ID's index within that bin)
*/
function getTokenBinIndex(uint256 _tokenId) internal pure returns (uint256 bin, uint256 index) {
bin = _tokenId * TYPES_BITS_SIZE / 256;
index = _tokenId % TYPES_PER_UINT256;
return (bin, index);
}
/**
* @dev update the balance of a type provided in _binBalances
* @param _binBalances Uint256 containing the balances of objects
* @param _index Index of the object in the provided bin
* @param _amount Value to update the type balance
* @param _operation Which operation to conduct :
* Operations.REPLACE : Replace type balance with _amount
* Operations.ADD : ADD _amount to type balance
* Operations.SUB : Substract _amount from type balance
*/
function updateTokenBalance(
uint256 _binBalances,
uint256 _index,
uint256 _amount,
Operations _operation) internal pure returns (uint256 newBinBalance)
{
uint256 objectBalance;
if (_operation == Operations.ADD) {
objectBalance = getValueInBin(_binBalances, _index);
newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount));
} else if (_operation == Operations.SUB) {
objectBalance = getValueInBin(_binBalances, _index);
newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount));
} else if (_operation == Operations.REPLACE) {
newBinBalance = writeValueInBin(_binBalances, _index, _amount);
} else {
revert("Invalid operation"); // Bad operation
}
return newBinBalance;
}
/*
* @dev return value in _binValue at position _index
* @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types
* @param _index index at which to retrieve value
* @return Value at given _index in _bin
*/
function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) {
// Mask to retrieve data for a given binData
uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;
// Shift amount
uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1);
return (_binValue >> rightShift) & mask;
}
/**
* @dev return the updated _binValue after writing _amount at _index
* @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types
* @param _index Index at which to retrieve value
* @param _amount Value to store at _index in _bin
* @return Value at given _index in _bin
*/
function writeValueInBin(uint256 _binValue, uint256 _index, uint256 _amount) internal pure returns (uint256) {
require(_amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large");
// Mask to retrieve data for a given binData
uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;
// Shift amount
uint256 leftShift = 256 - TYPES_BITS_SIZE * (_index + 1);
return (_binValue & ~(mask << leftShift) ) | (_amount << leftShift);
}
}
// File: erc721o/contracts/ERC721OBase.sol
pragma solidity ^0.5.4;
contract ERC721OBase is IERC721O, ERC165, IERC721 {
// Libraries
using ObjectLib for ObjectLib.Operations;
using ObjectLib for uint256;
// Array with all tokenIds
uint256[] internal allTokens;
// Packed balances
mapping(address => mapping(uint256 => uint256)) internal packedTokenBalance;
// Operators
mapping(address => mapping(address => bool)) internal operators;
// Keeps aprovals for tokens from owner to approved address
// tokenApprovals[tokenId][owner] = approved
mapping (uint256 => mapping (address => address)) internal tokenApprovals;
// Token Id state
mapping(uint256 => uint256) internal tokenTypes;
uint256 constant internal INVALID = 0;
uint256 constant internal POSITION = 1;
uint256 constant internal PORTFOLIO = 2;
// Interface constants
bytes4 internal constant INTERFACE_ID_ERC721O = 0x12345678;
// EIP712 constants
bytes32 public DOMAIN_SEPARATOR;
bytes32 public PERMIT_TYPEHASH;
// mapping holds nonces for approval permissions
// nonces[holder] => nonce
mapping (address => uint) public nonces;
modifier isOperatorOrOwner(address _from) {
require((msg.sender == _from) || operators[_from][msg.sender], "msg.sender is neither _from nor operator");
_;
}
constructor() public {
_registerInterface(INTERFACE_ID_ERC721O);
// Calculate EIP712 constants
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,address verifyingContract)"),
keccak256(bytes("ERC721o")),
keccak256(bytes("1")),
address(this)
));
PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
}
function implementsERC721O() public pure returns (bool) {
return true;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
return tokenTypes[_tokenId] != INVALID;
}
/**
* @dev return the _tokenId type' balance of _address
* @param _address Address to query balance of
* @param _tokenId type to query balance of
* @return Amount of objects of a given type ID
*/
function balanceOf(address _address, uint256 _tokenId) public view returns (uint256) {
(uint256 bin, uint256 index) = _tokenId.getTokenBinIndex();
return packedTokenBalance[_address][bin].getValueInBin(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 Iterate through the list of existing tokens and return the indexes
* and balances of the tokens owner by the user
* @param _owner The adddress we are checking
* @return indexes The tokenIds
* @return balances The balances of each token
*/
function tokensOwned(address _owner) public view returns (uint256[] memory indexes, uint256[] memory balances) {
uint256 numTokens = totalSupply();
uint256[] memory tokenIndexes = new uint256[](numTokens);
uint256[] memory tempTokens = new uint256[](numTokens);
uint256 count;
for (uint256 i = 0; i < numTokens; i++) {
uint256 tokenId = allTokens[i];
if (balanceOf(_owner, tokenId) > 0) {
tempTokens[count] = balanceOf(_owner, tokenId);
tokenIndexes[count] = tokenId;
count++;
}
}
// copy over the data to a correct size array
uint256[] memory _ownedTokens = new uint256[](count);
uint256[] memory _ownedTokensIndexes = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
_ownedTokens[i] = tempTokens[i];
_ownedTokensIndexes[i] = tokenIndexes[i];
}
return (_ownedTokensIndexes, _ownedTokens);
}
/**
* @dev Will set _operator operator status to true or false
* @param _operator Address to changes operator status.
* @param _approved _operator's new operator status (true or false)
*/
function setApprovalForAll(address _operator, bool _approved) public {
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Approve for all by signature
function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external {
// Calculate hash
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(
PERMIT_TYPEHASH,
_holder,
_spender,
_nonce,
_expiry,
_allowed
))
));
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
bytes32 r;
bytes32 s;
uint8 v;
bytes memory signature = _signature;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
address recoveredAddress;
// If the version is correct return the signer address
if (v != 27 && v != 28) {
recoveredAddress = address(0);
} else {
// solium-disable-next-line arg-overflow
recoveredAddress = ecrecover(digest, v, r, s);
}
require(_holder != address(0), "Holder can't be zero address");
require(_holder == recoveredAddress, "Signer address is invalid");
require(_expiry == 0 || now <= _expiry, "Permission expired");
require(_nonce == nonces[_holder]++, "Nonce is invalid");
// Update operator status
operators[_holder][_spender] = _allowed;
emit ApprovalForAll(_holder, _spender, _allowed);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* 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 {
require(_to != msg.sender, "Can't approve to yourself");
tokenApprovals[_tokenId][msg.sender] = _to;
emit Approval(msg.sender, _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 the given token ID
*/
function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address) {
return tokenApprovals[_tokenId][_tokenOwner];
}
/**
* @dev Function that verifies whether _operator is an authorized operator of _tokenHolder.
* @param _operator The address of the operator to query status of
* @param _owner Address of the tokenHolder
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) {
return operators[_owner][_operator];
}
function isApprovedOrOwner(
address _spender,
address _owner,
uint256 _tokenId
) public view returns (bool) {
return (
_spender == _owner ||
getApproved(_tokenId, _owner) == _spender ||
isApprovedForAll(_owner, _spender)
);
}
function _updateTokenBalance(
address _from,
uint256 _tokenId,
uint256 _amount,
ObjectLib.Operations op
) internal {
(uint256 bin, uint256 index) = _tokenId.getTokenBinIndex();
packedTokenBalance[_from][bin] = packedTokenBalance[_from][bin].updateTokenBalance(
index, _amount, op
);
}
}
// File: erc721o/contracts/ERC721OTransferable.sol
pragma solidity ^0.5.4;
contract ERC721OTransferable is ERC721OBase, ReentrancyGuard {
// Libraries
using Address for address;
// safeTransfer constants
bytes4 internal constant ERC721O_RECEIVED = 0xf891ffe0;
bytes4 internal constant ERC721O_BATCH_RECEIVED = 0xd0e17c0b;
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public {
// Batch Transfering
_batchTransferFrom(_from, _to, _tokenIds, _amounts);
}
/**
* @dev transfer objects from different tokenIds to specified address
* @param _from The address to BatchTransfer objects from.
* @param _to The address to batchTransfer objects to.
* @param _tokenIds Array of tokenIds to update balance of
* @param _amounts Array of amount of object per type to be transferred.
* @param _data Data to pass to onERC721OReceived() function if recipient is contract
* Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient).
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes memory _data
) public nonReentrant {
// Batch Transfering
_batchTransferFrom(_from, _to, _tokenIds, _amounts);
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC721OReceiver(_to).onERC721OBatchReceived(
msg.sender, _from, _tokenIds, _amounts, _data
);
require(retval == ERC721O_BATCH_RECEIVED);
}
}
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts
) public {
safeBatchTransferFrom(_from, _to, _tokenIds, _amounts, "");
}
function transfer(address _to, uint256 _tokenId, uint256 _amount) public {
_transferFrom(msg.sender, _to, _tokenId, _amount);
}
function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public {
_transferFrom(_from, _to, _tokenId, _amount);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public {
safeTransferFrom(_from, _to, _tokenId, _amount, "");
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public nonReentrant {
_transferFrom(_from, _to, _tokenId, _amount);
require(
_checkAndCallSafeTransfer(_from, _to, _tokenId, _amount, _data),
"Sent to a contract which is not an ERC721O receiver"
);
}
/**
* @dev transfer objects from different tokenIds to specified address
* @param _from The address to BatchTransfer objects from.
* @param _to The address to batchTransfer objects to.
* @param _tokenIds Array of tokenIds to update balance of
* @param _amounts Array of amount of object per type to be transferred.
* Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient).
*/
function _batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts
) internal isOperatorOrOwner(_from) {
// Requirements
require(_tokenIds.length == _amounts.length, "Inconsistent array length between args");
require(_to != address(0), "Invalid to address");
// Number of transfers to execute
uint256 nTransfer = _tokenIds.length;
// Don't do useless calculations
if (_from == _to) {
for (uint256 i = 0; i < nTransfer; i++) {
emit Transfer(_from, _to, _tokenIds[i]);
emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]);
}
return;
}
for (uint256 i = 0; i < nTransfer; i++) {
require(_amounts[i] <= balanceOf(_from, _tokenIds[i]), "Quantity greater than from balance");
_updateTokenBalance(_from, _tokenIds[i], _amounts[i], ObjectLib.Operations.SUB);
_updateTokenBalance(_to, _tokenIds[i], _amounts[i], ObjectLib.Operations.ADD);
emit Transfer(_from, _to, _tokenIds[i]);
emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]);
}
// Emit batchTransfer event
emit BatchTransfer(_from, _to, _tokenIds, _amounts);
}
function _transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) internal {
require(isApprovedOrOwner(msg.sender, _from, _tokenId), "Not approved");
require(_amount <= balanceOf(_from, _tokenId), "Quantity greater than from balance");
require(_to != address(0), "Invalid to address");
_updateTokenBalance(_from, _tokenId, _amount, ObjectLib.Operations.SUB);
_updateTokenBalance(_to, _tokenId, _amount, ObjectLib.Operations.ADD);
emit Transfer(_from, _to, _tokenId);
emit TransferWithQuantity(_from, _to, _tokenId, _amount);
}
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes memory _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes4 retval = IERC721OReceiver(_to).onERC721OReceived(msg.sender, _from, _tokenId, _amount, _data);
return(retval == ERC721O_RECEIVED);
}
}
// File: erc721o/contracts/ERC721OMintable.sol
pragma solidity ^0.5.4;
contract ERC721OMintable is ERC721OTransferable {
// Libraries
using LibPosition for bytes32;
// Internal functions
function _mint(uint256 _tokenId, address _to, uint256 _supply) internal {
// If the token doesn't exist, add it to the tokens array
if (!exists(_tokenId)) {
tokenTypes[_tokenId] = POSITION;
allTokens.push(_tokenId);
}
_updateTokenBalance(_to, _tokenId, _supply, ObjectLib.Operations.ADD);
emit Transfer(address(0), _to, _tokenId);
emit TransferWithQuantity(address(0), _to, _tokenId, _supply);
}
function _burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) internal {
uint256 ownerBalance = balanceOf(_tokenOwner, _tokenId);
require(ownerBalance >= _quantity, "TOKEN_MINTER:NOT_ENOUGH_POSITIONS");
_updateTokenBalance(_tokenOwner, _tokenId, _quantity, ObjectLib.Operations.SUB);
emit Transfer(_tokenOwner, address(0), _tokenId);
emit TransferWithQuantity(_tokenOwner, address(0), _tokenId, _quantity);
}
function _mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) internal {
_mintLong(_buyer, _derivativeHash, _quantity);
_mintShort(_seller, _derivativeHash, _quantity);
}
function _mintLong(address _buyer, bytes32 _derivativeHash, uint256 _quantity) internal {
uint256 longTokenId = _derivativeHash.getLongTokenId();
_mint(longTokenId, _buyer, _quantity);
}
function _mintShort(address _seller, bytes32 _derivativeHash, uint256 _quantity) internal {
uint256 shortTokenId = _derivativeHash.getShortTokenId();
_mint(shortTokenId, _seller, _quantity);
}
function _registerPortfolio(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio) internal {
if (!exists(_portfolioId)) {
tokenTypes[_portfolioId] = PORTFOLIO;
emit Composition(_portfolioId, _tokenIds, _tokenRatio);
}
}
}
// File: erc721o/contracts/ERC721OComposable.sol
pragma solidity ^0.5.4;
contract ERC721OComposable is ERC721OMintable {
// Libraries
using UintArray for uint256[];
using SafeMath for uint256;
function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public {
require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
for (uint256 i = 0; i < _tokenIds.length; i++) {
_burn(msg.sender, _tokenIds[i], _tokenRatio[i].mul(_quantity));
}
uint256 portfolioId = uint256(keccak256(abi.encodePacked(
_tokenIds,
_tokenRatio
)));
_registerPortfolio(portfolioId, _tokenIds, _tokenRatio);
_mint(portfolioId, msg.sender, _quantity);
}
function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public {
require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
uint256 portfolioId = uint256(keccak256(abi.encodePacked(
_tokenIds,
_tokenRatio
)));
require(portfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID");
_burn(msg.sender, _portfolioId, _quantity);
for (uint256 i = 0; i < _tokenIds.length; i++) {
_mint(_tokenIds[i], msg.sender, _tokenRatio[i].mul(_quantity));
}
}
function recompose(
uint256 _portfolioId,
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) public {
require(_initialTokenIds.length == _initialTokenRatio.length, "TOKEN_MINTER:INITIAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_finalTokenIds.length == _finalTokenRatio.length, "TOKEN_MINTER:FINAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_initialTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_finalTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_initialTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
require(_finalTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
uint256 oldPortfolioId = uint256(keccak256(abi.encodePacked(
_initialTokenIds,
_initialTokenRatio
)));
require(oldPortfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID");
_burn(msg.sender, _portfolioId, _quantity);
_removedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity);
_addedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity);
_keptIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity);
uint256 newPortfolioId = uint256(keccak256(abi.encodePacked(
_finalTokenIds,
_finalTokenRatio
)));
_registerPortfolio(newPortfolioId, _finalTokenIds, _finalTokenRatio);
_mint(newPortfolioId, msg.sender, _quantity);
}
function _removedIds(
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) private {
(uint256[] memory removedIds, uint256[] memory removedIdsIdxs) = _initialTokenIds.difference(_finalTokenIds);
for (uint256 i = 0; i < removedIds.length; i++) {
uint256 index = removedIdsIdxs[i];
_mint(_initialTokenIds[index], msg.sender, _initialTokenRatio[index].mul(_quantity));
}
_finalTokenRatio;
}
function _addedIds(
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) private {
(uint256[] memory addedIds, uint256[] memory addedIdsIdxs) = _finalTokenIds.difference(_initialTokenIds);
for (uint256 i = 0; i < addedIds.length; i++) {
uint256 index = addedIdsIdxs[i];
_burn(msg.sender, _finalTokenIds[index], _finalTokenRatio[index].mul(_quantity));
}
_initialTokenRatio;
}
function _keptIds(
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) private {
(uint256[] memory keptIds, uint256[] memory keptInitialIdxs, uint256[] memory keptFinalIdxs) = _initialTokenIds.intersect(_finalTokenIds);
for (uint256 i = 0; i < keptIds.length; i++) {
uint256 initialIndex = keptInitialIdxs[i];
uint256 finalIndex = keptFinalIdxs[i];
if (_initialTokenRatio[initialIndex] > _finalTokenRatio[finalIndex]) {
uint256 diff = _initialTokenRatio[initialIndex] - _finalTokenRatio[finalIndex];
_mint(_initialTokenIds[initialIndex], msg.sender, diff.mul(_quantity));
} else if (_initialTokenRatio[initialIndex] < _finalTokenRatio[finalIndex]) {
uint256 diff = _finalTokenRatio[finalIndex] - _initialTokenRatio[initialIndex];
_burn(msg.sender, _initialTokenIds[initialIndex], diff.mul(_quantity));
}
}
}
}
// File: erc721o/contracts/Libs/UintsLib.sol
pragma solidity ^0.5.4;
library UintsLib {
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
// File: erc721o/contracts/ERC721OBackwardCompatible.sol
pragma solidity ^0.5.4;
contract ERC721OBackwardCompatible is ERC721OComposable {
using UintsLib for uint256;
// Interface constants
bytes4 internal constant INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 internal constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 internal constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
// Reciever constants
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
// Metadata URI
string internal baseTokenURI;
constructor(string memory _baseTokenURI) public ERC721OBase() {
baseTokenURI = _baseTokenURI;
_registerInterface(INTERFACE_ID_ERC721);
_registerInterface(INTERFACE_ID_ERC721_ENUMERABLE);
_registerInterface(INTERFACE_ID_ERC721_METADATA);
}
// ERC721 compatibility
function implementsERC721() public pure returns (bool) {
return true;
}
/**
* @dev Gets the owner of a given NFT
* @param _tokenId uint256 representing the unique token identifier
* @return address the owner of the token
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
if (exists(_tokenId)) {
return address(this);
}
return address(0);
}
/**
* @dev Gets the number of tokens owned by the address we are checking
* @param _owner The adddress we are checking
* @return balance The unique amount of tokens owned
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
(, uint256[] memory tokens) = tokensOwned(_owner);
return tokens.length;
}
// ERC721 - Enumerable compatibility
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* 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];
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) {
(, uint256[] memory tokens) = tokensOwned(_owner);
require(_index < tokens.length);
return tokens[_index];
}
// ERC721 - Metadata compatibility
function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri) {
require(exists(_tokenId), "Token doesn't exist");
return string(abi.encodePacked(
baseTokenURI,
_tokenId.uint2str(),
".json"
));
}
/**
* @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 the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
if (exists(_tokenId)) {
return address(this);
}
return address(0);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public nonReentrant {
_transferFrom(_from, _to, _tokenId, 1);
require(
_checkAndCallSafeTransfer(_from, _to, _tokenId, _data),
"Sent to a contract which is not an ERC721 receiver"
);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public {
_transferFrom(_from, _to, _tokenId, 1);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data
);
return (retval == ERC721_RECEIVED);
}
}
// File: contracts/TokenMinter.sol
pragma solidity 0.5.16;
/// @title Opium.TokenMinter contract implements ERC721O token standard for minting, burning and transferring position tokens
contract TokenMinter is ERC721OBackwardCompatible, UsingRegistry {
/// @notice Calls constructors of super-contracts
/// @param _baseTokenURI string URI for token explorers
/// @param _registry address Address of Opium.registry
constructor(string memory _baseTokenURI, address _registry) public ERC721OBackwardCompatible(_baseTokenURI) UsingRegistry(_registry) {}
/// @notice Mints LONG and SHORT position tokens
/// @param _buyer address Address of LONG position receiver
/// @param _seller address Address of SHORT position receiver
/// @param _derivativeHash bytes32 Hash of derivative (ticker) of position
/// @param _quantity uint256 Quantity of positions to mint
function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore {
_mint(_buyer, _seller, _derivativeHash, _quantity);
}
/// @notice Mints only LONG position tokens for "pooled" derivatives
/// @param _buyer address Address of LONG position receiver
/// @param _derivativeHash bytes32 Hash of derivative (ticker) of position
/// @param _quantity uint256 Quantity of positions to mint
function mint(address _buyer, bytes32 _derivativeHash, uint256 _quantity) external onlyCore {
_mintLong(_buyer, _derivativeHash, _quantity);
}
/// @notice Burns position tokens
/// @param _tokenOwner address Address of tokens owner
/// @param _tokenId uint256 tokenId of positions to burn
/// @param _quantity uint256 Quantity of positions to burn
function burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) external onlyCore {
_burn(_tokenOwner, _tokenId, _quantity);
}
/// @notice ERC721 interface compatible function for position token name retrieving
/// @return Returns name of token
function name() external view returns (string memory) {
return "Opium Network Position Token";
}
/// @notice ERC721 interface compatible function for position token symbol retrieving
/// @return Returns symbol of token
function symbol() external view returns (string memory) {
return "ONP";
}
/// VIEW FUNCTIONS
/// @notice Checks whether _spender is approved to spend tokens on _owners behalf or owner itself
/// @param _spender address Address of spender
/// @param _owner address Address of owner
/// @param _tokenId address tokenId of interest
/// @return Returns whether _spender is approved to spend tokens
function isApprovedOrOwner(
address _spender,
address _owner,
uint256 _tokenId
) public view returns (bool) {
return (
_spender == _owner ||
getApproved(_tokenId, _owner) == _spender ||
isApprovedForAll(_owner, _spender) ||
isOpiumSpender(_spender)
);
}
/// @notice Checks whether _spender is Opium.TokenSpender
/// @return Returns whether _spender is Opium.TokenSpender
function isOpiumSpender(address _spender) public view returns (bool) {
return _spender == registry.getTokenSpender();
}
}
// File: contracts/Errors/OracleAggregatorErrors.sol
pragma solidity 0.5.16;
contract OracleAggregatorErrors {
string constant internal ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER = "ORACLE_AGGREGATOR:NOT_ENOUGH_ETHER";
string constant internal ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE = "ORACLE_AGGREGATOR:QUERY_WAS_ALREADY_MADE";
string constant internal ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST = "ORACLE_AGGREGATOR:DATA_DOESNT_EXIST";
string constant internal ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST = "ORACLE_AGGREGATOR:DATA_ALREADY_EXIST";
}
// File: contracts/Interface/IOracleId.sol
pragma solidity 0.5.16;
/// @title Opium.Interface.IOracleId contract is an interface that every oracleId should implement
interface IOracleId {
/// @notice Requests data from `oracleId` one time
/// @param timestamp uint256 Timestamp at which data are needed
function fetchData(uint256 timestamp) external payable;
/// @notice Requests data from `oracleId` multiple times
/// @param timestamp uint256 Timestamp at which data are needed for the first time
/// @param period uint256 Period in seconds between multiple timestamps
/// @param times uint256 How many timestamps are requested
function recursivelyFetchData(uint256 timestamp, uint256 period, uint256 times) external payable;
/// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view.
/// @return fetchPrice uint256 Price of one data request in ETH
function calculateFetchPrice() external returns (uint256 fetchPrice);
// Event with oracleId metadata JSON string (for DIB.ONE derivative explorer)
event MetadataSet(string metadata);
}
// File: contracts/OracleAggregator.sol
pragma solidity 0.5.16;
/// @title Opium.OracleAggregator contract requests and caches the data from `oracleId`s and provides them to the Core for positions execution
contract OracleAggregator is OracleAggregatorErrors, ReentrancyGuard {
using SafeMath for uint256;
// Storage for the `oracleId` results
// dataCache[oracleId][timestamp] => data
mapping (address => mapping(uint256 => uint256)) public dataCache;
// Flags whether data were provided
// dataExist[oracleId][timestamp] => bool
mapping (address => mapping(uint256 => bool)) public dataExist;
// Flags whether data were requested
// dataRequested[oracleId][timestamp] => bool
mapping (address => mapping(uint256 => bool)) public dataRequested;
// MODIFIERS
/// @notice Checks whether enough ETH were provided withing data request to proceed
/// @param oracleId address Address of the `oracleId` smart contract
/// @param times uint256 How many times the `oracleId` is being requested
modifier enoughEtherProvided(address oracleId, uint256 times) {
// Calling Opium.IOracleId function to get the data fetch price per one request
uint256 oneTimePrice = calculateFetchPrice(oracleId);
// Checking if enough ether was provided for `times` amount of requests
require(msg.value >= oneTimePrice.mul(times), ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER);
_;
}
// PUBLIC FUNCTIONS
/// @notice Requests data from `oracleId` one time
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data are needed
function fetchData(address oracleId, uint256 timestamp) public payable nonReentrant enoughEtherProvided(oracleId, 1) {
// Check if was not requested before and mark as requested
_registerQuery(oracleId, timestamp);
// Call the `oracleId` contract and transfer ETH
IOracleId(oracleId).fetchData.value(msg.value)(timestamp);
}
/// @notice Requests data from `oracleId` multiple times
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data are needed for the first time
/// @param period uint256 Period in seconds between multiple timestamps
/// @param times uint256 How many timestamps are requested
function recursivelyFetchData(address oracleId, uint256 timestamp, uint256 period, uint256 times) public payable nonReentrant enoughEtherProvided(oracleId, times) {
// Check if was not requested before and mark as requested in loop for each timestamp
for (uint256 i = 0; i < times; i++) {
_registerQuery(oracleId, timestamp + period * i);
}
// Call the `oracleId` contract and transfer ETH
IOracleId(oracleId).recursivelyFetchData.value(msg.value)(timestamp, period, times);
}
/// @notice Receives and caches data from `msg.sender`
/// @param timestamp uint256 Timestamp of data
/// @param data uint256 Data itself
function __callback(uint256 timestamp, uint256 data) public {
// Don't allow to push data twice
require(!dataExist[msg.sender][timestamp], ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST);
// Saving data
dataCache[msg.sender][timestamp] = data;
// Flagging that data were received
dataExist[msg.sender][timestamp] = true;
}
/// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view.
/// @param oracleId address Address of the `oracleId` smart contract
/// @return fetchPrice uint256 Price of one data request in ETH
function calculateFetchPrice(address oracleId) public returns(uint256 fetchPrice) {
fetchPrice = IOracleId(oracleId).calculateFetchPrice();
}
// PRIVATE FUNCTIONS
/// @notice Checks if data was not requested and provided before and marks as requested
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data are requested
function _registerQuery(address oracleId, uint256 timestamp) private {
// Check if data was not requested and provided yet
require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE);
// Mark as requested
dataRequested[oracleId][timestamp] = true;
}
// VIEW FUNCTIONS
/// @notice Returns cached data if they exist, or reverts with an error
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data were requested
/// @return dataResult uint256 Cached data provided by `oracleId`
function getData(address oracleId, uint256 timestamp) public view returns(uint256 dataResult) {
// Check if Opium.OracleAggregator has data
require(hasData(oracleId, timestamp), ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST);
// Return cached data
dataResult = dataCache[oracleId][timestamp];
}
/// @notice Getter for dataExist mapping
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data were requested
/// @param result bool Returns whether data were provided already
function hasData(address oracleId, uint256 timestamp) public view returns(bool result) {
return dataExist[oracleId][timestamp];
}
}
// File: contracts/Errors/SyntheticAggregatorErrors.sol
pragma solidity 0.5.16;
contract SyntheticAggregatorErrors {
string constant internal ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH = "SYNTHETIC_AGGREGATOR:DERIVATIVE_HASH_NOT_MATCH";
string constant internal ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN = "SYNTHETIC_AGGREGATOR:WRONG_MARGIN";
string constant internal ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG = "SYNTHETIC_AGGREGATOR:COMMISSION_TOO_BIG";
}
// File: contracts/SyntheticAggregator.sol
pragma solidity 0.5.16;
/// @notice Opium.SyntheticAggregator contract initialized, identifies and caches syntheticId sensitive data
contract SyntheticAggregator is SyntheticAggregatorErrors, LibDerivative, LibCommission, ReentrancyGuard {
// Emitted when new ticker is initialized
event Create(Derivative derivative, bytes32 derivativeHash);
// Enum for types of syntheticId
// Invalid - syntheticId is not initialized yet
// NotPool - syntheticId with p2p logic
// Pool - syntheticId with pooled logic
enum SyntheticTypes { Invalid, NotPool, Pool }
// Cache of buyer margin by ticker
// buyerMarginByHash[derivativeHash] = buyerMargin
mapping (bytes32 => uint256) public buyerMarginByHash;
// Cache of seller margin by ticker
// sellerMarginByHash[derivativeHash] = sellerMargin
mapping (bytes32 => uint256) public sellerMarginByHash;
// Cache of type by ticker
// typeByHash[derivativeHash] = type
mapping (bytes32 => SyntheticTypes) public typeByHash;
// Cache of commission by ticker
// commissionByHash[derivativeHash] = commission
mapping (bytes32 => uint256) public commissionByHash;
// Cache of author addresses by ticker
// authorAddressByHash[derivativeHash] = authorAddress
mapping (bytes32 => address) public authorAddressByHash;
// PUBLIC FUNCTIONS
/// @notice Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return commission uint256 Synthetic author commission
function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) {
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
commission = commissionByHash[_derivativeHash];
}
/// @notice Initializes ticker, if was not initialized and returns `syntheticId` author address from cache
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return authorAddress address Synthetic author address
function getAuthorAddress(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (address authorAddress) {
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
authorAddress = authorAddressByHash[_derivativeHash];
}
/// @notice Initializes ticker, if was not initialized and returns buyer and seller margin from cache
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return buyerMargin uint256 Margin of buyer
/// @return sellerMargin uint256 Margin of seller
function getMargin(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 buyerMargin, uint256 sellerMargin) {
// If it's a pool, just return margin from syntheticId contract
if (_isPool(_derivativeHash, _derivative)) {
return IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative);
}
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
// Check if margins for _derivativeHash were already cached
buyerMargin = buyerMarginByHash[_derivativeHash];
sellerMargin = sellerMarginByHash[_derivativeHash];
}
/// @notice Checks whether `syntheticId` implements pooled logic
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return result bool Returns whether synthetic implements pooled logic
function isPool(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (bool result) {
result = _isPool(_derivativeHash, _derivative);
}
// PRIVATE FUNCTIONS
/// @notice Initializes ticker, if was not initialized and returns whether `syntheticId` implements pooled logic
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return result bool Returns whether synthetic implements pooled logic
function _isPool(bytes32 _derivativeHash, Derivative memory _derivative) private returns (bool result) {
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
result = typeByHash[_derivativeHash] == SyntheticTypes.Pool;
}
/// @notice Initializes ticker: caches syntheticId type, margin, author address and commission
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
function _initDerivative(bytes32 _derivativeHash, Derivative memory _derivative) private {
// Check if type for _derivativeHash was already cached
SyntheticTypes syntheticType = typeByHash[_derivativeHash];
// Type could not be Invalid, thus this condition says us that type was not cached before
if (syntheticType != SyntheticTypes.Invalid) {
return;
}
// For security reasons we calculate hash of provided _derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
require(derivativeHash == _derivativeHash, ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH);
// POOL
// Get isPool from SyntheticId
bool result = IDerivativeLogic(_derivative.syntheticId).isPool();
// Cache type returned from synthetic
typeByHash[derivativeHash] = result ? SyntheticTypes.Pool : SyntheticTypes.NotPool;
// MARGIN
// Get margin from SyntheticId
(uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative);
// We are not allowing both margins to be equal to 0
require(buyerMargin != 0 || sellerMargin != 0, ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN);
// Cache margins returned from synthetic
buyerMarginByHash[derivativeHash] = buyerMargin;
sellerMarginByHash[derivativeHash] = sellerMargin;
// AUTHOR ADDRESS
// Cache author address returned from synthetic
authorAddressByHash[derivativeHash] = IDerivativeLogic(_derivative.syntheticId).getAuthorAddress();
// AUTHOR COMMISSION
// Get commission from syntheticId
uint256 commission = IDerivativeLogic(_derivative.syntheticId).getAuthorCommission();
// Check if commission is not set > 100%
require(commission <= COMMISSION_BASE, ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG);
// Cache commission
commissionByHash[derivativeHash] = commission;
// If we are here, this basically means this ticker was not used before, so we emit an event for Dapps developers about new ticker (derivative) and it's hash
emit Create(_derivative, derivativeHash);
}
}
// File: contracts/Lib/Whitelisted.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses
contract Whitelisted {
// Whitelist array
address[] internal whitelist;
/// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses
modifier onlyWhitelisted() {
// Allowance flag
bool allowed = false;
// Going through whitelisted addresses array
uint256 whitelistLength = whitelist.length;
for (uint256 i = 0; i < whitelistLength; i++) {
// If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop
if (whitelist[i] == msg.sender) {
allowed = true;
break;
}
}
// Check if flag was raised
require(allowed, "Only whitelisted allowed");
_;
}
/// @notice Getter for whitelisted addresses array
/// @return Array of whitelisted addresses
function getWhitelist() public view returns (address[] memory) {
return whitelist;
}
}
// File: contracts/Lib/WhitelistedWithGovernance.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.WhitelistedWithGovernance contract implements Opium.Lib.Whitelisted and adds governance for whitelist controlling
contract WhitelistedWithGovernance is Whitelisted {
// Emitted when new governor is set
event GovernorSet(address governor);
// Emitted when new whitelist is proposed
event Proposed(address[] whitelist);
// Emitted when proposed whitelist is committed (set)
event Committed(address[] whitelist);
// Proposal life timelock interval
uint256 public timeLockInterval;
// Governor address
address public governor;
// Timestamp of last proposal
uint256 public proposalTime;
// Proposed whitelist
address[] public proposedWhitelist;
/// @notice This modifier restricts access to functions, which could be called only by governor
modifier onlyGovernor() {
require(msg.sender == governor, "Only governor allowed");
_;
}
/// @notice Contract constructor
/// @param _timeLockInterval uint256 Initial value for timelock interval
/// @param _governor address Initial value for governor
constructor(uint256 _timeLockInterval, address _governor) public {
timeLockInterval = _timeLockInterval;
governor = _governor;
emit GovernorSet(governor);
}
/// @notice Calling this function governor could propose new whitelist addresses array. Also it allows to initialize first whitelist if it was not initialized yet.
function proposeWhitelist(address[] memory _whitelist) public onlyGovernor {
// Restrict empty proposals
require(_whitelist.length != 0, "Can't be empty");
// Consider empty whitelist as not initialized, as proposing of empty whitelists is not allowed
// If whitelist has never been initialized, we set whitelist right away without proposal
if (whitelist.length == 0) {
whitelist = _whitelist;
emit Committed(_whitelist);
// Otherwise save current time as timestamp of proposal, save proposed whitelist and emit event
} else {
proposalTime = now;
proposedWhitelist = _whitelist;
emit Proposed(_whitelist);
}
}
/// @notice Calling this function governor commits proposed whitelist if timelock interval of proposal was passed
function commitWhitelist() public onlyGovernor {
// Check if proposal was made
require(proposalTime != 0, "Didn't proposed yet");
// Check if timelock interval was passed
require((proposalTime + timeLockInterval) < now, "Can't commit yet");
// Set new whitelist and emit event
whitelist = proposedWhitelist;
emit Committed(whitelist);
// Reset proposal time lock
proposalTime = 0;
}
/// @notice This function allows governor to transfer governance to a new governor and emits event
/// @param _governor address Address of new governor
function setGovernor(address _governor) public onlyGovernor {
require(_governor != address(0), "Can't set zero address");
governor = _governor;
emit GovernorSet(governor);
}
}
// File: contracts/Lib/WhitelistedWithGovernanceAndChangableTimelock.sol
pragma solidity 0.5.16;
/// @notice Opium.Lib.WhitelistedWithGovernanceAndChangableTimelock contract implements Opium.Lib.WhitelistedWithGovernance and adds possibility for governor to change timelock interval within timelock interval
contract WhitelistedWithGovernanceAndChangableTimelock is WhitelistedWithGovernance {
// Emitted when new timelock is proposed
event Proposed(uint256 timelock);
// Emitted when new timelock is committed (set)
event Committed(uint256 timelock);
// Timestamp of last timelock proposal
uint256 public timeLockProposalTime;
// Proposed timelock
uint256 public proposedTimeLock;
/// @notice Calling this function governor could propose new timelock
/// @param _timelock uint256 New timelock value
function proposeTimelock(uint256 _timelock) public onlyGovernor {
timeLockProposalTime = now;
proposedTimeLock = _timelock;
emit Proposed(_timelock);
}
/// @notice Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed
function commitTimelock() public onlyGovernor {
// Check if proposal was made
require(timeLockProposalTime != 0, "Didn't proposed yet");
// Check if timelock interval was passed
require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet");
// Set new timelock and emit event
timeLockInterval = proposedTimeLock;
emit Committed(proposedTimeLock);
// Reset timelock time lock
timeLockProposalTime = 0;
}
}
// File: contracts/TokenSpender.sol
pragma solidity 0.5.16;
/// @title Opium.TokenSpender contract holds users ERC20 approvals and allows whitelisted contracts to use tokens
contract TokenSpender is WhitelistedWithGovernanceAndChangableTimelock {
using SafeERC20 for IERC20;
// Initial timelock period
uint256 public constant WHITELIST_TIMELOCK = 1 hours;
/// @notice Calls constructors of super-contracts
/// @param _governor address Address of governor, who is allowed to adjust whitelist
constructor(address _governor) public WhitelistedWithGovernance(WHITELIST_TIMELOCK, _governor) {}
/// @notice Using this function whitelisted contracts could call ERC20 transfers
/// @param token IERC20 Instance of token
/// @param from address Address from which tokens are transferred
/// @param to address Address of tokens receiver
/// @param amount uint256 Amount of tokens to be transferred
function claimTokens(IERC20 token, address from, address to, uint256 amount) external onlyWhitelisted {
token.safeTransferFrom(from, to, amount);
}
/// @notice Using this function whitelisted contracts could call ERC721O transfers
/// @param token IERC721O Instance of token
/// @param from address Address from which tokens are transferred
/// @param to address Address of tokens receiver
/// @param tokenId uint256 Token ID to be transferred
/// @param amount uint256 Amount of tokens to be transferred
function claimPositions(IERC721O token, address from, address to, uint256 tokenId, uint256 amount) external onlyWhitelisted {
token.safeTransferFrom(from, to, tokenId, amount);
}
}
// File: contracts/Core.sol
pragma solidity 0.5.16;
/// @title Opium.Core contract creates positions, holds and distributes margin at the maturity
contract Core is LibDerivative, LibCommission, UsingRegistry, CoreErrors, ReentrancyGuard {
using SafeMath for uint256;
using LibPosition for bytes32;
using SafeERC20 for IERC20;
// Emitted when Core creates new position
event Created(address buyer, address seller, bytes32 derivativeHash, uint256 quantity);
// Emitted when Core executes positions
event Executed(address tokenOwner, uint256 tokenId, uint256 quantity);
// Emitted when Core cancels ticker for the first time
event Canceled(bytes32 derivativeHash);
// Period of time after which ticker could be canceled if no data was provided to the `oracleId`
uint256 public constant NO_DATA_CANCELLATION_PERIOD = 2 weeks;
// Vaults for pools
// This mapping holds balances of pooled positions
// poolVaults[syntheticAddress][tokenAddress] => availableBalance
mapping (address => mapping(address => uint256)) public poolVaults;
// Vaults for fees
// This mapping holds balances of fee recipients
// feesVaults[feeRecipientAddress][tokenAddress] => availableBalance
mapping (address => mapping(address => uint256)) public feesVaults;
// Hashes of cancelled tickers
mapping (bytes32 => bool) public cancelled;
/// @notice Calls Core.Lib.UsingRegistry constructor
constructor(address _registry) public UsingRegistry(_registry) {}
// PUBLIC FUNCTIONS
/// @notice This function allows fee recipients to withdraw their fees
/// @param _tokenAddress address Address of an ERC20 token to withdraw
function withdrawFee(address _tokenAddress) public nonReentrant {
uint256 balance = feesVaults[msg.sender][_tokenAddress];
feesVaults[msg.sender][_tokenAddress] = 0;
IERC20(_tokenAddress).safeTransfer(msg.sender, balance);
}
/// @notice Creates derivative contracts (positions)
/// @param _derivative Derivative Derivative definition
/// @param _quantity uint256 Quantity of derivatives to be created
/// @param _addresses address[2] Addresses of buyer and seller
/// [0] - buyer address
/// [1] - seller address - if seller is set to `address(0)`, consider as pooled position
function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant {
if (_addresses[1] == address(0)) {
_createPooled(_derivative, _quantity, _addresses[0]);
} else {
_create(_derivative, _quantity, _addresses);
}
}
/// @notice Executes several positions of `msg.sender` with same `tokenId`
/// @param _tokenId uint256 `tokenId` of positions that needs to be executed
/// @param _quantity uint256 Quantity of positions to execute
/// @param _derivative Derivative Derivative definition
function execute(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant {
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory quantities = new uint256[](1);
Derivative[] memory derivatives = new Derivative[](1);
tokenIds[0] = _tokenId;
quantities[0] = _quantity;
derivatives[0] = _derivative;
_execute(msg.sender, tokenIds, quantities, derivatives);
}
/// @notice Executes several positions of `_tokenOwner` with same `tokenId`
/// @param _tokenOwner address Address of the owner of positions
/// @param _tokenId uint256 `tokenId` of positions that needs to be executed
/// @param _quantity uint256 Quantity of positions to execute
/// @param _derivative Derivative Derivative definition
function execute(address _tokenOwner, uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant {
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory quantities = new uint256[](1);
Derivative[] memory derivatives = new Derivative[](1);
tokenIds[0] = _tokenId;
quantities[0] = _quantity;
derivatives[0] = _derivative;
_execute(_tokenOwner, tokenIds, quantities, derivatives);
}
/// @notice Executes several positions of `msg.sender` with different `tokenId`s
/// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed
/// @param _quantities uint256[] Quantity of positions to execute for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function execute(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant {
_execute(msg.sender, _tokenIds, _quantities, _derivatives);
}
/// @notice Executes several positions of `_tokenOwner` with different `tokenId`s
/// @param _tokenOwner address Address of the owner of positions
/// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed
/// @param _quantities uint256[] Quantity of positions to execute for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant {
_execute(_tokenOwner, _tokenIds, _quantities, _derivatives);
}
/// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD`
/// @param _tokenId uint256 `tokenId` of positions that needs to be canceled
/// @param _quantity uint256 Quantity of positions to cancel
/// @param _derivative Derivative Derivative definition
function cancel(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant {
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory quantities = new uint256[](1);
Derivative[] memory derivatives = new Derivative[](1);
tokenIds[0] = _tokenId;
quantities[0] = _quantity;
derivatives[0] = _derivative;
_cancel(tokenIds, quantities, derivatives);
}
/// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD`
/// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled
/// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant {
_cancel(_tokenIds, _quantities, _derivatives);
}
// PRIVATE FUNCTIONS
struct CreatePooledLocalVars {
SyntheticAggregator syntheticAggregator;
IDerivativeLogic derivativeLogic;
IERC20 marginToken;
TokenSpender tokenSpender;
TokenMinter tokenMinter;
}
/// @notice This function creates pooled positions
/// @param _derivative Derivative Derivative definition
/// @param _quantity uint256 Quantity of positions to create
/// @param _address address Address of position receiver
function _createPooled(Derivative memory _derivative, uint256 _quantity, address _address) private {
// Local variables
CreatePooledLocalVars memory vars;
// Create instance of Opium.SyntheticAggregator
// Create instance of Opium.IDerivativeLogic
// Create instance of margin token
// Create instance of Opium.TokenSpender
// Create instance of Opium.TokenMinter
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId);
vars.marginToken = IERC20(_derivative.token);
vars.tokenSpender = TokenSpender(registry.getTokenSpender());
vars.tokenMinter = TokenMinter(registry.getMinter());
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
// Check with Opium.SyntheticAggregator if syntheticId is a pool
require(vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_NOT_POOL);
// Check if ticker was canceled
require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED);
// Validate input data against Derivative logic (`syntheticId`)
require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR);
// Get cached margin required according to logic from Opium.SyntheticAggregator
(uint256 margin, ) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative);
// Check ERC20 tokens allowance: margin * quantity
// `msg.sender` must provide margin for position creation
require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margin.mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE);
// Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation
vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margin.mul(_quantity));
// Since it's a pooled position, we add transferred margin to pool balance
poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].add(margin.mul(_quantity));
// Mint LONG position tokens
vars.tokenMinter.mint(_address, derivativeHash, _quantity);
emit Created(_address, address(0), derivativeHash, _quantity);
}
struct CreateLocalVars {
SyntheticAggregator syntheticAggregator;
IDerivativeLogic derivativeLogic;
IERC20 marginToken;
TokenSpender tokenSpender;
TokenMinter tokenMinter;
}
/// @notice This function creates p2p positions
/// @param _derivative Derivative Derivative definition
/// @param _quantity uint256 Quantity of positions to create
/// @param _addresses address[2] Addresses of buyer and seller
/// [0] - buyer address
/// [1] - seller address
function _create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) private {
// Local variables
CreateLocalVars memory vars;
// Create instance of Opium.SyntheticAggregator
// Create instance of Opium.IDerivativeLogic
// Create instance of margin token
// Create instance of Opium.TokenSpender
// Create instance of Opium.TokenMinter
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId);
vars.marginToken = IERC20(_derivative.token);
vars.tokenSpender = TokenSpender(registry.getTokenSpender());
vars.tokenMinter = TokenMinter(registry.getMinter());
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
// Check with Opium.SyntheticAggregator if syntheticId is not a pool
require(!vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_CANT_BE_POOL);
// Check if ticker was canceled
require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED);
// Validate input data against Derivative logic (`syntheticId`)
require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR);
uint256[2] memory margins;
// Get cached margin required according to logic from Opium.SyntheticAggregator
// margins[0] - buyerMargin
// margins[1] - sellerMargin
(margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative);
// Check ERC20 tokens allowance: (margins[0] + margins[1]) * quantity
// `msg.sender` must provide margin for position creation
require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margins[0].add(margins[1]).mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE);
// Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation
vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margins[0].add(margins[1]).mul(_quantity));
// Mint LONG and SHORT positions tokens
vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity);
emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity);
}
struct ExecuteAndCancelLocalVars {
TokenMinter tokenMinter;
OracleAggregator oracleAggregator;
SyntheticAggregator syntheticAggregator;
}
/// @notice Executes several positions of `_tokenOwner` with different `tokenId`s
/// @param _tokenOwner address Address of the owner of positions
/// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed
/// @param _quantities uint256[] Quantity of positions to execute for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function _execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private {
require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH);
require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH);
// Local variables
ExecuteAndCancelLocalVars memory vars;
// Create instance of Opium.TokenMinter
// Create instance of Opium.OracleAggregator
// Create instance of Opium.SyntheticAggregator
vars.tokenMinter = TokenMinter(registry.getMinter());
vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator());
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
for (uint256 i; i < _tokenIds.length; i++) {
// Check if execution is performed after endTime
require(now > _derivatives[i].endTime, ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED);
// Checking whether execution is performed by `_tokenOwner` or `_tokenOwner` allowed third party executions on it's behalf
require(
_tokenOwner == msg.sender ||
IDerivativeLogic(_derivatives[i].syntheticId).thirdpartyExecutionAllowed(_tokenOwner),
ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED
);
// Returns payout for all positions
uint256 payout = _getPayout(_derivatives[i], _tokenIds[i], _quantities[i], vars);
// Transfer payout
if (payout > 0) {
IERC20(_derivatives[i].token).safeTransfer(_tokenOwner, payout);
}
// Burn executed position tokens
vars.tokenMinter.burn(_tokenOwner, _tokenIds[i], _quantities[i]);
emit Executed(_tokenOwner, _tokenIds[i], _quantities[i]);
}
}
/// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD`
/// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled
/// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function _cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private {
require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH);
require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH);
// Local variables
ExecuteAndCancelLocalVars memory vars;
// Create instance of Opium.TokenMinter
// Create instance of Opium.OracleAggregator
// Create instance of Opium.SyntheticAggregator
vars.tokenMinter = TokenMinter(registry.getMinter());
vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator());
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
for (uint256 i; i < _tokenIds.length; i++) {
// Don't allow to cancel tickers with "dummy" oracleIds
require(_derivatives[i].oracleId != address(0), ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID);
// Check if cancellation is called after `NO_DATA_CANCELLATION_PERIOD` and `oracleId` didn't provided data
require(
_derivatives[i].endTime + NO_DATA_CANCELLATION_PERIOD <= now &&
!vars.oracleAggregator.hasData(_derivatives[i].oracleId, _derivatives[i].endTime),
ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED
);
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivatives[i]);
// Emit `Canceled` event only once and mark ticker as canceled
if (!cancelled[derivativeHash]) {
cancelled[derivativeHash] = true;
emit Canceled(derivativeHash);
}
uint256[2] memory margins;
// Get cached margin required according to logic from Opium.SyntheticAggregator
// margins[0] - buyerMargin
// margins[1] - sellerMargin
(margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivatives[i]);
uint256 payout;
// Check if `_tokenId` is an ID of LONG position
if (derivativeHash.getLongTokenId() == _tokenIds[i]) {
// Set payout to buyerPayout
payout = margins[0];
// Check if `_tokenId` is an ID of SHORT position
} else if (derivativeHash.getShortTokenId() == _tokenIds[i]) {
// Set payout to sellerPayout
payout = margins[1];
} else {
// Either portfolioId, hack or bug
revert(ERROR_CORE_UNKNOWN_POSITION_TYPE);
}
// Transfer payout * _quantities[i]
if (payout > 0) {
IERC20(_derivatives[i].token).safeTransfer(msg.sender, payout.mul(_quantities[i]));
}
// Burn canceled position tokens
vars.tokenMinter.burn(msg.sender, _tokenIds[i], _quantities[i]);
}
}
/// @notice Calculates payout for position and gets fees
/// @param _derivative Derivative Derivative definition
/// @param _tokenId uint256 `tokenId` of positions
/// @param _quantity uint256 Quantity of positions
/// @param _vars ExecuteAndCancelLocalVars Helping local variables
/// @return payout uint256 Payout for all tokens
function _getPayout(Derivative memory _derivative, uint256 _tokenId, uint256 _quantity, ExecuteAndCancelLocalVars memory _vars) private returns (uint256 payout) {
// Trying to getData from Opium.OracleAggregator, could be reverted
// Opium allows to use "dummy" oracleIds, in this case data is set to `0`
uint256 data;
if (_derivative.oracleId != address(0)) {
data = _vars.oracleAggregator.getData(_derivative.oracleId, _derivative.endTime);
} else {
data = 0;
}
uint256[2] memory payoutRatio;
// Get payout ratio from Derivative logic
// payoutRatio[0] - buyerPayout
// payoutRatio[1] - sellerPayout
(payoutRatio[0], payoutRatio[1]) = IDerivativeLogic(_derivative.syntheticId).getExecutionPayout(_derivative, data);
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
// Check if ticker was canceled
require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED);
uint256[2] memory margins;
// Get cached total margin required from Opium.SyntheticAggregator
// margins[0] - buyerMargin
// margins[1] - sellerMargin
(margins[0], margins[1]) = _vars.syntheticAggregator.getMargin(derivativeHash, _derivative);
uint256[2] memory payouts;
// Calculate payouts from ratio
// payouts[0] -> buyerPayout = (buyerMargin + sellerMargin) * buyerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio)
// payouts[1] -> sellerPayout = (buyerMargin + sellerMargin) * sellerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio)
payouts[0] = margins[0].add(margins[1]).mul(payoutRatio[0]).div(payoutRatio[0].add(payoutRatio[1]));
payouts[1] = margins[0].add(margins[1]).mul(payoutRatio[1]).div(payoutRatio[0].add(payoutRatio[1]));
// Check if `_tokenId` is an ID of LONG position
if (derivativeHash.getLongTokenId() == _tokenId) {
// Check if it's a pooled position
if (_vars.syntheticAggregator.isPool(derivativeHash, _derivative)) {
// Pooled position payoutRatio is considered as full payout, not as payoutRatio
payout = payoutRatio[0];
// Multiply payout by quantity
payout = payout.mul(_quantity);
// Check sufficiency of syntheticId balance in poolVaults
require(
poolVaults[_derivative.syntheticId][_derivative.token] >= payout
,
ERROR_CORE_INSUFFICIENT_POOL_BALANCE
);
// Subtract paid out margin from poolVault
poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].sub(payout);
} else {
// Set payout to buyerPayout
payout = payouts[0];
// Multiply payout by quantity
payout = payout.mul(_quantity);
}
// Take fees only from profit makers
// Check: payout > buyerMargin * quantity
if (payout > margins[0].mul(_quantity)) {
// Get Opium and `syntheticId` author fees and subtract it from payout
payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[0].mul(_quantity)));
}
// Check if `_tokenId` is an ID of SHORT position
} else if (derivativeHash.getShortTokenId() == _tokenId) {
// Set payout to sellerPayout
payout = payouts[1];
// Multiply payout by quantity
payout = payout.mul(_quantity);
// Take fees only from profit makers
// Check: payout > sellerMargin * quantity
if (payout > margins[1].mul(_quantity)) {
// Get Opium fees and subtract it from payout
payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[1].mul(_quantity)));
}
} else {
// Either portfolioId, hack or bug
revert(ERROR_CORE_UNKNOWN_POSITION_TYPE);
}
}
/// @notice Calculates `syntheticId` author and opium fees from profit makers
/// @param _syntheticAggregator SyntheticAggregator Instance of Opium.SyntheticAggregator
/// @param _derivativeHash bytes32 Derivative hash
/// @param _derivative Derivative Derivative definition
/// @param _profit uint256 payout of one position
/// @return fee uint256 Opium and `syntheticId` author fee
function _getFees(SyntheticAggregator _syntheticAggregator, bytes32 _derivativeHash, Derivative memory _derivative, uint256 _profit) private returns (uint256 fee) {
// Get cached `syntheticId` author address from Opium.SyntheticAggregator
address authorAddress = _syntheticAggregator.getAuthorAddress(_derivativeHash, _derivative);
// Get cached `syntheticId` fee percentage from Opium.SyntheticAggregator
uint256 commission = _syntheticAggregator.getAuthorCommission(_derivativeHash, _derivative);
// Calculate fee
// fee = profit * commission / COMMISSION_BASE
fee = _profit.mul(commission).div(COMMISSION_BASE);
// If commission is zero, finish
if (fee == 0) {
return 0;
}
// Calculate opium fee
// opiumFee = fee * OPIUM_COMMISSION_PART / OPIUM_COMMISSION_BASE
uint256 opiumFee = fee.mul(OPIUM_COMMISSION_PART).div(OPIUM_COMMISSION_BASE);
// Calculate author fee
// authorFee = fee - opiumFee
uint256 authorFee = fee.sub(opiumFee);
// Get opium address
address opiumAddress = registry.getOpiumAddress();
// Update feeVault for Opium team
// feesVault[opium][token] += opiumFee
feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee);
// Update feeVault for `syntheticId` author
// feeVault[author][token] += authorFee
feesVaults[authorAddress][_derivative.token] = feesVaults[authorAddress][_derivative.token].add(authorFee);
}
}
// File: contracts/Errors/MatchingErrors.sol
pragma solidity 0.5.16;
contract MatchingErrors {
string constant internal ERROR_MATCH_CANCELLATION_NOT_ALLOWED = "MATCH:CANCELLATION_NOT_ALLOWED";
string constant internal ERROR_MATCH_ALREADY_CANCELED = "MATCH:ALREADY_CANCELED";
string constant internal ERROR_MATCH_ORDER_WAS_CANCELED = "MATCH:ORDER_WAS_CANCELED";
string constant internal ERROR_MATCH_TAKER_ADDRESS_WRONG = "MATCH:TAKER_ADDRESS_WRONG";
string constant internal ERROR_MATCH_ORDER_IS_EXPIRED = "MATCH:ORDER_IS_EXPIRED";
string constant internal ERROR_MATCH_SENDER_ADDRESS_WRONG = "MATCH:SENDER_ADDRESS_WRONG";
string constant internal ERROR_MATCH_SIGNATURE_NOT_VERIFIED = "MATCH:SIGNATURE_NOT_VERIFIED";
string constant internal ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES = "MATCH:NOT_ENOUGH_ALLOWED_FEES";
}
// File: contracts/Lib/LibEIP712.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.LibEIP712 contract implements the domain of EIP712 for meta transactions
contract LibEIP712 {
// EIP712Domain structure
// name - protocol name
// version - protocol version
// verifyingContract - signed message verifying contract
struct EIP712Domain {
string name;
string version;
address verifyingContract;
}
// Calculate typehash of ERC712Domain
bytes32 constant internal EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
// solhint-disable-next-line var-name-mixedcase
bytes32 internal DOMAIN_SEPARATOR;
// Calculate domain separator at creation
constructor () public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256("Opium Network"),
keccak256("1"),
address(this)
));
}
/// @notice Hashes EIP712Message
/// @param hashStruct bytes32 Hash of structured message
/// @return result bytes32 Hash of EIP712Message
function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) {
bytes32 domainSeparator = DOMAIN_SEPARATOR;
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), domainSeparator) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// File: contracts/Matching/SwaprateMatch/LibSwaprateOrder.sol
pragma solidity 0.5.16;
/// @title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch
contract LibSwaprateOrder is LibEIP712 {
/**
Structure of order
Description should be considered from the order signer (maker) perspective
syntheticId - address of derivative syntheticId
oracleId - address of derivative oracleId
token - address of derivative margin token
makerMarginAddress - address of token that maker is willing to pay with
takerMarginAddress - address of token that maker is willing to receive
makerAddress - address of maker
takerAddress - address of counterparty (taker). If zero address, then taker could be anyone
senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle
relayerAddress - address of the relayer fee recipient
affiliateAddress - address of the affiliate fee recipient
feeTokenAddress - address of token which is used for fees
endTime - timestamp of derivative maturity
quantity - quantity of positions maker wants to receive
partialFill - whether maker allows partial fill of it's order
param0...param9 - additional params to pass it to syntheticId
relayerFee - amount of fee in feeToken that should be paid to relayer
affiliateFee - amount of fee in feeToken that should be paid to affiliate
nonce - unique order ID
signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes
*/
struct SwaprateOrder {
address syntheticId;
address oracleId;
address token;
address makerAddress;
address takerAddress;
address senderAddress;
address relayerAddress;
address affiliateAddress;
address feeTokenAddress;
uint256 endTime;
uint256 quantity;
uint256 partialFill;
uint256 param0;
uint256 param1;
uint256 param2;
uint256 param3;
uint256 param4;
uint256 param5;
uint256 param6;
uint256 param7;
uint256 param8;
uint256 param9;
uint256 relayerFee;
uint256 affiliateFee;
uint256 nonce;
// Not used in hash
bytes signature;
}
// Calculate typehash of Order
bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked(
"Order(",
"address syntheticId,",
"address oracleId,",
"address token,",
"address makerAddress,",
"address takerAddress,",
"address senderAddress,",
"address relayerAddress,",
"address affiliateAddress,",
"address feeTokenAddress,",
"uint256 endTime,",
"uint256 quantity,",
"uint256 partialFill,",
"uint256 param0,",
"uint256 param1,",
"uint256 param2,",
"uint256 param3,",
"uint256 param4,",
"uint256 param5,",
"uint256 param6,",
"uint256 param7,",
"uint256 param8,",
"uint256 param9,",
"uint256 relayerFee,",
"uint256 affiliateFee,",
"uint256 nonce",
")"
));
/// @notice Hashes the order
/// @param _order SwaprateOrder Order to hash
/// @return hash bytes32 Order hash
function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) {
hash = keccak256(
abi.encodePacked(
abi.encodePacked(
EIP712_ORDER_TYPEHASH,
uint256(_order.syntheticId),
uint256(_order.oracleId),
uint256(_order.token),
uint256(_order.makerAddress),
uint256(_order.takerAddress),
uint256(_order.senderAddress),
uint256(_order.relayerAddress),
uint256(_order.affiliateAddress),
uint256(_order.feeTokenAddress)
),
abi.encodePacked(
_order.endTime,
_order.quantity,
_order.partialFill
),
abi.encodePacked(
_order.param0,
_order.param1,
_order.param2,
_order.param3,
_order.param4
),
abi.encodePacked(
_order.param5,
_order.param6,
_order.param7,
_order.param8,
_order.param9
),
abi.encodePacked(
_order.relayerFee,
_order.affiliateFee,
_order.nonce
)
)
);
}
/// @notice Verifies order signature
/// @param _hash bytes32 Hash of the order
/// @param _signature bytes Signature of the order
/// @param _address address Address of the order signer
/// @return bool Returns whether `_signature` is valid and was created by `_address`
function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) {
require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH");
bytes32 digest = hashEIP712Message(_hash);
address recovered = retrieveAddress(digest, _signature);
return _address == recovered;
}
/// @notice Helping function to recover signer address
/// @param _hash bytes32 Hash for signature
/// @param _signature bytes Signature
/// @return address Returns address of signature creator
function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(_hash, v, r, s);
}
}
}
// File: contracts/Matching/SwaprateMatch/SwaprateMatchBase.sol
pragma solidity 0.5.16;
/// @title Opium.Matching.SwaprateMatchBase contract implements logic for order validation and cancelation
contract SwaprateMatchBase is MatchingErrors, LibSwaprateOrder, UsingRegistry, ReentrancyGuard {
using SafeMath for uint256;
using LibPosition for bytes32;
using SafeERC20 for IERC20;
// Emmitted when order was canceled
event Canceled(bytes32 orderHash);
// Canceled orders
// This mapping holds hashes of canceled orders
// canceled[orderHash] => canceled
mapping (bytes32 => bool) public canceled;
// Verified orders
// This mapping holds hashes of verified orders to verify only once
// verified[orderHash] => verified
mapping (bytes32 => bool) public verified;
// Vaults for fees
// This mapping holds balances of relayers and affiliates fees to withdraw
// balances[feeRecipientAddress][tokenAddress] => balances
mapping (address => mapping (address => uint256)) public balances;
// Keeps whether fee was already taken
mapping (bytes32 => bool) public feeTaken;
/// @notice Calling this function maker of the order could cancel it on-chain
/// @param _order SwaprateOrder
function cancel(SwaprateOrder memory _order) public {
require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED);
bytes32 orderHash = hashOrder(_order);
require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED);
canceled[orderHash] = true;
emit Canceled(orderHash);
}
/// @notice Function to withdraw fees from orders for relayer and affiliates
/// @param _token IERC20 Instance of token to withdraw
function withdraw(IERC20 _token) public nonReentrant {
uint256 balance = balances[msg.sender][address(_token)];
balances[msg.sender][address(_token)] = 0;
_token.safeTransfer(msg.sender, balance);
}
/// @notice This function checks whether order was canceled
/// @param _hash bytes32 Hash of the order
function validateNotCanceled(bytes32 _hash) internal view {
require(!canceled[_hash], ERROR_MATCH_ORDER_WAS_CANCELED);
}
/// @notice This function validates takerAddress of _leftOrder. It should match either with _rightOrder.makerAddress or be set to zero address
/// @param _leftOrder SwaprateOrder Left order
/// @param _rightOrder SwaprateOrder Right order
function validateTakerAddress(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder) pure internal {
require(
_leftOrder.takerAddress == address(0) ||
_leftOrder.takerAddress == _rightOrder.makerAddress,
ERROR_MATCH_TAKER_ADDRESS_WRONG
);
}
/// @notice This function validates whether sender address equals to `msg.sender` or set to zero address
/// @param _order SwaprateOrder
function validateSenderAddress(SwaprateOrder memory _order) internal view {
require(
_order.senderAddress == address(0) ||
_order.senderAddress == msg.sender,
ERROR_MATCH_SENDER_ADDRESS_WRONG
);
}
/// @notice This function validates order signature if not validated before
/// @param orderHash bytes32 Hash of the order
/// @param _order SwaprateOrder
function validateSignature(bytes32 orderHash, SwaprateOrder memory _order) internal {
if (verified[orderHash]) {
return;
}
bool result = verifySignature(orderHash, _order.signature, _order.makerAddress);
require(result, ERROR_MATCH_SIGNATURE_NOT_VERIFIED);
verified[orderHash] = true;
}
/// @notice This function is responsible for taking relayer and affiliate fees, if they were not taken already
/// @param _orderHash bytes32 Hash of the order
/// @param _order Order Order itself
function takeFees(bytes32 _orderHash, SwaprateOrder memory _order) internal {
// Check if fee was already taken
if (feeTaken[_orderHash]) {
return;
}
// Check if feeTokenAddress is not set to zero address
if (_order.feeTokenAddress == address(0)) {
return;
}
// Calculate total amount of fees needs to be transfered
uint256 fees = _order.relayerFee.add(_order.affiliateFee);
// If total amount of fees is non-zero
if (fees == 0) {
return;
}
// Create instance of fee token
IERC20 feeToken = IERC20(_order.feeTokenAddress);
// Create instance of TokenSpender
TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender());
// Check if user has enough token approval to pay the fees
require(feeToken.allowance(_order.makerAddress, address(tokenSpender)) >= fees, ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES);
// Transfer fee
tokenSpender.claimTokens(feeToken, _order.makerAddress, address(this), fees);
// Get opium address
address opiumAddress = registry.getOpiumAddress();
// Add commission to relayer balance, or to opium balance if relayer is not set
if (_order.relayerAddress != address(0)) {
balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee);
} else {
balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee);
}
// Add commission to affiliate balance, or to opium balance if affiliate is not set
if (_order.affiliateAddress != address(0)) {
balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee);
} else {
balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee);
}
// Mark the fee of token as taken
feeTaken[_orderHash] = true;
}
/// @notice Helper to get minimal of two integers
/// @param _a uint256 First integer
/// @param _b uint256 Second integer
/// @return uint256 Minimal integer
function min(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: contracts/Matching/SwaprateMatch/SwaprateMatch.sol
pragma solidity 0.5.16;
/// @title Opium.Matching.SwaprateMatch contract implements create() function to settle a pair of orders and create derivatives for order makers
contract SwaprateMatch is SwaprateMatchBase, LibDerivative {
// Orders filled quantity
// This mapping holds orders filled quantity
// filled[orderHash] => filled
mapping (bytes32 => uint256) public filled;
/// @notice Calls constructors of super-contracts
/// @param _registry address Address of Opium.registry
constructor (address _registry) public UsingRegistry(_registry) {}
/// @notice This function receives left and right orders, derivative related to it
/// @param _leftOrder Order
/// @param _rightOrder Order
/// @param _derivative Derivative Data of derivative for validation and calculation purposes
function create(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) public nonReentrant {
// New deals must not offer tokenIds
require(
_leftOrder.syntheticId == _rightOrder.syntheticId,
"MATCH:NOT_CREATION"
);
// Check if it's not pool
require(!IDerivativeLogic(_derivative.syntheticId).isPool(), "MATCH:CANT_BE_POOL");
// Validate taker if set
validateTakerAddress(_leftOrder, _rightOrder);
validateTakerAddress(_rightOrder, _leftOrder);
// Validate sender if set
validateSenderAddress(_leftOrder);
validateSenderAddress(_rightOrder);
// Validate if was canceled
// orderHashes[0] - leftOrderHash
// orderHashes[1] - rightOrderHash
bytes32[2] memory orderHashes;
orderHashes[0] = hashOrder(_leftOrder);
validateNotCanceled(orderHashes[0]);
validateSignature(orderHashes[0], _leftOrder);
orderHashes[1] = hashOrder(_rightOrder);
validateNotCanceled(orderHashes[1]);
validateSignature(orderHashes[1], _rightOrder);
// Calculate derivative hash and get margin
// margins[0] - leftMargin
// margins[1] - rightMargin
(uint256[2] memory margins, ) = _calculateDerivativeAndGetMargin(_derivative);
// Calculate and validate availabilities of orders and fill them
uint256 fillable = _checkFillability(orderHashes[0], _leftOrder, orderHashes[1], _rightOrder);
// Validate derivative parameters with orders
_verifyDerivative(_leftOrder, _rightOrder, _derivative);
// Take fees
takeFees(orderHashes[0], _leftOrder);
takeFees(orderHashes[1], _rightOrder);
// Send margin to Core
_distributeFunds(_leftOrder, _rightOrder, _derivative, margins, fillable);
// Settle contracts
Core(registry.getCore()).create(_derivative, fillable, [_leftOrder.makerAddress, _rightOrder.makerAddress]);
}
// PRIVATE FUNCTIONS
/// @notice Calculates derivative hash and gets margin
/// @param _derivative Derivative
/// @return margins uint256[2] left and right margin
/// @return derivativeHash bytes32 Hash of the derivative
function _calculateDerivativeAndGetMargin(Derivative memory _derivative) private returns (uint256[2] memory margins, bytes32 derivativeHash) {
// Calculate derivative related data for validation
derivativeHash = getDerivativeHash(_derivative);
// Get cached total margin required according to logic
// margins[0] - leftMargin
// margins[1] - rightMargin
(margins[0], margins[1]) = SyntheticAggregator(registry.getSyntheticAggregator()).getMargin(derivativeHash, _derivative);
}
/// @notice Calculate and validate availabilities of orders and fill them
/// @param _leftOrderHash bytes32
/// @param _leftOrder SwaprateOrder
/// @param _rightOrderHash bytes32
/// @param _rightOrder SwaprateOrder
/// @return fillable uint256
function _checkFillability(bytes32 _leftOrderHash, SwaprateOrder memory _leftOrder, bytes32 _rightOrderHash, SwaprateOrder memory _rightOrder) private returns (uint256 fillable) {
// Calculate availabilities of orders
uint256 leftAvailable = _leftOrder.quantity.sub(filled[_leftOrderHash]);
uint256 rightAvailable = _rightOrder.quantity.sub(filled[_rightOrderHash]);
require(leftAvailable != 0 && rightAvailable !=0, "MATCH:NO_AVAILABLE");
// We could only fill minimum available of both counterparties
fillable = min(leftAvailable, rightAvailable);
// Check fillable with order conditions about partial fill requirements
if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 0) {
require(_leftOrder.quantity == _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE");
} else if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 1) {
require(_leftOrder.quantity <= rightAvailable, "MATCH:FULL_FILL_NOT_POSSIBLE");
} else if (_leftOrder.partialFill == 1 && _rightOrder.partialFill == 0) {
require(leftAvailable >= _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE");
}
// Update filled
filled[_leftOrderHash] = filled[_leftOrderHash].add(fillable);
filled[_rightOrderHash] = filled[_rightOrderHash].add(fillable);
}
/// @notice Validate derivative parameters with orders
/// @param _leftOrder SwaprateOrder
/// @param _rightOrder SwaprateOrder
/// @param _derivative Derivative
function _verifyDerivative(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) private pure {
string memory orderError = "MATCH:DERIVATIVE_PARAM_IS_WRONG";
// Validate derivative endTime
require(
_derivative.endTime == _leftOrder.endTime &&
_derivative.endTime == _rightOrder.endTime,
orderError
);
// Validate derivative syntheticId
require(
_derivative.syntheticId == _leftOrder.syntheticId &&
_derivative.syntheticId == _rightOrder.syntheticId,
orderError
);
// Validate derivative oracleId
require(
_derivative.oracleId == _leftOrder.oracleId &&
_derivative.oracleId == _rightOrder.oracleId,
orderError
);
// Validate derivative token
require(
_derivative.token == _leftOrder.token &&
_derivative.token == _rightOrder.token,
orderError
);
// Validate derivative params
require(_derivative.params.length >= 20, "MATCH:DERIVATIVE_PARAMS_LENGTH_IS_WRONG");
// Validate left order params
require(_leftOrder.param0 == _derivative.params[0], orderError);
require(_leftOrder.param1 == _derivative.params[1], orderError);
require(_leftOrder.param2 == _derivative.params[2], orderError);
require(_leftOrder.param3 == _derivative.params[3], orderError);
require(_leftOrder.param4 == _derivative.params[4], orderError);
require(_leftOrder.param5 == _derivative.params[5], orderError);
require(_leftOrder.param6 == _derivative.params[6], orderError);
require(_leftOrder.param7 == _derivative.params[7], orderError);
require(_leftOrder.param8 == _derivative.params[8], orderError);
require(_leftOrder.param9 == _derivative.params[9], orderError);
// Validate right order params
require(_rightOrder.param0 == _derivative.params[10], orderError);
require(_rightOrder.param1 == _derivative.params[11], orderError);
require(_rightOrder.param2 == _derivative.params[12], orderError);
require(_rightOrder.param3 == _derivative.params[13], orderError);
require(_rightOrder.param4 == _derivative.params[14], orderError);
require(_rightOrder.param5 == _derivative.params[15], orderError);
require(_rightOrder.param6 == _derivative.params[16], orderError);
require(_rightOrder.param7 == _derivative.params[17], orderError);
require(_rightOrder.param8 == _derivative.params[18], orderError);
require(_rightOrder.param9 == _derivative.params[19], orderError);
}
/// @notice Distributes funds to core
/// @param _leftOrder SwaprateOrder
/// @param _rightOrder SwaprateOrder
/// @param _derivative Derivative
/// @param margins uint256[2] left and right margin
/// @param _fillable uint256 How many positions are fillable
function _distributeFunds(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative, uint256[2] memory margins, uint256 _fillable) private {
IERC20 marginToken = IERC20(_derivative.token);
TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender());
// Transfer margin from left to Match and send to Core
if (margins[0] != 0) {
// Check allowance for margins
require(marginToken.allowance(_leftOrder.makerAddress, address(tokenSpender)) >= margins[0].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN");
// Transfer margins from buyer to Match
tokenSpender.claimTokens(marginToken, _leftOrder.makerAddress, address(this), margins[0].mul(_fillable));
}
// Transfer margin from right to Match and send to Core
if (margins[1] != 0) {
// Check allowance for premiums + margin
require(marginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= margins[1].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN");
// Transfer margins from seller to Match
tokenSpender.claimTokens(marginToken, _rightOrder.makerAddress, address(this), margins[1].mul(_fillable));
}
if (margins[0].add(margins[1]) != 0) {
// Approve margin to Core for derivative creation
require(marginToken.approve(address(tokenSpender), margins[0].add(margins[1]).mul(_fillable)), "MATCH:COULDNT_APPROVE_MARGIN_FOR_CORE");
}
}
}
|
Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed Check if proposal was made Check if timelock interval was passed Set new timelock and emit event Reset timelock time lock
|
function commitTimelock() public onlyGovernor {
require(timeLockProposalTime != 0, "Didn't proposed yet");
require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet");
timeLockInterval = proposedTimeLock;
emit Committed(proposedTimeLock);
timeLockProposalTime = 0;
}
| 1,368,134
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;
/// @title Campaign Factory
/// @notice A factory contract to instantiate campaigns
contract CampaignFactory {
/// @notice List of deployed campaigns
Campaign[] public deployedCampaigns;
event NewContractCreated(address contractAddress);
/// @notice Creates a new campaign and adds it to the list of deployed campaigns
/// @dev msg.sender is passed as an argument to preserve the correct sender of the transaction
/// @param minimum Minimal contribution you can make to this campaign
function createCampaign(uint256 minimum) public {
Campaign newCampaign = new Campaign(minimum, msg.sender);
deployedCampaigns.push(newCampaign);
emit NewContractCreated(address(newCampaign));
}
/// @notice Returns the list of deployed campaigns
/// @return List of deployed campaigns
function getDeployedCampaigns() public view returns (Campaign[] memory) {
return deployedCampaigns;
}
}
/// @title Campaign
/// @notice Contract with the main functionalities of a campaign
contract Campaign {
/** @dev Request struct
When the campaign owner wants to use the donated money,
he creates a request object with his intents. At least
50% of the donors need to accept this request for him to
be able to send this money to the recipient address.
This is to reduce the chances of an eventual scam.
*/
struct Request {
string description;
uint256 value;
address payable recipient;
bool complete;
uint256 approvalCount;
mapping(address => bool) approvals;
}
/// @notice List of requests
Request[] public requests;
/// @notice Campaign owner
address public manager;
/// @notice Minimum contribution accepted for this campaign
uint256 public minimumContribution;
/// @notice List of approvers
mapping(address => bool) public approvers;
/// @notice Approvers count
/// @dev Design pattern used with mapping to account for the mapping's length without iteration
uint256 public approversCount;
/// @dev Withdrawal design pattern
mapping(address => uint256) public pendingWithdrawals;
/// @dev Counter that follows life of contract balance
uint256 public balance;
event NewContribution(uint256 amount);
event NewContributor(address contributor);
event SubmittedRequestToRecipient(address recipient, uint256 amount);
event TransferComplete(address recipient, uint256 amount);
/// @notice Modifier that authorizes only a manager to perform an action
modifier restricted() {
require(msg.sender == manager, "You do not have manager privileges.");
_;
}
/// @notice Campaign constructor
/// @param minimum Minumum contribution
/// @param creator Creator of the campaign contract through the factory method
constructor(uint256 minimum, address creator) public {
manager = creator;
minimumContribution = minimum;
}
// TODO Make your voting power proportional to the amount you contributed
/// @notice Donate for a campaign
function contribute() public payable {
require(msg.value >= minimumContribution, 'The contribution amount is lower than the minimum accepted.');
/// Avoid increasing the approversCount for the same donor
if(!approvers[msg.sender]) {
approversCount++;
emit NewContributor(msg.sender);
}
approvers[msg.sender] = true;
balance += msg.value;
emit NewContribution(msg.value);
}
/// @notice Allow a campaign owner to create a request
/// @param description Description of request
/// @param value Associated value to the request
/// @param recipient Recipient of the money
function createRequest(string memory description, uint256 value, address payable recipient) public restricted {
Request memory newRequest = Request({
description: description,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
requests.push(newRequest);
}
/// @notice Allow a contributor to approve a request
/// @param index Request's id
function approveRequest(uint256 index) public {
Request storage request = requests[index];
require(approvers[msg.sender], 'You are not a contributor to this campaign.');
require(!request.approvals[msg.sender], 'You have already approved this request.');
request.approvals[msg.sender] = true;
request.approvalCount++;
}
/// @notice Transfer request value to the recipient when the majority of contirbutors approve the request
/// @param index Request's id
function finalizeRequest(uint256 index) public restricted {
Request storage request = requests[index];
require(request.value < balance, "Attempt to finalize an infeasible request");
require(request.approvalCount > (approversCount/2), 'More than 50% of the approvers must accept the request for it to pass.');
require(!request.complete, 'Request has already been completed.');
balance -= request.value;
// TODO Add Safe Math
pendingWithdrawals[request.recipient] += request.value;
request.complete = true;
emit SubmittedRequestToRecipient(request.recipient, request.value);
}
// TODO This feature might be deleted
/// @notice Cancel finalization of request
/// @param index Request's id
function cancelRequest(uint256 index) public restricted {
Request storage request = requests[index];
require(request.complete, 'Request is not complete.');
request.complete = false;
balance += request.value;
pendingWithdrawals[request.recipient] -= request.value;
// TODO reset mapping to default configuration (to be able to revote)
}
/// @notice Allow a request's recipient to withdraw value
function withdraw() public {
uint256 amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
emit TransferComplete(msg.sender, amount);
}
/// @notice Get summarized contract information
/// @return uint Minimum contribution
/// @return uint Contract balance
/// @return uint Number of requests
/// @return uint Number of contributors
/// @return uint Owner's address
function getSummary() public view returns (
uint256, uint256, uint256, uint256, address
) {
return (
minimumContribution,
address(this).balance,
requests.length,
approversCount,
manager
);
}
/// @notice Get the number of requests
/// @return Request's array length
function getRequestsCount() public view returns (uint256) {
return requests.length;
}
}
|
Transfer request value to the recipient when the majority of contirbutors approve the request index Request's id TODO Add Safe Math
|
function finalizeRequest(uint256 index) public restricted {
Request storage request = requests[index];
require(request.value < balance, "Attempt to finalize an infeasible request");
require(request.approvalCount > (approversCount/2), 'More than 50% of the approvers must accept the request for it to pass.');
require(!request.complete, 'Request has already been completed.');
balance -= request.value;
pendingWithdrawals[request.recipient] += request.value;
request.complete = true;
emit SubmittedRequestToRecipient(request.recipient, request.value);
}
| 6,454,837
|
pragma solidity ^0.5.10;
/** @title ValidateSPV*/
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
import {BTCUtils} from "./BTCUtils.sol";
library ValidateSPV {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using SafeMath for uint256;
enum InputTypes {
NONE,
LEGACY,
COMPATIBILITY,
WITNESS
}
enum OutputTypes {
NONE,
WPKH,
WSH,
OP_RETURN,
PKH,
SH,
NONSTANDARD
}
uint256 constant ERR_BAD_LENGTH =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant ERR_INVALID_CHAIN =
0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;
uint256 constant ERR_LOW_WORK =
0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;
function getErrBadLength() internal pure returns (uint256) {
return ERR_BAD_LENGTH;
}
function getErrInvalidChain() internal pure returns (uint256) {
return ERR_INVALID_CHAIN;
}
function getErrLowWork() internal pure returns (uint256) {
return ERR_LOW_WORK;
}
/// @notice Validates a tx inclusion in the block
/// @param _txid The txid (LE)
/// @param _merkleRoot The merkle root (as in the block header)
/// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)
/// @param _index The leaf's index in the tree (0-indexed)
/// @return true if fully valid, false otherwise
function prove(
bytes32 _txid,
bytes32 _merkleRoot,
bytes memory _intermediateNodes,
uint256 _index
) internal pure returns (bool) {
// Shortcut the empty-block case
if (
_txid == _merkleRoot &&
_index == 0 &&
_intermediateNodes.length == 0
) {
return true;
}
bytes memory _proof = abi.encodePacked(
_txid,
_intermediateNodes,
_merkleRoot
);
// If the Merkle proof failed, bubble up error
return _proof.verifyHash256Merkle(_index);
}
/// @notice Hashes transaction to get txid
/// @dev Supports Legacy and Witness
/// @param _version 4-bytes version
/// @param _vin Raw bytes length-prefixed input vector
/// @param _vout Raw bytes length-prefixed output vector
/// @ param _locktime 4-byte tx locktime
/// @return 32-byte transaction id, little endian
function calculateTxId(
bytes memory _version,
bytes memory _vin,
bytes memory _vout,
bytes memory _locktime
) internal pure returns (bytes32) {
// Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)
return abi.encodePacked(_version, _vin, _vout, _locktime).hash256();
}
/// @notice Parses a tx input from raw input bytes
/// @dev Supports Legacy and Witness inputs
/// @param _input Raw bytes tx input
/// @return Tx input sequence number, tx hash, and index
function parseInput(bytes memory _input)
internal
pure
returns (
uint32 _sequence,
bytes32 _hash,
uint32 _index,
uint8 _inputType
)
{
// NB: If the scriptsig is exactly 00, we are witness.
// Otherwise we are compatibility
if (_input.keccak256Slice(36, 1) != keccak256(hex"00")) {
_sequence = _input.extractSequenceLegacy();
bytes32 _witnessTag = _input.keccak256Slice(36, 3);
if (
_witnessTag == keccak256(hex"220020") ||
_witnessTag == keccak256(hex"160014")
) {
_inputType = uint8(InputTypes.COMPATIBILITY);
} else {
_inputType = uint8(InputTypes.LEGACY);
}
} else {
_sequence = _input.extractSequenceWitness();
_inputType = uint8(InputTypes.WITNESS);
}
return (
_sequence,
_input.extractInputTxId(),
_input.extractTxIndex(),
_inputType
);
}
/// @notice Parses a tx output from raw output bytes
/// @dev Differentiates by output script prefix, handles legacy and witness
/// @param _output Raw bytes tx output
/// @return Tx output value, output type, payload
function parseOutput(bytes memory _output)
internal
pure
returns (
uint64 _value,
uint8 _outputType,
bytes memory _payload
)
{
_value = _output.extractValue();
if (_output.keccak256Slice(9, 1) == keccak256(hex"6a")) {
// OP_RETURN
_outputType = uint8(OutputTypes.OP_RETURN);
_payload = _output.extractOpReturnData();
} else {
bytes32 _prefixHash = _output.keccak256Slice(8, 2);
if (_prefixHash == keccak256(hex"2200")) {
// P2WSH
_outputType = uint8(OutputTypes.WSH);
_payload = _output.slice(11, 32);
} else if (_prefixHash == keccak256(hex"1600")) {
// P2WPKH
_outputType = uint8(OutputTypes.WPKH);
_payload = _output.slice(11, 20);
} else if (_prefixHash == keccak256(hex"1976")) {
// PKH
_outputType = uint8(OutputTypes.PKH);
_payload = _output.slice(12, 20);
} else if (_prefixHash == keccak256(hex"17a9")) {
// SH
_outputType = uint8(OutputTypes.SH);
_payload = _output.slice(11, 20);
} else {
_outputType = uint8(OutputTypes.NONSTANDARD);
}
}
return (_value, _outputType, _payload);
}
/// @notice Parses a block header struct from a bytestring
/// @dev Block headers are always 80 bytes, see Bitcoin docs
/// @return Header digest, version, previous block header hash, merkle root, timestamp, target, nonce
function parseHeader(bytes memory _header)
internal
pure
returns (
bytes32 _digest,
uint32 _version,
bytes32 _prevHash,
bytes32 _merkleRoot,
uint32 _timestamp,
uint256 _target,
uint32 _nonce
)
{
// If header has an invalid length, bubble up error
if (_header.length != 80) {
return (
_digest,
_version,
_prevHash,
_merkleRoot,
_timestamp,
_target,
_nonce
);
}
_digest = abi
.encodePacked(_header.hash256())
.reverseEndianness()
.toBytes32();
_version = uint32(
_header.slice(0, 4).reverseEndianness().bytesToUint()
);
_prevHash = _header.extractPrevBlockLE().toBytes32();
_merkleRoot = _header.extractMerkleRootLE().toBytes32();
_timestamp = _header.extractTimestamp();
_target = _header.extractTarget();
_nonce = uint32(_header.slice(76, 4).reverseEndianness().bytesToUint());
return (
_digest,
_version,
_prevHash,
_merkleRoot,
_timestamp,
_target,
_nonce
);
}
/// @notice Checks validity of header chain
/// @notice Compares the hash of each header to the prevHash in the next header
/// @param _headers Raw byte array of header chain
/// @return The total accumulated difficulty of the header chain, or an error code
function validateHeaderChain(bytes memory _headers)
internal
view
returns (uint256 _totalDifficulty)
{
// Check header chain length
if (_headers.length % 80 != 0) {
return ERR_BAD_LENGTH;
}
// Initialize header start index
bytes32 _digest;
_totalDifficulty = 0;
for (uint256 _start = 0; _start < _headers.length; _start += 80) {
// ith header start index and ith header
bytes memory _header = _headers.slice(_start, 80);
// After the first header, check that headers are in a chain
if (_start != 0) {
if (!validateHeaderPrevHash(_header, _digest)) {
return ERR_INVALID_CHAIN;
}
}
// ith header target
uint256 _target = _header.extractTarget();
// Require that the header has sufficient work
_digest = _header.hash256View();
if (uint256(_digest).reverseUint256() > _target) {
return ERR_LOW_WORK;
}
// Add ith header difficulty to difficulty sum
_totalDifficulty = _totalDifficulty.add(
_target.calculateDifficulty()
);
}
}
/// @notice Checks validity of header work
/// @param _digest Header digest
/// @param _target The target threshold
/// @return true if header work is valid, false otherwise
function validateHeaderWork(bytes32 _digest, uint256 _target)
internal
pure
returns (bool)
{
if (_digest == bytes32(0)) {
return false;
}
return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() <
_target);
}
/// @notice Checks validity of header chain
/// @dev Compares current header prevHash to previous header's digest
/// @param _header The raw bytes header
/// @param _prevHeaderDigest The previous header's digest
/// @return true if header chain is valid, false otherwise
function validateHeaderPrevHash(
bytes memory _header,
bytes32 _prevHeaderDigest
) internal pure returns (bool) {
// Extract prevHash of current header
bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32();
// Compare prevHash of current header to previous header's digest
if (_prevHash != _prevHeaderDigest) {
return false;
}
return true;
}
}
|
Checks validity of header chain Compares the hash of each header to the prevHash in the next header _headers Raw byte array of header chain return The total accumulated difficulty of the header chain, or an error code Check header chain length ith header start index and ith header After the first header, check that headers are in a chain
|
function validateHeaderChain(bytes memory _headers)
internal
view
returns (uint256 _totalDifficulty)
{
if (_headers.length % 80 != 0) {
return ERR_BAD_LENGTH;
}
_totalDifficulty = 0;
for (uint256 _start = 0; _start < _headers.length; _start += 80) {
bytes memory _header = _headers.slice(_start, 80);
if (_start != 0) {
if (!validateHeaderPrevHash(_header, _digest)) {
return ERR_INVALID_CHAIN;
}
}
if (uint256(_digest).reverseUint256() > _target) {
return ERR_LOW_WORK;
}
_target.calculateDifficulty()
);
}
}
| 12,914,202
|
pragma solidity 0.5.1;
// File: contracts/lib/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Only the owner can call this function.");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/lib/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
// solhint-disable-next-line func-order
function transfer(address to, uint256 value) external returns (bool);
// solhint-disable-next-line func-order
function approve(address spender, uint256 value)
external returns (bool);
// solhint-disable-next-line func-order
function transferFrom(address from, address to, uint256 value)
external returns (bool);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/lib/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts/lib/Roles.sol
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
// File: contracts/lib/PauserRole.sol
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() public {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender), "Can only be called by pauser.");
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: contracts/lib/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused();
event Unpaused();
bool private _paused = false;
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Cannot call when paused.");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Can only call this when paused.");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused();
}
}
// File: contracts/lib/ValidatorRole.sol
contract ValidatorRole {
using Roles for Roles.Role;
event ValidatorAdded(address indexed account);
event ValidatorRemoved(address indexed account);
Roles.Role private validators;
constructor(address validator) public {
_addValidator(validator);
}
modifier onlyValidator() {
require(
isValidator(msg.sender),
"This function can only be called by a validator."
);
_;
}
function isValidator(address account) public view returns (bool) {
return validators.has(account);
}
function addValidator(address account) public onlyValidator {
_addValidator(account);
}
function renounceValidator() public {
_removeValidator(msg.sender);
}
function _addValidator(address account) internal {
validators.add(account);
emit ValidatorAdded(account);
}
function _removeValidator(address account) internal {
validators.remove(account);
emit ValidatorRemoved(account);
}
}
// File: contracts/IxtProtect.sol
/// @title IxtEvents
/// @notice Holds all events used by the IXTProtect contract
contract IxtEvents {
event MemberAdded(
address indexed memberAddress,
bytes32 indexed membershipNumber,
bytes32 indexed invitationCode
);
event StakeDeposited(
address indexed memberAddress,
bytes32 indexed membershipNumber,
uint256 stakeAmount
);
event StakeWithdrawn(
address indexed memberAddress,
uint256 stakeAmount
);
event RewardClaimed(
address indexed memberAddress,
uint256 rewardAmount
);
event InvitationRewardGiven(
address indexed memberReceivingReward,
address indexed memberGivingReward,
uint256 rewardAmount
);
event PoolDeposit(
address indexed depositer,
uint256 amount
);
event PoolWithdraw(
address indexed withdrawer,
uint256 amount
);
event AdminRemovedMember(
address indexed admin,
address indexed userAddress,
uint256 refundIssued
);
event MemberDrained(
address indexed memberAddress,
uint256 amountRefunded
);
event PoolDrained(
address indexed refundRecipient,
uint256 amountRefunded
);
event ContractDrained(
address indexed drainInitiator
);
event InvitationRewardChanged(
uint256 newInvitationReward
);
event LoyaltyRewardChanged(
uint256 newLoyaltyRewardAmount
);
}
/// @title RoleManager which inherits the Role-based functionality used
/// by the IXTProtect contract
contract RoleManager is Ownable, Pausable, ValidatorRole {
constructor(address validator)
public
ValidatorRole(validator)
{}
}
/// @title StakeManager which contains some of the stake-based state
/// used by the IXTProtect contract
contract StakeManager {
/* Function modifiers */
modifier isValidStakeLevel(StakeLevel level) {
require(
uint8(level) >= 0 && uint8(level) <= 2,
"Is not valid a staking level."
);
_;
}
/* Data types */
/// @dev The three levels of stake used within the IXTProtect platform
/// @dev Solidity enums are 0 based
enum StakeLevel { LOW, MEDIUM, HIGH }
/* Variable declarations */
/// @dev the defined staking amount for each level
uint256[3] public ixtStakingLevels;
/* Constructor */
/// @param _ixtStakingLevels the amount of stake used for each of the staking levels
/// used within the IXTProtect platform
constructor(
uint256[3] memory _ixtStakingLevels
) public {
ixtStakingLevels = _ixtStakingLevels;
}
}
/// @title RewardManager which contains some of the reward-based state
/// used by the IXTProtect contract
contract RewardManager {
/* Variable declarations */
/// @dev the reward received when inviting someone
uint256 public invitationReward;
/// @dev the period after which a member gets a loyalty reward
uint256 public loyaltyPeriodDays;
/// @dev the rate used for calculation of the loyalty reward
uint256 public loyaltyRewardAmount;
/* Constructor */
/// @param _invitationReward the amount of reward used when a member uses an invitation code
/// @param _loyaltyPeriodDays the amount of days that will be used for the loyalty period
/// @param _loyaltyRewardAmount the rate used as a loyalty reward after every loyalty period
constructor(
uint256 _invitationReward,
uint256 _loyaltyPeriodDays,
uint256 _loyaltyRewardAmount
) public {
require(
_loyaltyRewardAmount >= 0 &&
_loyaltyRewardAmount <= 100,
"Loyalty reward amount must be between 0 and 100."
);
invitationReward = _invitationReward;
loyaltyPeriodDays = _loyaltyPeriodDays;
loyaltyRewardAmount = _loyaltyRewardAmount;
}
}
/// @title IxtProtect
/// @notice Holds state and contains key logic which controls the IXTProtect platform
contract IxtProtect is IxtEvents, RoleManager, StakeManager, RewardManager {
/* Function modifiers */
modifier isNotMember(address memberAddress) {
require(
members[memberAddress].addedTimestamp == 0,
"Already a member."
);
_;
}
modifier isMember(address memberAddress) {
require(
members[memberAddress].addedTimestamp != 0,
"User is not a member."
);
_;
}
modifier notStaking(address memberAddress) {
require(
members[memberAddress].stakeTimestamp == 0,
"Member is staking already."
);
_;
}
modifier staking(address memberAddress) {
require(
members[memberAddress].stakeTimestamp != 0,
"Member is not staking."
);
_;
}
/* Data types */
/// @dev data structure used to track state on each member using the platform
struct Member {
uint256 addedTimestamp;
uint256 stakeTimestamp;
uint256 startOfLoyaltyRewardEligibility;
bytes32 membershipNumber;
bytes32 invitationCode;
uint256 stakeBalance;
uint256 invitationRewards;
uint256 previouslyAppliedLoyaltyBalance;
}
/* Variable declarations */
/// @dev the IXT ERC20 Token contract
IERC20 public ixtToken;
/// @dev a mapping from member wallet addresses to Member struct
mapping(address => Member) public members;
/// @dev the same data as `members`, but iterable
address[] public membersArray;
/// @dev the total balance of all members
uint256 public totalMemberBalance;
/// @dev the total pool balance
uint256 public totalPoolBalance;
/// @notice a mapping from invitationCode => memberAddress, so invitation rewards can be applied.
mapping(bytes32 => address) public registeredInvitationCodes;
/* Constants */
/// @dev the amount of decimals used by the IXT ERC20 token
uint256 public constant IXT_DECIMALS = 8;
/* Constructor */
/// @param _validator the address to use as the validator
/// @param _loyaltyPeriodDays the amount of days that will be used for the loyalty period
/// @param _ixtToken the address of the IXT ERC20 token to be used as stake and for rewards
/// @param _invitationReward the amount of reward used when a member uses an invitation code
/// @param _loyaltyRewardAmount the rate used as a loyalty reward after every loyalty period
/// @param _ixtStakingLevels three ascending amounts of IXT token to be used as staking levels
constructor(
address _validator,
uint256 _loyaltyPeriodDays,
address _ixtToken,
uint256 _invitationReward,
uint256 _loyaltyRewardAmount,
uint256[3] memory _ixtStakingLevels
)
public
RoleManager(_validator)
StakeManager(_ixtStakingLevels)
RewardManager(_invitationReward, _loyaltyPeriodDays, _loyaltyRewardAmount)
{
require(_ixtToken != address(0x0), "ixtToken address was set to 0.");
ixtToken = IERC20(_ixtToken);
}
/* */
/* PUBLIC FUNCTIONS */
/* */
/* (member control) */
/// @notice Registers a new user as a member after the KYC process
/// @notice This function should not add the invitationCode
/// to the mapping yet, this should only happen after join
/// @notice This function can only be called by a "validator" which is set inside the
/// constructor
/// @param _membershipNumber the membership number of the member to authorise
/// @param _memberAddress the EOA address of the member to authorise
/// @param _invitationCode should be associated with *this* member in order to apply invitation rewards
/// @param _referralInvitationCode the invitation code of another member which is used to give the
function addMember(
bytes32 _membershipNumber,
address _memberAddress,
bytes32 _invitationCode,
bytes32 _referralInvitationCode
)
public
onlyValidator
isNotMember(_memberAddress)
notStaking(_memberAddress)
{
require(
_memberAddress != address(0x0),
"Member address was set to 0."
);
Member memory member = Member({
addedTimestamp: block.timestamp,
stakeTimestamp: 0,
startOfLoyaltyRewardEligibility: 0,
membershipNumber: _membershipNumber,
invitationCode: _invitationCode,
stakeBalance: 0,
invitationRewards: 0,
previouslyAppliedLoyaltyBalance: 0
});
members[_memberAddress] = member;
membersArray.push(_memberAddress);
/// @dev add this members invitation code to the mapping
registeredInvitationCodes[member.invitationCode] = _memberAddress;
/// @dev if the _referralInvitationCode is already registered, add on reward
address rewardMemberAddress = registeredInvitationCodes[_referralInvitationCode];
if (
rewardMemberAddress != address(0x0)
) {
Member storage rewardee = members[rewardMemberAddress];
rewardee.invitationRewards = SafeMath.add(rewardee.invitationRewards, invitationReward);
emit InvitationRewardGiven(rewardMemberAddress, _memberAddress, invitationReward);
}
emit MemberAdded(_memberAddress, _membershipNumber, _invitationCode);
}
/// @notice Called by a member once they have been approved to join the scheme
/// @notice Before calling the prospective member *must* have approved the appropriate amount of
/// IXT token to be transferred by this contract
/// @param _stakeLevel the staking level used by this member. Note this is not the staking *amount*.
/// other member a reward upon *this* user joining.
function depositStake(
StakeLevel _stakeLevel
)
public
whenNotPaused()
isMember(msg.sender)
notStaking(msg.sender)
isValidStakeLevel(_stakeLevel)
{
uint256 amountDeposited = depositInternal(msg.sender, ixtStakingLevels[uint256(_stakeLevel)], false);
Member storage member = members[msg.sender];
member.stakeTimestamp = block.timestamp;
member.startOfLoyaltyRewardEligibility = block.timestamp;
/// @dev add this members invitation code to the mapping
registeredInvitationCodes[member.invitationCode] = msg.sender;
emit StakeDeposited(msg.sender, member.membershipNumber, amountDeposited);
}
/// @notice Called by the member if they wish to withdraw the stake
/// @notice This function will return all stake and eligible reward balance back to the user
function withdrawStake()
public
whenNotPaused()
staking(msg.sender)
{
uint256 stakeAmount = refundUserBalance(msg.sender);
delete registeredInvitationCodes[members[msg.sender].invitationCode];
Member storage member = members[msg.sender];
member.stakeTimestamp = 0;
member.startOfLoyaltyRewardEligibility = 0;
emit StakeWithdrawn(msg.sender, stakeAmount);
}
/// @notice Called by the member if they wish to claim the rewards they are eligible
/// @notice This function will return all eligible reward balance back to the user
function claimRewards()
public
whenNotPaused()
staking(msg.sender)
{
uint256 rewardClaimed = claimRewardsInternal(msg.sender);
emit RewardClaimed(msg.sender, rewardClaimed);
}
/* (getter functions) */
/// @notice Called in order to get the number of members on the platform
/// @return length of the members array
function getMembersArrayLength() public view returns (uint256) {
return membersArray.length;
}
/// @notice Called to obtain the account balance of any given member
/// @param memberAddress the address of the member to get the account balance for
/// @return the account balance of the member in question
function getAccountBalance(address memberAddress)
public
view
staking(memberAddress)
returns (uint256)
{
return getStakeBalance(memberAddress) +
getRewardBalance(memberAddress);
}
/// @notice Called to obtain the stake balance of any given member
/// @param memberAddress the address of the member to get the stake balance for
/// @return the stake balance of the member in question
function getStakeBalance(address memberAddress)
public
view
staking(memberAddress)
returns (uint256)
{
return members[memberAddress].stakeBalance;
}
/// @notice Called to obtain the reward balance of any given member
/// @param memberAddress the address of the member to get the total reward balance for
/// @return the total reward balance of the member in question
function getRewardBalance(address memberAddress)
public
view
staking(memberAddress)
returns (uint256)
{
return getInvitationRewardBalance(memberAddress) +
getLoyaltyRewardBalance(memberAddress);
}
/// @notice Called to obtain the invitation reward balance of any given member
/// @param memberAddress the address of the member to get the invitation reward balance for
/// @return the invitation reward balance of the member in question
function getInvitationRewardBalance(address memberAddress)
public
view
staking(memberAddress)
returns (uint256)
{
return members[memberAddress].invitationRewards;
}
/// @notice Called to obtain the loyalty reward balance of any given member
/// @param memberAddress the address of the member to get the loyalty reward balance for
/// @return the loyalty reward balance of the member in question
function getLoyaltyRewardBalance(address memberAddress)
public
view
staking(memberAddress)
returns (uint256 loyaltyReward)
{
uint256 loyaltyPeriodSeconds = loyaltyPeriodDays * 1 days;
Member storage thisMember = members[memberAddress];
uint256 elapsedTimeSinceEligible = block.timestamp - thisMember.startOfLoyaltyRewardEligibility;
loyaltyReward = thisMember.previouslyAppliedLoyaltyBalance;
if (elapsedTimeSinceEligible >= loyaltyPeriodSeconds) {
uint256 numWholePeriods = SafeMath.div(elapsedTimeSinceEligible, loyaltyPeriodSeconds);
uint256 rewardForEachPeriod = thisMember.stakeBalance * loyaltyRewardAmount / 100;
loyaltyReward += rewardForEachPeriod * numWholePeriods;
}
}
/* (admin functions) */
/// @notice Called by the admin to deposit extra IXT into the contract to be used as rewards
/// @notice This function can only be called by the contract owner
/// @param amountToDeposit the amount of IXT ERC20 token to deposit into the pool
function depositPool(uint256 amountToDeposit)
public
onlyOwner
{
uint256 amountDeposited = depositInternal(msg.sender, amountToDeposit, true);
emit PoolDeposit(msg.sender, amountDeposited);
}
/// @notice Called by the admin to withdraw IXT from the pool balance
/// @notice This function can only be called by the contract owner
/// @param amountToWithdraw the amount of IXT ERC20 token to withdraw from the pool
function withdrawPool(uint256 amountToWithdraw)
public
onlyOwner
{
if (amountToWithdraw > 0) {
require(
totalPoolBalance >= amountToWithdraw &&
ixtToken.transfer(msg.sender, amountToWithdraw),
"Unable to withdraw this value of IXT."
);
totalPoolBalance = SafeMath.sub(totalPoolBalance, amountToWithdraw);
}
emit PoolWithdraw(msg.sender, amountToWithdraw);
}
/// @notice Called by an admin to remove a member from the platform
/// @notice This function can only be called by the contract owner
/// @notice The member will be automatically refunded their stake balance and any
/// unclaimed rewards as a result of being removed by the admin
/// @notice Can be called if user is authorised *or* joined
/// @param userAddress the address of the member that the admin wishes to remove
function removeMember(address userAddress)
public
isMember(userAddress)
onlyOwner
{
uint256 refund = cancelMembershipInternal(userAddress);
emit AdminRemovedMember(msg.sender, userAddress, refund);
}
/// @notice Called by an admin in emergency situations only, will returns *ALL* stake balance
/// and reward balances back to the users. Any left over pool balance will be returned to the
/// contract owner.
/// @notice This function can only be called by the contract owner
function drain() public onlyOwner {
/// @dev Refund and delete all members
for (uint256 index = 0; index < membersArray.length; index++) {
address memberAddress = membersArray[index];
bool memberJoined = members[memberAddress].stakeTimestamp != 0;
uint256 amountRefunded = memberJoined ? refundUserBalance(memberAddress) : 0;
delete registeredInvitationCodes[members[memberAddress].invitationCode];
delete members[memberAddress];
emit MemberDrained(memberAddress, amountRefunded);
}
delete membersArray;
/// @dev Refund the pool balance
require(
ixtToken.transfer(msg.sender, totalPoolBalance),
"Unable to withdraw this value of IXT."
);
totalPoolBalance = 0;
emit PoolDrained(msg.sender, totalPoolBalance);
emit ContractDrained(msg.sender);
}
/// @notice Called by the contract owner to set the invitation reward to be given to future members
/// @notice This function does not affect previously awarded invitation rewards
/// @param _invitationReward the amount that the invitation reward should be set to
function setInvitationReward(uint256 _invitationReward)
public
onlyOwner
{
invitationReward = _invitationReward;
emit InvitationRewardChanged(_invitationReward);
}
/// @notice Called by the contract owner to set the loyalty reward rate to be given to future members
/// @notice This function does not affect previously awarded loyalty rewards
/// @notice The loyalty reward amount is actually a rate from 0 to 100 that is used to
/// calculate the proportion of stake balance that should be rewarded.
/// @param newLoyaltyRewardAmount the amount that the loyalty reward should be set to
function setLoyaltyRewardAmount(uint256 newLoyaltyRewardAmount)
public
onlyOwner
{
require(
newLoyaltyRewardAmount >= 0 &&
newLoyaltyRewardAmount <= 100,
"Loyalty reward amount must be between 0 and 100."
);
uint256 loyaltyPeriodSeconds = loyaltyPeriodDays * 1 days;
/// @dev Loop through all the current members and apply previous reward amounts
for (uint256 i = 0; i < membersArray.length; i++) {
Member storage thisMember = members[membersArray[i]];
uint256 elapsedTimeSinceEligible = block.timestamp - thisMember.startOfLoyaltyRewardEligibility;
if (elapsedTimeSinceEligible >= loyaltyPeriodSeconds) {
uint256 numWholePeriods = SafeMath.div(elapsedTimeSinceEligible, loyaltyPeriodSeconds);
uint256 rewardForEachPeriod = thisMember.stakeBalance * loyaltyRewardAmount / 100;
thisMember.previouslyAppliedLoyaltyBalance += rewardForEachPeriod * numWholePeriods;
thisMember.startOfLoyaltyRewardEligibility += numWholePeriods * loyaltyPeriodSeconds;
}
}
loyaltyRewardAmount = newLoyaltyRewardAmount;
emit LoyaltyRewardChanged(newLoyaltyRewardAmount);
}
/* */
/* INTERNAL FUNCTIONS */
/* */
function cancelMembershipInternal(address memberAddress)
internal
returns
(uint256 amountRefunded)
{
if(members[memberAddress].stakeTimestamp != 0) {
amountRefunded = refundUserBalance(memberAddress);
}
delete registeredInvitationCodes[members[memberAddress].invitationCode];
delete members[memberAddress];
removeMemberFromArray(memberAddress);
}
function refundUserBalance(
address memberAddress
)
internal
returns (uint256)
{
Member storage member = members[memberAddress];
/// @dev Pool balance will be reduced inside this function
uint256 claimsRefunded = claimRewardsInternal(memberAddress);
uint256 stakeToRefund = member.stakeBalance;
bool userStaking = member.stakeTimestamp != 0;
if (stakeToRefund > 0 && userStaking) {
require(
ixtToken.transfer(memberAddress, stakeToRefund),
"Unable to withdraw this value of IXT."
);
totalMemberBalance = SafeMath.sub(totalMemberBalance, stakeToRefund);
}
member.stakeBalance = 0;
return claimsRefunded + stakeToRefund;
}
function removeMemberFromArray(address memberAddress) internal {
/// @dev removing the member address from the membersArray
for (uint256 index; index < membersArray.length; index++) {
if (membersArray[index] == memberAddress) {
membersArray[index] = membersArray[membersArray.length - 1];
membersArray[membersArray.length - 1] = address(0);
membersArray.length -= 1;
break;
}
}
}
function claimRewardsInternal(address memberAddress)
internal
returns (uint256 rewardAmount)
{
rewardAmount = getRewardBalance(memberAddress);
if (rewardAmount == 0) {
return rewardAmount;
}
require(
totalPoolBalance >= rewardAmount,
"Pool balance not sufficient to withdraw rewards."
);
require(
ixtToken.transfer(memberAddress, rewardAmount),
"Unable to withdraw this value of IXT."
);
/// @dev we know this is safe as totalPoolBalance >= rewardAmount
totalPoolBalance -= rewardAmount;
Member storage thisMember = members[memberAddress];
thisMember.previouslyAppliedLoyaltyBalance = 0;
thisMember.invitationRewards = 0;
uint256 loyaltyPeriodSeconds = loyaltyPeriodDays * 1 days;
uint256 elapsedTimeSinceEligible = block.timestamp - thisMember.startOfLoyaltyRewardEligibility;
if (elapsedTimeSinceEligible >= loyaltyPeriodSeconds) {
uint256 numWholePeriods = SafeMath.div(elapsedTimeSinceEligible, loyaltyPeriodSeconds);
thisMember.startOfLoyaltyRewardEligibility += numWholePeriods * loyaltyPeriodSeconds;
}
}
function depositInternal(
address depositer,
uint256 amount,
bool isPoolDeposit
)
internal
returns (uint256)
{
/// @dev Explicitly checking allowance & balance before transferFrom
/// so we get the revert message.
require(amount > 0, "Cannot deposit 0 IXT.");
require(
ixtToken.allowance(depositer, address(this)) >= amount &&
ixtToken.balanceOf(depositer) >= amount &&
ixtToken.transferFrom(depositer, address(this), amount),
"Unable to deposit IXT - check allowance and balance."
);
if (isPoolDeposit) {
totalPoolBalance = SafeMath.add(totalPoolBalance, amount);
} else {
Member storage member = members[depositer];
member.stakeBalance = SafeMath.add(member.stakeBalance, amount);
totalMemberBalance = SafeMath.add(totalMemberBalance, amount);
}
return amount;
}
}
|
Called by the contract owner to set the loyalty reward rate to be given to future members This function does not affect previously awarded loyalty rewards The loyalty reward amount is actually a rate from 0 to 100 that is used to calculate the proportion of stake balance that should be rewarded. newLoyaltyRewardAmount the amount that the loyalty reward should be set to Loop through all the current members and apply previous reward amounts
|
function setLoyaltyRewardAmount(uint256 newLoyaltyRewardAmount)
public
onlyOwner
{
require(
newLoyaltyRewardAmount >= 0 &&
newLoyaltyRewardAmount <= 100,
"Loyalty reward amount must be between 0 and 100."
);
uint256 loyaltyPeriodSeconds = loyaltyPeriodDays * 1 days;
for (uint256 i = 0; i < membersArray.length; i++) {
Member storage thisMember = members[membersArray[i]];
uint256 elapsedTimeSinceEligible = block.timestamp - thisMember.startOfLoyaltyRewardEligibility;
if (elapsedTimeSinceEligible >= loyaltyPeriodSeconds) {
uint256 numWholePeriods = SafeMath.div(elapsedTimeSinceEligible, loyaltyPeriodSeconds);
uint256 rewardForEachPeriod = thisMember.stakeBalance * loyaltyRewardAmount / 100;
thisMember.previouslyAppliedLoyaltyBalance += rewardForEachPeriod * numWholePeriods;
thisMember.startOfLoyaltyRewardEligibility += numWholePeriods * loyaltyPeriodSeconds;
}
}
loyaltyRewardAmount = newLoyaltyRewardAmount;
emit LoyaltyRewardChanged(newLoyaltyRewardAmount);
}
| 12,984,235
|
./full_match/1001/0xF2AffaFa966780988f7FBdf06B6A807a1687b2c8/sources/_klaytn/contracts/KIP/token/KIP17/KIP17.sol
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals
|
function _burn(uint256 tokenId) internal virtual {
address owner = KIP17.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
| 16,364,162
|
./full_match/1/0xed6Ae5BB8B4b5777713Fe30ba74Df7FEF66e2183/sources/contracts/MyContract.sol
|
performs chained getAmountOut calculations on any number of pairs
|
function getAmountsOut(address[] memory pairsPath, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i = 0; i < path.length - 1; i++)
{
(uint reserveIn, uint reserveOut) = getReserves(pairsPath[i], path[i], path[i + 1]);
amounts[i + 1] = UniswapV2Library.getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
| 17,150,021
|
./full_match/3/0xD3fC173B7a6b8e6b965933eFA1ee4e70136687Bc/sources/contracts/Main.sol
|
Withdraw ether from this contract (Callable by owner)/
|
function withdraw() public onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
| 8,139,628
|
/**
*Submitted for verification at Etherscan.io on 2022-03-09
*/
// __ __ ______ ______ ______ _____ _____
// /\ "-./ \ /\ == \ /\__ _\ /\ __ \ /\ __-. /\ __-.
// \ \ \-./\ \ \ \ __< \/_/\ \/ \ \ \/\ \ \ \ \/\ \ \ \ \/\ \
// \ \_\ \ \_\ \ \_\ \_\ \ \_\ \ \_____\ \ \____- \ \____-
// \/_/ \/_/ \/_/ /_/ \/_/ \/_____/ \/____/ \/____/
// Message @Todd_Velorex (telegram)
// https://www.linkedin.com/in/toddbsc/
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// 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;
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
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;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
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);
/**
* @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/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
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);
}
// File: contracts/ERC721A.sol
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// 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) internal _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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_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);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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 _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_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 ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = 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)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn 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)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @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);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received(
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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* 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`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
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.
* And also called after one token has been burned.
*
* 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` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: contracts/VelorexMembersClub.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract VelorexMembersClub is ERC721A, Ownable {
using Address for address;
using MerkleProof for bytes32[];
using SafeMath for uint256;
using Strings for uint;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.1133 ether;
uint256 public whitelistCost = 0.084975 ether;
uint256 public maxSupply = 2500;
uint256 public maxMintPerWallet = 5;
uint256 public dropLimit = 500;
bool public paused = true;
mapping(address => bool) public adminRights;
mapping(address => bool) public whitelistWallets;
WhitelistData[] public whitelistData;
struct WhitelistData {
uint256 maxMintPerWallet;
uint256 price;
bytes32 merkleroot;
}
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721A(_name, _symbol) {
setBaseURI(_initBaseURI);
_safeMint(msg.sender, 15);
}
modifier whenAddressOnWhitelist(bytes32[] memory _merkleproof) {
require(MerkleProof.verify(
_merkleproof,
getPresale().merkleroot,
keccak256(abi.encodePacked(msg.sender))
),
"Not on whitelist"
);
_;
}
// internal functions
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(uint256 _amountToMint) external payable {
uint256 supply = totalSupply();
require(_amountToMint > 0, "Well, what's the point in minting nothing? ;) Please try again.");
require(supply + _amountToMint <= maxSupply, "Maximum supply reached! You'll have to buy from the secondary market!");
require(supply + _amountToMint <= dropLimit, "Sorry, you'll have to wait untill the next drop is released! Join the telegram to find out - t.me/velorex_net");
if (msg.sender != owner()){
require(_amountToMint <= maxMintPerWallet, "You can only mint 5 per transaction");
require(!paused, "Minting is currently paused");
require((_numberMinted(msg.sender) + _amountToMint) <= maxMintPerWallet, "You can't mint that many NFTs with this wallet! Check the limit please.");
if (adminRights[msg.sender] != true) {
if (whitelistWallets[msg.sender] != true) {
//full price
require(msg.value >= cost * _amountToMint, "Incorrect amount entered, try increasing the value.");
} else {
//apply discount
require(msg.value >= whitelistCost * _amountToMint, "Incorrect amount entered, try increasing the value.");
}
}
}
_safeMint(msg.sender, _amountToMint);
payable(owner()).transfer(msg.value);
}
function tokenURI(uint tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
function getPresale() private view returns (WhitelistData storage) {
return whitelistData[0];
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setDiscountedCost(uint256 _newCost) public onlyOwner {
whitelistCost = _newCost;
}
function setmaxMintPerWallet(uint256 _newmaxMintPerWallet) public onlyOwner {
maxMintPerWallet = _newmaxMintPerWallet;
}
function setDropLimit(uint256 _newDropLimit) public onlyOwner {
dropLimit = _newDropLimit;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pauseMinting(bool _state) public onlyOwner {
paused = _state;
}
function giveAdminRights(address _user) public onlyOwner {
adminRights[_user] = true;
}
function removeAdminRights(address _user) public onlyOwner {
adminRights[_user] = false;
}
function addToWhitelist(address[] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
whitelistWallets[_users[i]] = true;
}
}
function removeFromWhitelist(address _user) public onlyOwner {
whitelistWallets[_user] = false;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
}
|
full priceapply discount
|
function mint(uint256 _amountToMint) external payable {
uint256 supply = totalSupply();
require(_amountToMint > 0, "Well, what's the point in minting nothing? ;) Please try again.");
require(supply + _amountToMint <= maxSupply, "Maximum supply reached! You'll have to buy from the secondary market!");
require(supply + _amountToMint <= dropLimit, "Sorry, you'll have to wait untill the next drop is released! Join the telegram to find out - t.me/velorex_net");
if (msg.sender != owner()){
require(_amountToMint <= maxMintPerWallet, "You can only mint 5 per transaction");
require(!paused, "Minting is currently paused");
require((_numberMinted(msg.sender) + _amountToMint) <= maxMintPerWallet, "You can't mint that many NFTs with this wallet! Check the limit please.");
if (adminRights[msg.sender] != true) {
if (whitelistWallets[msg.sender] != true) {
require(msg.value >= cost * _amountToMint, "Incorrect amount entered, try increasing the value.");
require(msg.value >= whitelistCost * _amountToMint, "Incorrect amount entered, try increasing the value.");
}
}
}
_safeMint(msg.sender, _amountToMint);
payable(owner()).transfer(msg.value);
}
| 6,797,362
|
./full_match/1/0x0C8f71D19f87c0bD1b9baD2484EcC3388D5DbB98/sources/contracts/gauges/StakelessGaugeCheckpointer.sol
|
@inheritdoc IStakelessGaugeCheckpointer
|
function getSingleBridgeCost(string memory gaugeType, IStakelessGauge gauge)
external
view
override
withValidGauge(gaugeType, gauge)
returns (uint256)
{
return _getSingleBridgeCost(gauge);
}
| 16,508,160
|
pragma solidity 0.5.0;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
/**
* @title Debts Package.
* @notice Package of debts tokens to be sold on a time auction.
* @author Anibal Catalán <anibalcatalanf@gmail.com>.
*/
contract Package {
using SafeMath for uint256;
uint256 public maxRisk;
uint256 public maxFund;
uint256 public total;
uint256 public fundingPeriod;
uint256 public auctionPeriod;
uint256 public auctionFloorPrice;
uint256 public startTime;
uint256 public fundingTimeFinished;
uint256 public auctionTimeFinished;
uint256 public tokenBalance;
uint256 public finalPrice;
address public liquidityToken;
address public owner;
address public riskOracle;
mapping(address => uint256) public tokenAmount; //token->amount
mapping(address => mapping(address => uint256)) public tokenContributions; //contributor->token->amount
event LogFunded(address contributor, address token, uint256 contribution, uint256 balance);
event LogPackageFunded();
event LogPackageSold(address owner, uint256 finalPrice);
event LogCashOut(address contributor, address token, uint256 liquidity);
event LogDebtRetrieved(address contributor, address token, uint256 contribution);
event LogTokenCollected(address token, uint256 amount);
constructor(
uint256 _maxRisk,
uint256 _maxFundPercentage,
uint256 _total,
uint256 _fundingPeriod,
uint256 _auctionPeriod,
uint256 _auctionFloorPricePercentage,
address _liquidityToken,
address _riskOracle
) public {
require(_maxRisk > 0 && _maxRisk <= 100, "risk aout of range");
require(_maxFundPercentage > 0 && _maxFundPercentage <= 100, "max fund per token aut of range");
require(_fundingPeriod > 0, "invalid funding period");
require(_auctionPeriod > 0, "invalid auction period");
require(_auctionFloorPricePercentage > 0 && _auctionFloorPricePercentage <= 100, "auction floor price aout of range");
require(_liquidityToken != address(0), "invalid controller address");
require(_riskOracle != address(0), "invalid risk oracle address");
maxRisk = _maxRisk;
maxFund = _total * _maxFundPercentage / 100;
total = _total;
fundingPeriod = _fundingPeriod * 1 minutes;
auctionPeriod = _auctionPeriod * 1 minutes;
auctionFloorPrice = _total * _auctionFloorPricePercentage / 100;
startTime = now;
liquidityToken = _liquidityToken;
riskOracle = _riskOracle;
}
/**
* @notice Function controlling by the company,
* when the company see that this contract was funded with debt tokens,
* they call this function to change the state according.
* @param contributor Is who sent the debt token to this contract.
* @param token It is the debt token.
* @param contribution It how much token was send.
*/
function fund(address contributor, address token, uint256 contribution) public {
require(tokenBalance < total, "package totally funded"); // validate balance
require(now <= startTime.add(fundingPeriod) && fundingTimeFinished == 0, "out of period"); //validate funding time
//TODO: Validate risk with an external risk Oracle
require(
contribution >= IERC20(token).allowance(contributor, address(this)),
"not enough amount of tokens are allowed"
); // validate if amount of contribution is allowed
uint256 contributionAmount;
if (tokenAmount[token].add(contribution) > maxFund && tokenBalance.add(contribution) > total) {
if (tokenBalance.add(contribution).sub(total) > tokenAmount[token].add(contribution).sub(maxFund)) {
contributionAmount = total.sub(tokenBalance);
} else {
contributionAmount = maxFund.sub(tokenAmount[token]);
}
} else if (tokenBalance.add(contribution) > total) {
contributionAmount = total.sub(tokenBalance);
} else if (tokenAmount[token].add(contribution) > maxFund) {
contributionAmount = maxFund.sub(tokenAmount[token]);
} else {
contributionAmount = contribution;
}
tokenAmount[token] = tokenAmount[token].add(contributionAmount);
tokenContributions[contributor][token] = tokenContributions[contributor][token].add(contributionAmount);
tokenBalance = tokenBalance.add(contributionAmount);
if (tokenBalance == total) {
fundingTimeFinished = now;
emit LogPackageFunded();
}
require(IERC20(token).transferFrom(contributor, address(this), contributionAmount), "transfer from fail");
emit LogFunded(contributor, token, contributionAmount, tokenBalance);
}
/**
* @notice Time auction, the price of the package will decrease linearly,
* until reach the floor auction price at the end of the auction period.
* @param purchaser Who purchased the package.
*/
function auction(address purchaser) public {
finalPrice = packagePrice();
uint256 amount = IERC20(liquidityToken).allowance(purchaser, address(this));
require(amount >= finalPrice, "not enough liquidity token is allowed");
owner = purchaser;
auctionTimeFinished = now;
require(IERC20(liquidityToken).transferFrom(purchaser, address(this), finalPrice), "transfer from fail");
emit LogPackageSold(owner, finalPrice);
}
/**
* @notice Contributors can get liquidity as result of selling their debt tokens,
* this is proportional to the final package price and the debt token contribution.
* @param token Helps to identify the debt token contribution.
*/
function cashOut(address token) public {
require(auctionTimeFinished > 0, "auction is not successfully finished");
uint256 contribution = tokenContributions[msg.sender][token];
require(contribution > 0, "no contributions");
tokenContributions[msg.sender][token] = 0;
tokenAmount[token] = tokenAmount[token].sub(contribution);
uint256 liquidity = contribution.mul(finalPrice).div(total);
require(IERC20(liquidityToken).transfer(msg.sender, liquidity), "fail liquidity transfer");
emit LogCashOut(msg.sender, token, liquidity);
}
/**
* @notice Contributors can retrieve their debt tokens if the funding of the package it was not successful.
* @param token Helps to identify the debt token contribution.
*/
function retrieveDebt(address token) public {
require((now > startTime.add(fundingPeriod) && fundingTimeFinished == 0) ||
(fundingTimeFinished > 0 && now > fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0),
"funding or auction running");
uint256 contribution = tokenContributions[msg.sender][token];
require(contribution > 0, "no contributions");
tokenContributions[msg.sender][token] = 0;
tokenAmount[token] = tokenAmount[token].sub(contribution);
tokenBalance = tokenBalance.sub(contribution);
require(IERC20(token).transfer(msg.sender, contribution), "token transfer fail");
emit LogDebtRetrieved(msg.sender, token, contribution);
}
/**
* @notice Package owner can collect the debt tokens.
* @param token Helps to identify the debt token to be collect.
*/
function collectToken(address token) public {
require(auctionTimeFinished > 0, "auction is not successfully finished");
require(msg.sender == owner, "caller is not the owner");
uint256 amount = IERC20(token).balanceOf(address(this));
tokenAmount[token] = 0;
tokenBalance = tokenBalance.sub(amount);
require(IERC20(token).transfer(owner, amount), "token transfer fail");
emit LogTokenCollected(token, amount);
}
/**
* @notice Calculate the package price while the auction is running.
* @return price Package price in Wei.
*/
function packagePrice() public view returns(uint256) {
require(fundingTimeFinished > 0, "funding is not complete");
require(now <= fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0, "out of period");
uint256 linearPriceChange = total.sub(auctionFloorPrice).mul(now.sub(fundingTimeFinished)).div(auctionPeriod);
return total.sub(linearPriceChange);
}
/**
* @notice Get the amount of tokens contributed by a contributor.
* @param contributor where the contribution came from.
* @param token it is the token contributed.
* @return amount of tokens contributed.
*/
function contributions(address contributor, address token) public view returns(uint256) {
return tokenContributions[contributor][token];
}
/**
* @notice Get the amount of tokens contributed.
* @param token it is the token contributed.
* @return amount of tokens contributed.
*/
function tokens(address token) public view returns(uint256) {
return tokenAmount[token];
}
}
|
Contributors can retrieve their debt tokens if the funding of the package it was not successful. token Helps to identify the debt token contribution./
|
function retrieveDebt(address token) public {
require((now > startTime.add(fundingPeriod) && fundingTimeFinished == 0) ||
(fundingTimeFinished > 0 && now > fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0),
"funding or auction running");
uint256 contribution = tokenContributions[msg.sender][token];
require(contribution > 0, "no contributions");
tokenContributions[msg.sender][token] = 0;
tokenAmount[token] = tokenAmount[token].sub(contribution);
tokenBalance = tokenBalance.sub(contribution);
require(IERC20(token).transfer(msg.sender, contribution), "token transfer fail");
emit LogDebtRetrieved(msg.sender, token, contribution);
}
| 1,070,969
|
./full_match/1/0xA7CCd0326757C6ceE056b2c28D1571A4366152f3/sources/contracts/doodcats.sol
|
See {IERC165-supportsInterface}./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.10;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
| 4,902,851
|
// 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/ERC721Burnable.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
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;
/// @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;
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)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) 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_);
}
// transferOwnership if needed
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
/// @notice Allows to burn a tokenId
/// @dev Burns `tokenId`. See {ERC721-_burn}. The caller must own `tokenId` or be an approved operator.
/// @param tokenId the tokenId to burn
function burn(uint256 tokenId) public virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721Burnable: caller is not owner nor approved'
);
_burn(tokenId);
}
/// @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
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.9;
/// @title INiftyForge721
/// @author Simon Fremaux (@dievardump)
interface INiftyForge721 {
struct ModuleInit {
address module;
bool enabled;
bool minter;
}
/// @notice totalSupply access
function totalSupply() external view returns (uint256);
/// @notice helper to know if everyone can mint or only minters
function isMintingOpenToAll() external view returns (bool);
/// @notice Toggle minting open to all state
/// @param isOpen if the new state is open or not
function setMintingOpenToAll(bool isOpen) external;
/// @notice Mint token to `to` with `uri`
/// @param to address of recipient
/// @param uri token metadata uri
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uri[i]`
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory tokenIds);
/// @notice Mint `tokenId` to to` with `uri`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it is doing.
/// this also means, this function does not verify _maxTokenId
/// @param to address of recipient
/// @param uri token metadata uri
/// @param tokenId token id wanted
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
uint256 tokenId_,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uris[i]`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it's doing.
/// this also means, this function does not verify _maxTokenId
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param tokenIds array of token ids wanted
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
uint256[] memory tokenIds,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory);
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
/// @param canModuleMint if the module has to be given the minter role
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
/// @dev Allows owner to enable a module
/// @param module to enable
/// @param canModuleMint if the module has to be given the minter role
function enableModule(address module, bool canModuleMint) external;
/// @dev Allows owner to disable a module
/// @param module to disable
function disableModule(address module, bool keepListeners) external;
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
interface INFModule is IERC165 {
/// @notice Called by a Token Registry whenever the module is Attached
/// @return if the attach worked
function onAttach() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Enabled
/// @return if the enabling worked
function onEnable() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Disabled
function onDisable() external;
/// @notice returns an URI with information about the module
/// @return the URI where to find information about the module
function contractURI() external view returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleRenderTokenURI is INFModule {
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
function renderTokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleTokenURI is INFModule {
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleWithRoyalties is INFModule {
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param registry registry to check id of
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(address registry, uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import './INFModule.sol';
/// @title NFBaseModule
/// @author Simon Fremaux (@dievardump)
contract NFBaseModule is INFModule, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet internal _attached;
event NewContractURI(string contractURI);
string private _contractURI;
modifier onlyAttached(address registry) {
require(_attached.contains(registry), '!NOT_ATTACHED!');
_;
}
constructor(string memory contractURI_) {
_setContractURI(contractURI_);
}
/// @inheritdoc INFModule
function contractURI()
external
view
virtual
override
returns (string memory)
{
return _contractURI;
}
/// @inheritdoc INFModule
function onAttach() external virtual override returns (bool) {
if (_attached.add(msg.sender)) {
return true;
}
revert('!ALREADY_ATTACHED!');
}
/// @notice this contract doesn't really care if it's enabled or not
/// since trying to mint on a contract where it's not enabled will fail
/// @inheritdoc INFModule
function onEnable() external pure virtual override returns (bool) {
return true;
}
/// @inheritdoc INFModule
function onDisable() external virtual override {}
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
emit NewContractURI(contractURI_);
}
}
//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.9;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../NiftyForge/INiftyForge721.sol';
import '../NiftyForge/Modules/NFBaseModule.sol';
import '../NiftyForge/Modules/INFModuleTokenURI.sol';
import '../NiftyForge/Modules/INFModuleRenderTokenURI.sol';
import '../NiftyForge/Modules/INFModuleWithRoyalties.sol';
import '../v2/AstragladeUpgrade.sol';
import '../ERC2981/IERC2981Royalties.sol';
import '../libraries/Randomize.sol';
import '../libraries/Base64.sol';
/// @title PlanetsModule
/// @author Simon Fremaux (@dievardump)
contract PlanetsModule is
Ownable,
NFBaseModule,
INFModuleTokenURI,
INFModuleRenderTokenURI,
INFModuleWithRoyalties
{
// using ECDSA for bytes32;
using Strings for uint256;
using Randomize for Randomize.Random;
uint256 constant SEED_BOUND = 1000000000;
// emitted when planets are claimed
event PlanetsClaimed(uint256[] tokenIds);
// contract actually holding the planets
address public planetsContract;
// astraglade contract to claim ids from
address public astragladeContract;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// project base render URI
string private _baseRenderURI;
// whenever all images are uploaded on arweave/ipfs and
// this flag allows to stop all update of images, scripts etc...
bool public frozenMeta;
// base image rendering URI
// before all Planets are minted, images will be stored on our servers since
// they need to be generated after minting
// after all planets are minted, they will all be stored in a decentralized way
// and the _baseImagesURI will be updated
string private _baseImagesURI;
// project description
string internal _description;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
mapping(uint256 => bytes32) public planetSeed;
// saving already taken seeds to ensure not reusing a seed
mapping(uint256 => bool) public seedTaken;
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @notice constructor
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
/// @param astragladeContract_ the contract holding the astraglades
constructor(
string memory contractURI_,
address owner_,
address planetsContract_,
address astragladeContract_
) NFBaseModule(contractURI_) {
planetsContract = planetsContract_;
astragladeContract = astragladeContract_;
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(INFModuleTokenURI).interfaceId ||
interfaceId == type(INFModuleRenderTokenURI).interfaceId ||
interfaceId == type(INFModuleWithRoyalties).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(uint256 tokenId)
public
view
override
returns (address, uint256)
{
return royaltyInfo(msg.sender, tokenId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(address, uint256)
public
view
override
returns (address receiver, uint256 basisPoint)
{
receiver = address(this);
basisPoint = 1000;
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return tokenURI(msg.sender, tokenId);
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return
string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
abi.encodePacked(
'{"name":"Planet - ',
tokenId.toString(),
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"',
abi.encodePacked(
getBaseImageURI(),
tokenId.toString()
),
'","seed":"',
seed.toString(),
abi.encodePacked(
'","astragladeSeed":"',
astragladeSeed.toString(),
'","attributes":[',
_generateJSONAttributes(attributes),
'],"animation_url":"',
_renderTokenURI(
seed,
astragladeSeed,
attributes
),
'"}'
)
)
)
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return renderTokenURI(msg.sender, tokenId);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return _renderTokenURI(seed, astragladeSeed, attributes);
}
/// @notice Helper returning all data for a Planet
/// @param tokenId the planet id
/// @return the planet seed, the astraglade seed and the planet attributes (the integer form)
function getPlanetData(uint256 tokenId)
public
view
returns (
uint256,
uint256,
uint256[] memory
)
{
require(planetSeed[tokenId] != 0, '!UNKNOWN_TOKEN!');
uint256 seed = uint256(planetSeed[tokenId]) % SEED_BOUND;
uint256[] memory attributes = _getAttributes(seed);
AstragladeUpgrade.AstragladeMeta memory astraglade = AstragladeUpgrade(
payable(astragladeContract)
).getAstraglade(tokenId);
return (seed, astraglade.seed, attributes);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeUpgrade.AstragladeMeta memory astraglade)
{
return
AstragladeUpgrade(payable(astragladeContract)).getAstraglade(
tokenId
);
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
"Astraglade Planets is an extension of project Astraglade (https://nurecas.com/astraglade). Planets are an interactive and generative 3D art that can be minted for free by anyone who owns an astraglade at [https://astraglade.beyondnft.io/planets/](https://astraglade.beyondnft.io/planets/). When a Planet is minted, the owner's astraglade will orbit forever around the planet that they mint.";
}
return _description;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ar://JYtFvtxlpyur2Cdpaodmo46XzuTpmp0OwJl13rFUrrg/';
}
return _baseRenderURI;
}
/// @notice helper to get the baseImageURI
function getBaseImageURI() public view returns (string memory) {
if (bytes(_baseImagesURI).length == 0) {
return 'https://astraglade-api.beyondnft.io/planets/images/';
}
return _baseImagesURI;
}
/// @inheritdoc INFModule
function onAttach()
external
virtual
override(INFModule, NFBaseModule)
returns (bool)
{
// only the first attach is accepted, saves a "setPlanetsContract" call
if (planetsContract == address(0)) {
planetsContract = msg.sender;
return true;
}
return false;
}
/// @notice Claim tokenIds[] from the astraglade contract
/// @param tokenIds the tokenIds to claim
function claim(uint256[] calldata tokenIds) external {
address operator = msg.sender;
// saves some reads
address astragladeContract_ = astragladeContract;
address planetsContract_ = planetsContract;
for (uint256 i; i < tokenIds.length; i++) {
_claim(
operator,
tokenIds[i],
astragladeContract_,
planetsContract_
);
}
}
/// @notice Allows to freeze any metadata update
function freezeMeta() external onlyOperator {
frozenMeta = true;
}
/// @notice sets contract uri
/// @param newURI the new uri
function setContractURI(string memory newURI) external onlyOperator {
_setContractURI(newURI);
}
/// @notice sets planets contract
/// @param planetsContract_ the contract containing planets
function setPlanetsContract(address planetsContract_)
external
onlyOperator
{
planetsContract = planetsContract_;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_description = newDescription;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseRenderURI = newRenderURI;
}
/// @notice helper to set the baseImageURI
/// @param newBaseImagesURI the new base image URI
function setBaseImagesURI(string memory newBaseImagesURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseImagesURI = newBaseImagesURI;
}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, '!INDEX_OVERFLOW!');
require(newFeeRecipient != address(0), '!INVALID_ADDRESS!');
feeRecipients[index] = newFeeRecipient;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @dev Allows to claim a tokenId; the Planet will always be minted to the owner of the Astraglade
/// @param operator the one launching the claim (needs to be owner or approved on the Astraglade)
/// @param tokenId the Astraglade tokenId to claim
/// @param astragladeContract_ the Astraglade contract to check ownership
/// @param planetsContract_ the Planet contract (where to mint the tokens)
function _claim(
address operator,
uint256 tokenId,
address astragladeContract_,
address planetsContract_
) internal {
AstragladeUpgrade astraglade = AstragladeUpgrade(
payable(astragladeContract_)
);
address owner_ = astraglade.ownerOf(tokenId);
// verify that the operator has the right to claim
require(
owner_ == operator ||
astraglade.isApprovedForAll(owner_, operator) ||
astraglade.getApproved(tokenId) == operator,
'!NOT_AUTHORIZED!'
);
// mint
INiftyForge721 planets = INiftyForge721(planetsContract_);
// always mint to owner_, not to operator
planets.mint(owner_, '', tokenId, address(0), 0, address(0));
// creates a seed
bytes32 seed;
do {
seed = _generateSeed(
tokenId,
block.timestamp,
owner_,
blockhash(block.number - 1)
);
} while (seedTaken[uint256(seed) % SEED_BOUND]);
planetSeed[tokenId] = seed;
// ensure we won't have two seeds rendering the same planet
seedTaken[uint256(seed) % SEED_BOUND] = true;
}
/// @dev Calculate next seed using a few on chain data
/// @param tokenId tokenId
/// @param timestamp current block timestamp
/// @param operator current operator
/// @param blockHash last block hash
/// @return a new bytes32 seed
function _generateSeed(
uint256 tokenId,
uint256 timestamp,
address operator,
bytes32 blockHash
) internal view returns (bytes32) {
return
keccak256(
abi.encodePacked(
tokenId,
timestamp,
operator,
blockHash,
block.coinbase,
block.difficulty,
tx.gasprice
)
);
}
/// @notice generates the attributes values according to seed
/// @param seed the seed to generate the values
/// @return attributes an array of attributes (integers)
function _getAttributes(uint256 seed)
internal
pure
returns (uint256[] memory attributes)
{
Randomize.Random memory random = Randomize.Random({seed: seed});
// remember, all numbers returned by randomBetween are
// multiplicated by 1000, because solidity has no decimals
// so we will divide all those numbers later
attributes = new uint256[](6);
// density
attributes[0] = random.randomBetween(10, 200);
// radius
attributes[1] = random.randomBetween(5, 15);
// cube planet
attributes[2] = random.randomBetween(0, 5000);
if (attributes[2] < 20000) {
// set radius = 10 if cube
attributes[1] = 10000;
}
// shade - remember to actually change 1 into -1 in the HTML
attributes[3] = random.randomBetween(0, 2) < 1000 ? 0 : 1;
// rings
// if cube, 2 or 3 rings
if (attributes[2] < 20000) {
attributes[4] = random.randomBetween(2, 4) / 1000;
} else {
// else 30% chances to have rings (1, 2 and 3)
attributes[4] = random.randomBetween(0, 10) / 1000;
// if more than 3, then none.
if (attributes[4] > 3) {
attributes[4] = 0;
}
}
// moons, 0, 1, 2 or 3
attributes[5] = random.randomBetween(0, 4) / 1000;
}
/// @notice Generates the JSON string from the attributes values
/// @param attributes the attributes values
/// @return jsonAttributes, the string for attributes
function _generateJSONAttributes(uint256[] memory attributes)
internal
pure
returns (string memory)
{
bytes memory coma = bytes(',');
// Terrain
bytes memory jsonAttributes = abi.encodePacked(
_makeAttributes(
'Terrain',
attributes[0] < 50000 ? 'Dense' : 'Sparse'
),
coma
);
// Size
if (attributes[1] < 8000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Tiny'),
coma
);
} else if (attributes[1] < 12000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Medium'),
coma
);
} else {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Giant'),
coma
);
}
// Form
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes(
'Form',
attributes[2] < 20000 ? 'Tesseract' : 'Geo'
),
coma,
_makeAttributes('Shade', attributes[3] == 0 ? 'Vibrant' : 'Simple'),
coma,
_makeAttributes('Rings', attributes[4].toString()),
coma,
_makeAttributes('Moons', attributes[5].toString())
);
return string(jsonAttributes);
}
function _makeAttributes(string memory name_, string memory value)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
'{"trait_type":"',
name_,
'","value":"',
value,
'"}'
);
}
/// @notice returns the URL to render the Planet
/// @param seed the planet seed
/// @param astragladeSeed the astraglade seed
/// @param attributes all attributes needed for the planets
/// @return the URI to render the planet
function _renderTokenURI(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) internal view returns (string memory) {
bytes memory coma = bytes(',');
bytes memory attrs = abi.encodePacked(
attributes[0].toString(),
coma,
attributes[1].toString(),
coma,
attributes[2].toString(),
coma
);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
seed.toString(),
'&astragladeSeed=',
astragladeSeed.toString(),
'&attributes=',
abi.encodePacked(
attrs,
attributes[3].toString(),
coma,
attributes[4].toString(),
coma,
attributes[5].toString()
)
)
);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
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;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// small library to randomize using (min, max, seed)
// all number returned are considered with 3 decimals
library Randomize {
struct Random {
uint256 seed;
}
/// @notice This function uses seed to return a pseudo random interger between 0 and 1000
/// Because solidity has no decimal points, the number is considered to be [0, 0.999]
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomDec(Random memory random) internal pure returns (uint256) {
random.seed ^= random.seed << 13;
random.seed ^= random.seed >> 17;
random.seed ^= random.seed << 5;
return ((random.seed < 0 ? ~random.seed + 1 : random.seed) % 1000);
}
/// @notice return a number between [min, max[, multiplicated by 1000 (for 3 decimal basis)
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomBetween(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256) {
return min * 1000 + (max - min) * Randomize.randomDec(random);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../ERC721Ownable.sol';
import '../ERC2981/IERC2981Royalties.sol';
import './IOldMetaHolder.sol';
/// @title AstragladeUpgrade
/// @author Simon Fremaux (@dievardump)
contract AstragladeUpgrade is
IERC2981Royalties,
ERC721Ownable,
IERC721Receiver
{
using ECDSA for bytes32;
using Strings for uint256;
// emitted when an Astraglade has been upgrade
event AstragladeUpgraded(address indexed operator, uint256 indexed tokenId);
// emitted when a token owner asks for a metadata update (image or signature)
// because of rendering error
event RequestUpdate(address indexed operator, uint256 indexed tokenId);
struct MintingOrder {
address to;
uint256 expiration;
uint256 seed;
string signature;
string imageHash;
}
struct AstragladeMeta {
uint256 seed;
string signature;
string imageHash;
}
// start at the old contract last token Id minted
uint256 public lastTokenId = 84;
// signer that signs minting orders
address public mintSigner;
// how long before an order expires
uint256 public expiration;
// old astraglade contract to allow upgrade to new token
address public oldAstragladeContract;
// contract that holds metadata of previous contract Astraglades
address public oldMetaHolder;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// max supply
uint256 constant MAX_SUPPLY = 5555;
// price
uint256 constant PRICE = 0.0888 ether;
// project base render URI
string private _baseRenderURI;
// project description
string internal _description;
// list of Astraglades
mapping(uint256 => AstragladeMeta) internal _astraglades;
// saves if a minting order was already used or not
mapping(bytes32 => uint256) public messageToTokenId;
// request updates
mapping(uint256 => bool) public requestUpdates;
// remaining giveaways
uint256 public remainingGiveaways = 100;
// user giveaways
mapping(address => uint8) public giveaways;
// Petri already redeemed
mapping(uint256 => bool) public petriRedeemed;
address public artBlocks;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @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 mintSigner_ Address of the wallet used to sign minting orders
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address mintSigner_,
address owner_,
address oldAstragladeContract_,
address oldMetaHolder_,
address artBlocks_
)
ERC721Ownable(
name_,
symbol_,
contractURI_,
openseaProxyRegistry_,
owner_
)
{
mintSigner = mintSigner_;
oldAstragladeContract = oldAstragladeContract_;
oldMetaHolder = oldMetaHolder_;
artBlocks = artBlocks_;
}
/// @notice Mint one token using a minting order
/// @dev mintingSignature must be a signature that matches `mintSigner` for `mintingOrder`
/// @param mintingOrder the minting order
/// @param mintingSignature signature for the mintingOrder
/// @param petriId petri id to redeem if owner and not already redeemed the free AG
function mint(
MintingOrder memory mintingOrder,
bytes memory mintingSignature,
uint256 petriId
) external payable {
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
address sender = msg.sender;
require(
message.recover(mintingSignature) == mintSigner,
'Wrong minting order signature.'
);
require(
mintingOrder.expiration >= block.timestamp,
'Minting order expired.'
);
require(
mintingOrder.to == sender,
'Minting order for another address.'
);
require(mintingOrder.seed != 0, 'Seed can not be 0');
require(messageToTokenId[message] == 0, 'Token already minted.');
uint256 tokenId = lastTokenId + 1;
require(tokenId <= MAX_SUPPLY, 'Max supply already reached.');
uint256 mintingCost = PRICE;
// For Each Petri (https://artblocks.io/project/67/) created by Fabin on artblocks.io
// the owner can claim a free Astraglade
// After a Petri was used, it CAN NOT be used again to claim another Astraglade
if (petriId >= 67000000 && petriId < 67000200) {
require(
// petri was not redeemed already
petriRedeemed[petriId] == false &&
// msg.sender is Petri owner
ERC721(artBlocks).ownerOf(petriId) == sender,
'Petri already redeemed or not owner'
);
petriRedeemed[petriId] = true;
mintingCost = 0;
} else if (giveaways[sender] > 0) {
// if the user has some free mints
giveaways[sender]--;
mintingCost = 0;
}
require(
msg.value == mintingCost || isOperator(sender),
'Incorrect value.'
);
lastTokenId = tokenId;
messageToTokenId[message] = tokenId;
_astraglades[tokenId] = AstragladeMeta({
seed: mintingOrder.seed,
signature: mintingOrder.signature,
imageHash: mintingOrder.imageHash
});
_safeMint(mintingOrder.to, tokenId, '');
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
ERC721Enumerable.supportsInterface(interfaceId) ||
interfaceId == type(IERC2981Royalties).interfaceId;
}
/// @notice Helper to get the price
/// @return the price to mint
function getPrice() external pure returns (uint256) {
return PRICE;
}
/// @notice tokenURI override that returns a data:json application
/// @inheritdoc ERC721
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
string memory astraType;
if (tokenId <= 10) {
astraType = 'Universa';
} else if (tokenId <= 100) {
astraType = 'Galactica';
} else if (tokenId <= 1000) {
astraType = 'Nebula';
} else if (tokenId <= 2500) {
astraType = 'Meteora';
} else if (tokenId <= 5554) {
astraType = 'Solaris';
} else {
astraType = 'Quanta';
}
return
string(
abi.encodePacked(
'data:application/json;utf8,{"name":"Astraglade - ',
tokenId.toString(),
' - ',
astraType,
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"ipfs://ipfs/',
astraglade.imageHash,
'","seed":"',
astraglade.seed.toString(),
'","signature":"',
astraglade.signature,
'","animation_url":"',
renderTokenURI(tokenId),
'"}'
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
astraglade.seed.toString(),
'&signature=',
astraglade.signature
)
);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeMeta memory astraglade)
{
require(_exists(tokenId), 'Astraglade: nonexistent token');
// if the metadata are in this contract
if (_astraglades[tokenId].seed != 0) {
astraglade = _astraglades[tokenId];
} else {
// or in the old one
(
uint256 seed,
string memory signature,
string memory imageHash
) = IOldMetaHolder(oldMetaHolder).get(tokenId);
astraglade.seed = seed;
astraglade.signature = signature;
astraglade.imageHash = imageHash;
}
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
'Astraglade is an interactive, generative, 3D collectible project. Astraglades are collected through a unique social collection mechanism. Each version of Astraglade can be signed with a signature which will remain in the artwork forever.';
}
return _description;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
_description = newDescription;
}
/// @notice helper to get the base expiration time
function getExpiration() public view returns (uint256) {
if (expiration == 0) {
return 15 * 60;
}
return expiration;
}
/// @notice helper to set the expiration
/// @param newExpiration the new expiration
function setExpiration(uint256 newExpiration) external onlyOperator {
expiration = newExpiration;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ipfs://ipfs/QmP85DSrtLAxSBnct9iUr7qNca43F3E4vuG6Jv5aoTh9w7';
}
return _baseRenderURI;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
_baseRenderURI = newRenderURI;
}
/// @notice Helper to do giveaways - there can only be `remainingGiveaways` giveaways given all together
/// @param winner the giveaway winner
/// @param count how many we giveaway to recipient
function giveaway(address winner, uint8 count) external onlyOperator {
require(remainingGiveaways >= count, 'Giveaway limit reached');
remainingGiveaways -= count;
giveaways[winner] += count;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, 'Index too high.');
require(newFeeRecipient != address(0), 'Invalid address.');
feeRecipients[index] = newFeeRecipient;
}
/// @notice 10% royalties going to this contract
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = address(this);
royaltyAmount = (value * 1000) / 10000;
}
/// @notice Hash the Minting Order so it can be signed by the signer
/// @param mintingOrder the minting order
/// @return the hash to sign
function hashMintingOrder(MintingOrder memory mintingOrder)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(mintingOrder));
}
/// @notice Helper for the owner to change current minting signer
/// @dev needs to be owner
/// @param mintSigner_ new signer
function setMintingSigner(address mintSigner_) external onlyOperator {
require(mintSigner_ != address(0), 'Invalid Signer address.');
mintSigner = mintSigner_;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @notice Helper for the owner to change the oldMetaHolder
/// @dev needs to be owner
/// @param oldMetaHolder_ new oldMetaHolder address
function setOldMetaHolder(address oldMetaHolder_) external onlyOperator {
require(oldMetaHolder_ != address(0), 'Invalid Contract address.');
oldMetaHolder = oldMetaHolder_;
}
/// @notice Helpers that returns the MintingOrder plus the message to sign
/// @param to the address of the creator
/// @param seed the seed
/// @param signature the signature
/// @param imageHash image hash
/// @return mintingOrder and message to hash
function createMintingOrder(
address to,
uint256 seed,
string memory signature,
string memory imageHash
)
external
view
returns (MintingOrder memory mintingOrder, bytes32 message)
{
mintingOrder = MintingOrder({
to: to,
expiration: block.timestamp + getExpiration(),
seed: seed,
signature: signature,
imageHash: imageHash
});
message = hashMintingOrder(mintingOrder);
}
/// @notice returns a tokenId from an mintingOrder, used to know if already minted
/// @param mintingOrder the minting order to check
/// @return an integer. 0 if not minted, else the tokenId
function tokenIdFromOrder(MintingOrder memory mintingOrder)
external
view
returns (uint256)
{
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
return messageToTokenId[message];
}
/// @notice Allows an owner to request a metadata update.
/// Because Astraglade are generated from a backend it can happen that a bug
/// blocks the generation of the image OR that a signature with special characters stops the
/// token from working.
/// This method allows a user to ask for regeneration of the image / signature update
/// A contract operator can then update imageHash and / or signature
/// @param tokenId the tokenId to update
function requestMetaUpdate(uint256 tokenId) external {
require(ownerOf(tokenId) == msg.sender, 'Not token owner.');
requestUpdates[tokenId] = true;
emit RequestUpdate(msg.sender, tokenId);
}
/// @notice Allows an operator of this contract to update a tokenId metadata (signature or image hash)
/// after it was requested by its owner.
/// This is only used in the case the generation of the Preview image did fail
/// in some way or if the signature has special characters that stops the token from working
/// @param tokenId the tokenId to update
/// @param newImageHash the new imageHash (can be empty)
/// @param newSignature the new signature (can be empty)
function updateMeta(
uint256 tokenId,
string memory newImageHash,
string memory newSignature
) external onlyOperator {
require(
requestUpdates[tokenId] == true,
'No update request for token.'
);
requestUpdates[tokenId] = false;
// get the current Astraglade data
// for ids 1-82 it can come from oldMetaHolder
AstragladeMeta memory astraglade = getAstraglade(tokenId);
if (bytes(newImageHash).length > 0) {
astraglade.imageHash = newImageHash;
}
if (bytes(newSignature).length > 0) {
astraglade.signature = newSignature;
}
// save the new state
_astraglades[tokenId] = astraglade;
}
/// @notice function used to allow upgrade of old contract Astraglade to this one.
/// @inheritdoc IERC721Receiver
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
require(msg.sender == oldAstragladeContract, 'Only old Astraglades.');
// mint tokenId to from
_mint(from, tokenId);
// burn old tokenId
ERC721Burnable(msg.sender).burn(tokenId);
emit AstragladeUpgraded(from, tokenId);
return 0x150b7a02;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IOldMetaHolder
/// @author Simon Fremaux (@dievardump)
interface IOldMetaHolder {
function get(uint256 tokenId)
external
pure
returns (
uint256,
string memory,
string memory
);
}
|
helper to set the fee recipient at `index` newFeeRecipient the new address index the index to edit
|
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, '!INDEX_OVERFLOW!');
require(newFeeRecipient != address(0), '!INVALID_ADDRESS!');
feeRecipients[index] = newFeeRecipient;
}
| 164,150
|
./partial_match/1/0x77a13ccd9B3983ee24513f0845c8deffC1874E12/sources/TigerQueen.sol
|
Emergency withdraw for tokens left in contract /
|
function claimToken(address tokenAddress, uint256 amount) external onlyOwner {
IERC20(tokenAddress).transfer(owner(), amount);
}
| 15,945,411
|
pragma solidity 0.8.10;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import "../../interfaces/IERC20.sol";
import "../../interfaces/IERC20Template.sol";
import "../../interfaces/IFactoryRouter.sol";
import "OpenZeppelin/openzeppelin-contracts@4.2.0/contracts/utils/math/SafeMath.sol";
import "../../utils/SafeERC20.sol";
import "OpenZeppelin/openzeppelin-contracts@4.2.0/contracts/security/ReentrancyGuard.sol";
/**
* @title FixedRateExchange
* @dev FixedRateExchange is a fixed rate exchange Contract
* Marketplaces uses this contract to allow consumers
* exchanging datatokens with ocean token using a fixed
* exchange rate.
*/
contract FixedRateExchange is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant BASE = 10**18;
uint public constant MIN_FEE = BASE / 10**4;
uint public constant MAX_FEE = BASE / 10;
uint public constant MIN_RATE = 10 ** 10;
address public router;
address public opcCollector;
struct Exchange {
bool active;
address exchangeOwner;
address datatoken;
address baseToken;
uint256 fixedRate;
uint256 dtDecimals;
uint256 btDecimals;
uint256 dtBalance;
uint256 btBalance;
uint256 marketFee;
address marketFeeCollector;
uint256 marketFeeAvailable;
uint256 oceanFeeAvailable;
bool withMint;
address allowedSwapper;
}
// maps an exchangeId to an exchange
mapping(bytes32 => Exchange) private exchanges;
bytes32[] private exchangeIds;
modifier onlyActiveExchange(bytes32 exchangeId) {
require(
//exchanges[exchangeId].fixedRate != 0 &&
exchanges[exchangeId].active,
"FixedRateExchange: Exchange does not exist!"
);
_;
}
modifier onlyExchangeOwner(bytes32 exchangeId) {
require(
exchanges[exchangeId].exchangeOwner == msg.sender,
"FixedRateExchange: invalid exchange owner"
);
_;
}
modifier onlyRouter() {
require(msg.sender == router, "FixedRateExchange: only router");
_;
}
event ExchangeCreated(
bytes32 indexed exchangeId,
address indexed baseToken,
address indexed datatoken,
address exchangeOwner,
uint256 fixedRate
);
event ExchangeRateChanged(
bytes32 indexed exchangeId,
address indexed exchangeOwner,
uint256 newRate
);
//triggered when the withMint state is changed
event ExchangeMintStateChanged(
bytes32 indexed exchangeId,
address indexed exchangeOwner,
bool withMint
);
event ExchangeActivated(
bytes32 indexed exchangeId,
address indexed exchangeOwner
);
event ExchangeDeactivated(
bytes32 indexed exchangeId,
address indexed exchangeOwner
);
event ExchangeAllowedSwapperChanged(
bytes32 indexed exchangeId,
address indexed allowedSwapper
);
event Swapped(
bytes32 indexed exchangeId,
address indexed by,
uint256 baseTokenSwappedAmount,
uint256 datatokenSwappedAmount,
address tokenOutAddress,
uint256 marketFeeAmount,
uint256 oceanFeeAmount,
uint256 consumeMarketFeeAmount
);
event TokenCollected(
bytes32 indexed exchangeId,
address indexed to,
address indexed token,
uint256 amount
);
event OceanFeeCollected(
bytes32 indexed exchangeId,
address indexed feeToken,
uint256 feeAmount
);
event MarketFeeCollected(
bytes32 indexed exchangeId,
address indexed feeToken,
uint256 feeAmount
);
// emited for fees sent to consumeMarket
event ConsumeMarketFee(
bytes32 indexed exchangeId,
address to,
address token,
uint256 amount);
event SWAP_FEES(
bytes32 indexed exchangeId,
uint oceanFeeAmount,
uint marketFeeAmount,
uint consumeMarketFeeAmount,
address tokenFeeAddress);
event PublishMarketFeeChanged(
bytes32 indexed exchangeId,
address caller,
address newMarketCollector,
uint256 swapFee);
constructor(address _router, address _opcCollector) {
require(_router != address(0), "FixedRateExchange: Wrong Router address");
require(_opcCollector != address(0), "FixedRateExchange: Wrong OPC address");
router = _router;
opcCollector = _opcCollector;
}
/**
* @dev getId
* Return template id in case we need different ABIs.
* If you construct your own template, please make sure to change the hardcoded value
*/
function getId() pure public returns (uint8) {
return 1;
}
function getOPCFee(address baseTokenAddress) public view returns (uint) {
return IFactoryRouter(router).getOPCFee(baseTokenAddress);
}
/**
* @dev create
* creates new exchange pairs between a baseToken
* (ocean token) and datatoken.
* datatoken refers to a datatoken contract address
* addresses - array of addresses with the following struct:
* [0] - baseToken
* [1] - owner
* [2] - marketFeeCollector
* [3] - allowedSwapper - if != address(0), only that is allowed to swap (used for ERC20Enterprise)
* uints - array of uints with the following struct:
* [0] - baseTokenDecimals
* [1] - datatokenDecimals
* [2] - fixedRate
* [3] - marketFee
* [4] - withMint
*/
function createWithDecimals(
address datatoken,
address[] memory addresses,
uint256[] memory uints
) external onlyRouter returns (bytes32 exchangeId) {
require(
addresses[0] != address(0),
"FixedRateExchange: Invalid baseToken, zero address"
);
require(
datatoken != address(0),
"FixedRateExchange: Invalid datatoken, zero address"
);
require(
addresses[0] != datatoken,
"FixedRateExchange: Invalid datatoken, equals baseToken"
);
require(
uints[2] >= MIN_RATE,
"FixedRateExchange: Invalid exchange rate value"
);
exchangeId = generateExchangeId(addresses[0], datatoken, addresses[1]);
require(
exchanges[exchangeId].fixedRate == 0,
"FixedRateExchange: Exchange already exists!"
);
bool withMint=true;
if(uints[4] == 0) withMint = false;
exchanges[exchangeId] = Exchange({
active: true,
exchangeOwner: addresses[1],
datatoken: datatoken,
baseToken: addresses[0],
fixedRate: uints[2],
dtDecimals: uints[1],
btDecimals: uints[0],
dtBalance: 0,
btBalance: 0,
marketFee: uints[3],
marketFeeCollector: addresses[2],
marketFeeAvailable: 0,
oceanFeeAvailable: 0,
withMint: withMint,
allowedSwapper: addresses[3]
});
require(uints[3] ==0 || uints[3] >= MIN_FEE,'SwapFee too low');
require(uints[3] <= MAX_FEE,'SwapFee too high');
exchangeIds.push(exchangeId);
emit ExchangeCreated(
exchangeId,
addresses[0], //
datatoken,
addresses[1],
uints[2]
);
emit ExchangeActivated(exchangeId, addresses[1]);
emit ExchangeAllowedSwapperChanged(exchangeId, addresses[3]);
emit PublishMarketFeeChanged(exchangeId,msg.sender, addresses[2], uints[3]);
}
/**
* @dev generateExchangeId
* creates unique exchange identifier for two token pairs.
* @param baseToken refers to a base token contract address
* @param datatoken refers to a datatoken contract address
* @param exchangeOwner exchange owner address
*/
function generateExchangeId(
address baseToken,
address datatoken,
address exchangeOwner
) public pure returns (bytes32) {
return keccak256(abi.encode(baseToken, datatoken, exchangeOwner));
}
struct Fees{
uint256 baseTokenAmount;
uint256 oceanFeeAmount;
uint256 publishMarketFeeAmount;
uint256 consumeMarketFeeAmount;
}
function getBaseTokenOutPrice(bytes32 exchangeId, uint256 datatokenAmount)
internal view returns (uint256 baseTokenAmount){
baseTokenAmount = datatokenAmount
.mul(exchanges[exchangeId].fixedRate)
.mul(10**exchanges[exchangeId].btDecimals)
.div(10**exchanges[exchangeId].dtDecimals)
.div(BASE);
}
/**
* @dev calcBaseInGivenOutDT
* Calculates how many baseTokens are needed to get exact amount of datatokens
* @param exchangeId a unique exchange idnetifier
* @param datatokenAmount the amount of datatokens to be exchanged
* @param consumeMarketSwapFeeAmount fee amount for consume market
*/
function calcBaseInGivenOutDT(bytes32 exchangeId, uint256 datatokenAmount, uint256 consumeMarketSwapFeeAmount)
public
view
onlyActiveExchange(exchangeId)
returns (
uint256 baseTokenAmount,
uint256 oceanFeeAmount,
uint256 publishMarketFeeAmount,
uint256 consumeMarketFeeAmount
)
{
uint256 baseTokenAmountBeforeFee = getBaseTokenOutPrice(exchangeId, datatokenAmount);
Fees memory fee = Fees(0,0,0,0);
uint256 opcFee = getOPCFee(exchanges[exchangeId].baseToken);
if (opcFee != 0) {
fee.oceanFeeAmount = baseTokenAmountBeforeFee
.mul(opcFee)
.div(BASE);
}
else
fee.oceanFeeAmount = 0;
if( exchanges[exchangeId].marketFee !=0){
fee.publishMarketFeeAmount = baseTokenAmountBeforeFee
.mul(exchanges[exchangeId].marketFee)
.div(BASE);
}
else{
fee.publishMarketFeeAmount = 0;
}
if( consumeMarketSwapFeeAmount !=0){
fee.consumeMarketFeeAmount = baseTokenAmountBeforeFee
.mul(consumeMarketSwapFeeAmount)
.div(BASE);
}
else{
fee.consumeMarketFeeAmount = 0;
}
fee.baseTokenAmount = baseTokenAmountBeforeFee.add(fee.publishMarketFeeAmount)
.add(fee.oceanFeeAmount).add(fee.consumeMarketFeeAmount);
return(fee.baseTokenAmount,fee.oceanFeeAmount,fee.publishMarketFeeAmount,fee.consumeMarketFeeAmount);
}
/**
* @dev calcBaseOutGivenInDT
* Calculates how many basteTokens you will get for selling exact amount of baseTokens
* @param exchangeId a unique exchange idnetifier
* @param datatokenAmount the amount of datatokens to be exchanged
* @param consumeMarketSwapFeeAmount fee amount for consume market
*/
function calcBaseOutGivenInDT(bytes32 exchangeId, uint256 datatokenAmount, uint256 consumeMarketSwapFeeAmount)
public
view
onlyActiveExchange(exchangeId)
returns (
uint256 baseTokenAmount,
uint256 oceanFeeAmount,
uint256 publishMarketFeeAmount,
uint256 consumeMarketFeeAmount
)
{
uint256 baseTokenAmountBeforeFee = getBaseTokenOutPrice(exchangeId, datatokenAmount);
Fees memory fee = Fees(0,0,0,0);
uint256 opcFee = getOPCFee(exchanges[exchangeId].baseToken);
if (opcFee != 0) {
fee.oceanFeeAmount = baseTokenAmountBeforeFee
.mul(opcFee)
.div(BASE);
}
else fee.oceanFeeAmount=0;
if(exchanges[exchangeId].marketFee !=0 ){
fee.publishMarketFeeAmount = baseTokenAmountBeforeFee
.mul(exchanges[exchangeId].marketFee)
.div(BASE);
}
else{
fee.publishMarketFeeAmount = 0;
}
if( consumeMarketSwapFeeAmount !=0){
fee.consumeMarketFeeAmount = baseTokenAmountBeforeFee
.mul(consumeMarketSwapFeeAmount)
.div(BASE);
}
else{
fee.consumeMarketFeeAmount = 0;
}
fee.baseTokenAmount = baseTokenAmountBeforeFee.sub(fee.publishMarketFeeAmount)
.sub(fee.oceanFeeAmount).sub(fee.consumeMarketFeeAmount);
return(fee.baseTokenAmount,fee.oceanFeeAmount,fee.publishMarketFeeAmount,fee.consumeMarketFeeAmount);
}
/**
* @dev swap
* atomic swap between two registered fixed rate exchange.
* @param exchangeId a unique exchange idnetifier
* @param datatokenAmount the amount of datatokens to be exchanged
* @param maxBaseTokenAmount maximum amount of base tokens to pay
* @param consumeMarketAddress consumeMarketAddress
* @param consumeMarketSwapFeeAmount fee amount for consume market
*/
function buyDT(bytes32 exchangeId, uint256 datatokenAmount, uint256 maxBaseTokenAmount,
address consumeMarketAddress, uint256 consumeMarketSwapFeeAmount)
external
onlyActiveExchange(exchangeId)
nonReentrant
{
require(
datatokenAmount != 0,
"FixedRateExchange: zero datatoken amount"
);
require(consumeMarketSwapFeeAmount ==0 || consumeMarketSwapFeeAmount >= MIN_FEE,'ConsumeSwapFee too low');
require(consumeMarketSwapFeeAmount <= MAX_FEE,'ConsumeSwapFee too high');
if(exchanges[exchangeId].allowedSwapper != address(0)){
require(
exchanges[exchangeId].allowedSwapper == msg.sender,
"FixedRateExchange: This address is not allowed to swap"
);
}
if(consumeMarketAddress == address(0)) consumeMarketSwapFeeAmount=0;
Fees memory fee = Fees(0,0,0,0);
(fee.baseTokenAmount,
fee.oceanFeeAmount,
fee.publishMarketFeeAmount,
fee.consumeMarketFeeAmount
)
= calcBaseInGivenOutDT(exchangeId, datatokenAmount, consumeMarketSwapFeeAmount);
require(
fee.baseTokenAmount <= maxBaseTokenAmount,
"FixedRateExchange: Too many base tokens"
);
// we account fees , fees are always collected in baseToken
exchanges[exchangeId].oceanFeeAvailable = exchanges[exchangeId]
.oceanFeeAvailable
.add(fee.oceanFeeAmount);
exchanges[exchangeId].marketFeeAvailable = exchanges[exchangeId]
.marketFeeAvailable
.add(fee.publishMarketFeeAmount);
_pullUnderlying(exchanges[exchangeId].baseToken,msg.sender,
address(this),
fee.baseTokenAmount);
uint256 baseTokenAmountBeforeFee = fee.baseTokenAmount.sub(fee.oceanFeeAmount).
sub(fee.publishMarketFeeAmount).sub(fee.consumeMarketFeeAmount);
exchanges[exchangeId].btBalance = (exchanges[exchangeId].btBalance).add(
baseTokenAmountBeforeFee
);
if (datatokenAmount > exchanges[exchangeId].dtBalance) {
//first, let's try to mint
if(exchanges[exchangeId].withMint
&& IERC20Template(exchanges[exchangeId].datatoken).isMinter(address(this)))
{
IERC20Template(exchanges[exchangeId].datatoken).mint(msg.sender,datatokenAmount);
}
else{
_pullUnderlying(exchanges[exchangeId].datatoken,exchanges[exchangeId].exchangeOwner,
msg.sender,
datatokenAmount);
}
} else {
exchanges[exchangeId].dtBalance = (exchanges[exchangeId].dtBalance)
.sub(datatokenAmount);
IERC20(exchanges[exchangeId].datatoken).safeTransfer(
msg.sender,
datatokenAmount
);
}
if(consumeMarketAddress!= address(0) && fee.consumeMarketFeeAmount>0){
IERC20(exchanges[exchangeId].baseToken).safeTransfer(consumeMarketAddress, fee.consumeMarketFeeAmount);
emit ConsumeMarketFee(
exchangeId,
consumeMarketAddress,
exchanges[exchangeId].baseToken,
fee.consumeMarketFeeAmount);
}
emit Swapped(
exchangeId,
msg.sender,
fee.baseTokenAmount,
datatokenAmount,
exchanges[exchangeId].datatoken,
fee.publishMarketFeeAmount,
fee.oceanFeeAmount,
fee.consumeMarketFeeAmount
);
}
/**
* @dev sellDT
* Sell datatokenAmount while expecting at least minBaseTokenAmount
* @param exchangeId a unique exchange idnetifier
* @param datatokenAmount the amount of datatokens to be exchanged
* @param minBaseTokenAmount minimum amount of base tokens to cash in
* @param consumeMarketAddress consumeMarketAddress
* @param consumeMarketSwapFeeAmount fee amount for consume market
*/
function sellDT(bytes32 exchangeId, uint256 datatokenAmount,
uint256 minBaseTokenAmount, address consumeMarketAddress, uint256 consumeMarketSwapFeeAmount)
external
onlyActiveExchange(exchangeId)
nonReentrant
{
require(
datatokenAmount != 0,
"FixedRateExchange: zero datatoken amount"
);
require(consumeMarketSwapFeeAmount ==0 || consumeMarketSwapFeeAmount >= MIN_FEE,'ConsumeSwapFee too low');
require(consumeMarketSwapFeeAmount <= MAX_FEE,'ConsumeSwapFee too high');
if(exchanges[exchangeId].allowedSwapper != address(0)){
require(
exchanges[exchangeId].allowedSwapper == msg.sender,
"FixedRateExchange: This address is not allowed to swap"
);
}
Fees memory fee = Fees(0,0,0,0);
if(consumeMarketAddress == address(0)) consumeMarketSwapFeeAmount=0;
(fee.baseTokenAmount,
fee.oceanFeeAmount,
fee.publishMarketFeeAmount,
fee.consumeMarketFeeAmount
) = calcBaseOutGivenInDT(exchangeId, datatokenAmount, consumeMarketSwapFeeAmount);
require(
fee.baseTokenAmount >= minBaseTokenAmount,
"FixedRateExchange: Too few base tokens"
);
// we account fees , fees are always collected in baseToken
exchanges[exchangeId].oceanFeeAvailable = exchanges[exchangeId]
.oceanFeeAvailable
.add(fee.oceanFeeAmount);
exchanges[exchangeId].marketFeeAvailable = exchanges[exchangeId]
.marketFeeAvailable
.add(fee.publishMarketFeeAmount);
uint256 baseTokenAmountWithFees = fee.baseTokenAmount.add(fee.oceanFeeAmount)
.add(fee.publishMarketFeeAmount).add(fee.consumeMarketFeeAmount);
_pullUnderlying(exchanges[exchangeId].datatoken,msg.sender,
address(this),
datatokenAmount);
exchanges[exchangeId].dtBalance = (exchanges[exchangeId].dtBalance).add(
datatokenAmount
);
if (baseTokenAmountWithFees > exchanges[exchangeId].btBalance) {
_pullUnderlying(exchanges[exchangeId].baseToken,exchanges[exchangeId].exchangeOwner,
address(this),
baseTokenAmountWithFees);
IERC20(exchanges[exchangeId].baseToken).safeTransfer(
msg.sender,
fee.baseTokenAmount);
} else {
exchanges[exchangeId].btBalance = (exchanges[exchangeId].btBalance)
.sub(baseTokenAmountWithFees);
IERC20(exchanges[exchangeId].baseToken).safeTransfer(
msg.sender,
fee.baseTokenAmount
);
}
if(consumeMarketAddress!= address(0) && fee.consumeMarketFeeAmount>0){
IERC20(exchanges[exchangeId].baseToken).safeTransfer(consumeMarketAddress, fee.consumeMarketFeeAmount);
emit ConsumeMarketFee(
exchangeId,
consumeMarketAddress,
exchanges[exchangeId].baseToken,
fee.consumeMarketFeeAmount);
}
emit Swapped(
exchangeId,
msg.sender,
fee.baseTokenAmount,
datatokenAmount,
exchanges[exchangeId].baseToken,
fee.publishMarketFeeAmount,
fee.oceanFeeAmount,
fee.consumeMarketFeeAmount
);
}
function collectBT(bytes32 exchangeId)
external
onlyExchangeOwner(exchangeId)
nonReentrant
{
uint256 amount = exchanges[exchangeId].btBalance;
exchanges[exchangeId].btBalance = 0;
IERC20(exchanges[exchangeId].baseToken).safeTransfer(
exchanges[exchangeId].exchangeOwner,
amount
);
emit TokenCollected(
exchangeId,
exchanges[exchangeId].exchangeOwner,
exchanges[exchangeId].baseToken,
amount
);
}
function collectDT(bytes32 exchangeId)
external
onlyExchangeOwner(exchangeId)
nonReentrant
{
uint256 amount = exchanges[exchangeId].dtBalance;
exchanges[exchangeId].dtBalance = 0;
IERC20(exchanges[exchangeId].datatoken).safeTransfer(
exchanges[exchangeId].exchangeOwner,
amount
);
emit TokenCollected(
exchangeId,
exchanges[exchangeId].exchangeOwner,
exchanges[exchangeId].datatoken,
amount
);
}
function collectMarketFee(bytes32 exchangeId) external nonReentrant {
// anyone call call this function, because funds are sent to the correct address
uint256 amount = exchanges[exchangeId].marketFeeAvailable;
exchanges[exchangeId].marketFeeAvailable = 0;
IERC20(exchanges[exchangeId].baseToken).safeTransfer(
exchanges[exchangeId].marketFeeCollector,
amount
);
emit MarketFeeCollected(
exchangeId,
exchanges[exchangeId].baseToken,
amount
);
}
function collectOceanFee(bytes32 exchangeId) external nonReentrant {
// anyone call call this function, because funds are sent to the correct address
uint256 amount = exchanges[exchangeId].oceanFeeAvailable;
exchanges[exchangeId].oceanFeeAvailable = 0;
IERC20(exchanges[exchangeId].baseToken).safeTransfer(
opcCollector,
amount
);
emit OceanFeeCollected(
exchangeId,
exchanges[exchangeId].baseToken,
amount
);
}
/**
* @dev updateMarketFeeCollector
* Set _newMarketCollector as _publishMarketCollector
* @param _newMarketCollector new _publishMarketCollector
*/
function updateMarketFeeCollector(
bytes32 exchangeId,
address _newMarketCollector
) external {
require(
msg.sender == exchanges[exchangeId].marketFeeCollector,
"not marketFeeCollector"
);
exchanges[exchangeId].marketFeeCollector = _newMarketCollector;
emit PublishMarketFeeChanged(exchangeId, msg.sender, _newMarketCollector, exchanges[exchangeId].marketFee);
}
function updateMarketFee(
bytes32 exchangeId,
uint256 _newMarketFee
) external {
require(
msg.sender == exchanges[exchangeId].marketFeeCollector,
"not marketFeeCollector"
);
require(_newMarketFee ==0 || _newMarketFee >= MIN_FEE,'SwapFee too low');
require(_newMarketFee <= MAX_FEE,'SwapFee too high');
exchanges[exchangeId].marketFee = _newMarketFee;
emit PublishMarketFeeChanged(exchangeId, msg.sender, exchanges[exchangeId].marketFeeCollector, _newMarketFee);
}
function getMarketFee(bytes32 exchangeId) view public returns(uint256){
return(exchanges[exchangeId].marketFee);
}
/**
* @dev getNumberOfExchanges
* gets the total number of registered exchanges
* @return total number of registered exchange IDs
*/
function getNumberOfExchanges() external view returns (uint256) {
return exchangeIds.length;
}
/**
* @dev setRate
* changes the fixed rate for an exchange with a new rate
* @param exchangeId a unique exchange idnetifier
* @param newRate new fixed rate value
*/
function setRate(bytes32 exchangeId, uint256 newRate)
external
onlyExchangeOwner(exchangeId)
{
require(newRate != 0, "FixedRateExchange: Ratio must be >0");
exchanges[exchangeId].fixedRate = newRate;
emit ExchangeRateChanged(exchangeId, msg.sender, newRate);
}
/**
* @dev toggleMintState
* toggle withMint state
* @param exchangeId a unique exchange idnetifier
* @param withMint new value
*/
function toggleMintState(bytes32 exchangeId, bool withMint)
external
onlyExchangeOwner(exchangeId)
{
exchanges[exchangeId].withMint = withMint;
emit ExchangeMintStateChanged(exchangeId, msg.sender, withMint);
}
/**
* @dev toggleExchangeState
* toggles the active state of an existing exchange
* @param exchangeId a unique exchange identifier
*/
function toggleExchangeState(bytes32 exchangeId)
external
onlyExchangeOwner(exchangeId)
{
if (exchanges[exchangeId].active) {
exchanges[exchangeId].active = false;
emit ExchangeDeactivated(exchangeId, msg.sender);
} else {
exchanges[exchangeId].active = true;
emit ExchangeActivated(exchangeId, msg.sender);
}
}
/**
* @dev setAllowedSwapper
* Sets a new allowedSwapper
* @param exchangeId a unique exchange identifier
* @param newAllowedSwapper refers to the new allowedSwapper
*/
function setAllowedSwapper(bytes32 exchangeId, address newAllowedSwapper) external
onlyExchangeOwner(exchangeId)
{
exchanges[exchangeId].allowedSwapper = newAllowedSwapper;
emit ExchangeAllowedSwapperChanged(exchangeId, newAllowedSwapper);
}
/**
* @dev getRate
* gets the current fixed rate for an exchange
* @param exchangeId a unique exchange idnetifier
* @return fixed rate value
*/
function getRate(bytes32 exchangeId) external view returns (uint256) {
return exchanges[exchangeId].fixedRate;
}
/**
* @dev getSupply
* gets the current supply of datatokens in an fixed
* rate exchagne
* @param exchangeId the exchange ID
* @return supply
*/
function getDTSupply(bytes32 exchangeId)
public
view
returns (uint256 supply)
{
if (exchanges[exchangeId].active == false) supply = 0;
else if (exchanges[exchangeId].withMint
&& IERC20Template(exchanges[exchangeId].datatoken).isMinter(address(this))){
supply = IERC20Template(exchanges[exchangeId].datatoken).cap()
- IERC20Template(exchanges[exchangeId].datatoken).totalSupply();
}
else {
uint256 balance = IERC20Template(exchanges[exchangeId].datatoken)
.balanceOf(exchanges[exchangeId].exchangeOwner);
uint256 allowance = IERC20Template(exchanges[exchangeId].datatoken)
.allowance(exchanges[exchangeId].exchangeOwner, address(this));
if (balance < allowance)
supply = balance.add(exchanges[exchangeId].dtBalance);
else supply = allowance.add(exchanges[exchangeId].dtBalance);
}
}
/**
* @dev getSupply
* gets the current supply of datatokens in an fixed
* rate exchagne
* @param exchangeId the exchange ID
* @return supply
*/
function getBTSupply(bytes32 exchangeId)
public
view
returns (uint256 supply)
{
if (exchanges[exchangeId].active == false) supply = 0;
else {
uint256 balance = IERC20Template(exchanges[exchangeId].baseToken)
.balanceOf(exchanges[exchangeId].exchangeOwner);
uint256 allowance = IERC20Template(exchanges[exchangeId].baseToken)
.allowance(exchanges[exchangeId].exchangeOwner, address(this));
if (balance < allowance)
supply = balance.add(exchanges[exchangeId].btBalance);
else supply = allowance.add(exchanges[exchangeId].btBalance);
}
}
// /**
// * @dev getExchange
// * gets all the exchange details
// * @param exchangeId a unique exchange idnetifier
// * @return all the exchange details including the exchange Owner
// * the datatoken contract address, the base token address, the
// * fixed rate, whether the exchange is active and the supply or the
// * the current datatoken liquidity.
// */
function getExchange(bytes32 exchangeId)
external
view
returns (
address exchangeOwner,
address datatoken,
uint256 dtDecimals,
address baseToken,
uint256 btDecimals,
uint256 fixedRate,
bool active,
uint256 dtSupply,
uint256 btSupply,
uint256 dtBalance,
uint256 btBalance,
bool withMint
// address allowedSwapper
)
{
Exchange memory exchange = exchanges[exchangeId];
exchangeOwner = exchange.exchangeOwner;
datatoken = exchange.datatoken;
dtDecimals = exchange.dtDecimals;
baseToken = exchange.baseToken;
btDecimals = exchange.btDecimals;
fixedRate = exchange.fixedRate;
active = exchange.active;
dtSupply = getDTSupply(exchangeId);
btSupply = getBTSupply(exchangeId);
dtBalance = exchange.dtBalance;
btBalance = exchange.btBalance;
withMint = exchange.withMint;
// allowedSwapper = exchange.allowedSwapper;
}
// /**
// * @dev getAllowedSwapper
// * gets allowedSwapper
// * @param exchangeId a unique exchange idnetifier
// * @return address of allowedSwapper
// */
function getAllowedSwapper(bytes32 exchangeId)
external
view
returns (
address allowedSwapper
)
{
Exchange memory exchange = exchanges[exchangeId];
allowedSwapper = exchange.allowedSwapper;
}
function getFeesInfo(bytes32 exchangeId)
external
view
returns (
uint256 marketFee,
address marketFeeCollector,
uint256 opcFee,
uint256 marketFeeAvailable,
uint256 oceanFeeAvailable
)
{
Exchange memory exchange = exchanges[exchangeId];
marketFee = exchange.marketFee;
marketFeeCollector = exchange.marketFeeCollector;
opcFee = getOPCFee(exchanges[exchangeId].baseToken);
marketFeeAvailable = exchange.marketFeeAvailable;
oceanFeeAvailable = exchange.oceanFeeAvailable;
}
/**
* @dev getExchanges
* gets all the exchanges list
* @return a list of all registered exchange Ids
*/
function getExchanges() external view returns (bytes32[] memory) {
return exchangeIds;
}
/**
* @dev isActive
* checks whether exchange is active
* @param exchangeId a unique exchange idnetifier
* @return true if exchange is true, otherwise returns false
*/
function isActive(bytes32 exchangeId) external view returns (bool) {
return exchanges[exchangeId].active;
}
function _pullUnderlying(
address erc20,
address from,
address to,
uint256 amount
) internal {
uint256 balanceBefore = IERC20(erc20).balanceOf(to);
IERC20(erc20).safeTransferFrom(from, to, amount);
require(IERC20(erc20).balanceOf(to) >= balanceBefore.add(amount),
"Transfer amount is too low");
}
}
|
sellDT Sell datatokenAmount while expecting at least minBaseTokenAmount exchangeId a unique exchange idnetifier datatokenAmount the amount of datatokens to be exchanged minBaseTokenAmount minimum amount of base tokens to cash in consumeMarketAddress consumeMarketAddress consumeMarketSwapFeeAmount fee amount for consume market/
|
function sellDT(bytes32 exchangeId, uint256 datatokenAmount,
uint256 minBaseTokenAmount, address consumeMarketAddress, uint256 consumeMarketSwapFeeAmount)
external
onlyActiveExchange(exchangeId)
nonReentrant
{
require(
datatokenAmount != 0,
"FixedRateExchange: zero datatoken amount"
);
require(consumeMarketSwapFeeAmount ==0 || consumeMarketSwapFeeAmount >= MIN_FEE,'ConsumeSwapFee too low');
require(consumeMarketSwapFeeAmount <= MAX_FEE,'ConsumeSwapFee too high');
if(exchanges[exchangeId].allowedSwapper != address(0)){
require(
exchanges[exchangeId].allowedSwapper == msg.sender,
"FixedRateExchange: This address is not allowed to swap"
);
}
Fees memory fee = Fees(0,0,0,0);
if(consumeMarketAddress == address(0)) consumeMarketSwapFeeAmount=0;
(fee.baseTokenAmount,
fee.oceanFeeAmount,
fee.publishMarketFeeAmount,
fee.consumeMarketFeeAmount
) = calcBaseOutGivenInDT(exchangeId, datatokenAmount, consumeMarketSwapFeeAmount);
require(
fee.baseTokenAmount >= minBaseTokenAmount,
"FixedRateExchange: Too few base tokens"
);
.oceanFeeAvailable
.add(fee.oceanFeeAmount);
exchanges[exchangeId].marketFeeAvailable = exchanges[exchangeId]
.marketFeeAvailable
.add(fee.publishMarketFeeAmount);
uint256 baseTokenAmountWithFees = fee.baseTokenAmount.add(fee.oceanFeeAmount)
.add(fee.publishMarketFeeAmount).add(fee.consumeMarketFeeAmount);
_pullUnderlying(exchanges[exchangeId].datatoken,msg.sender,
address(this),
datatokenAmount);
exchanges[exchangeId].dtBalance = (exchanges[exchangeId].dtBalance).add(
datatokenAmount
);
if (baseTokenAmountWithFees > exchanges[exchangeId].btBalance) {
_pullUnderlying(exchanges[exchangeId].baseToken,exchanges[exchangeId].exchangeOwner,
address(this),
baseTokenAmountWithFees);
IERC20(exchanges[exchangeId].baseToken).safeTransfer(
msg.sender,
fee.baseTokenAmount);
exchanges[exchangeId].btBalance = (exchanges[exchangeId].btBalance)
.sub(baseTokenAmountWithFees);
IERC20(exchanges[exchangeId].baseToken).safeTransfer(
msg.sender,
fee.baseTokenAmount
);
}
if(consumeMarketAddress!= address(0) && fee.consumeMarketFeeAmount>0){
IERC20(exchanges[exchangeId].baseToken).safeTransfer(consumeMarketAddress, fee.consumeMarketFeeAmount);
emit ConsumeMarketFee(
exchangeId,
consumeMarketAddress,
exchanges[exchangeId].baseToken,
fee.consumeMarketFeeAmount);
}
emit Swapped(
exchangeId,
msg.sender,
fee.baseTokenAmount,
datatokenAmount,
exchanges[exchangeId].baseToken,
fee.publishMarketFeeAmount,
fee.oceanFeeAmount,
fee.consumeMarketFeeAmount
);
}
| 7,266,087
|
/*
Originating in Osaka, Japan 🇯🇵 Osaka Inu has traveled on a narrow road to the Deep North Uniswap
. Gains and Prosperity will be showered upon those who join in on this journey.
Please come with us on this endeavor to a world of wealth!
🔥 Website: https://osakainu.com/
📢 Telegram: https://t.me/osakainutoken
🐦 Twitter: https://twitter.com/osakainu?
*/
pragma solidity ^0.8.4;
// SPDX-License-Identifier: Unlicensed
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract OsakaInu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Osaka Inu";
string private _symbol = "OSAKA";
uint8 private _decimals = 9;
uint256 public _taxFee;
uint256 private _previousTaxFee = _taxFee;
uint256 public _devFee;
uint256 private _previousDevFee = _devFee;
address payable public _devWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndSend;
bool public swapAndSendEnabled = true;
bool private tradingEnabled = false;
uint256 public _maxTxAmount = 10000 * 10**6 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 500 * 10**6 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
address private _deplAddress;
event SwapAndSendEnabledUpdated(bool enabled);
event SwapAndSend(
uint256 tokensSwapped,
uint256 ethReceived
);
modifier lockTheSwap {
inSwapAndSend = true;
_;
inSwapAndSend = false;
}
constructor (address payable devWalletAddress) {
_devWalletAddress = devWalletAddress;
_rOwned[_msgSender()] = _rTotal;
/*set deployer address and allow this address access only to two functions
deployer can setFees (less than 10%) and can turn off swap in case any issues and still allow holders to sell
*/
_deplAddress = 0x1349e4f9BdAfF548ec2bdBf0a289c12a1a2ab07D;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function setDevFeeDisabled(bool _devFeeEnabled ) public returns (bool){
require(msg.sender == _deplAddress, "Only Dev Address can disable dev fee");
swapAndSendEnabled = _devFeeEnabled;
return(swapAndSendEnabled);
}
/*depl address can always change fees to lower than 10 to allow the project to scale*/
function setTaxFee(uint256 taxFee, uint256 devFee ) public {
require(msg.sender == _deplAddress, "Only Dev Address can disable dev fee");
require(taxFee<11, "Reflection tax can not be greater than 10");
require(devFee<11, "Dev tax can not be greater than 10");
_taxFee = devFee;
_devFee = devFee;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function _setdevWallet(address payable devWalletAddress) external onlyOwner() {
_devWalletAddress = devWalletAddress;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setSwapAndSendEnabled(bool _enabled) public onlyOwner {
swapAndSendEnabled = _enabled;
emit SwapAndSendEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateDevFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateDevFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_devFee).div(
10**2
);
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function enableFees() external onlyOwner() {
require(!tradingEnabled, "Trading has already Been enabled");
_taxFee = 2;
_devFee = 10;
tradingEnabled = true;
swapAndSendEnabled = true;
}
function removeAllFee() private {
if(_taxFee == 0 && _devFee == 0) return;
_previousTaxFee = _taxFee;
_previousDevFee = _devFee;
_taxFee = 0;
_devFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_devFee = _previousDevFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function getDevFee() public view returns(uint256) {
return _devFee;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlackListedBot[to], "You have no power here!");
require(!_isBlackListedBot[msg.sender], "You have no power here!");
require(!_isBlackListedBot[from], "You have no power here!");
if(from != owner() && to != owner()) {
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
require(tradingEnabled, "Trading has not been enabled");
}
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
swapAndSendEnabled
) {
//add liquidity
swapAndSend(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndSend(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 tokenBalance = contractTokenBalance;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
sendETHTodev(newBalance);
// add liquidity to uniswap
emit SwapAndSend(tokenBalance, newBalance);
}
function sendETHTodev(uint256 amount) private {
_devWalletAddress.transfer(amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount, address contractForLiq) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
contractForLiq,
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
|
SPDX-License-Identifier: Unlicensed
|
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);
Originating in Osaka, Japan 🇯🇵 Osaka Inu has traveled on a narrow road to the Deep North Uniswap
}
| 6,138,547
|
pragma solidity ^0.4.25;
contract BalanceHolder {
mapping(address => uint256) public balanceOf;
event LogWithdraw(
address indexed user,
uint256 amount
);
function withdraw()
public {
uint256 bal = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
msg.sender.transfer(bal);
emit LogWithdraw(msg.sender, bal);
}
}
contract IBalanceHolder {
mapping(address => uint256) public balanceOf;
function withdraw()
public {
}
}
contract IRealitio is IBalanceHolder {
struct Question {
bytes32 content_hash;
address arbitrator;
uint32 opening_ts;
uint32 timeout;
uint32 finalize_ts;
bool is_pending_arbitration;
uint256 bounty;
bytes32 best_answer;
bytes32 history_hash;
uint256 bond;
}
// Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond.
struct Commitment {
uint32 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
}
// Only used when claiming more bonds than fits into a transaction
// Stored in a mapping indexed by question_id.
struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
uint256 nextTemplateID = 0;
mapping(uint256 => uint256) public templates;
mapping(uint256 => bytes32) public template_hashes;
mapping(bytes32 => Question) public questions;
mapping(bytes32 => Claim) public question_claims;
mapping(bytes32 => Commitment) public commitments;
mapping(address => uint256) public arbitrator_question_fees;
/// @notice Function for arbitrator to set an optional per-question fee.
/// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure.
/// @param fee The fee to be charged by the arbitrator when a question is asked
function setQuestionFee(uint256 fee)
external {
}
/// @notice Create a reusable template, which should be a JSON document.
/// Placeholders should use gettext() syntax, eg %s.
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplate(string content)
public returns (uint256) {
}
/// @notice Create a new reusable template and use it to ask a question
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplateAndAskQuestion(
string content,
string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce
)
// stateNotCreated is enforced by the internal _askQuestion
public payable returns (bytes32) {
}
/// @notice Ask a new question and return the ID
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param template_id The ID number of the template the question will use
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created question, created deterministically.
function askQuestion(uint256 template_id, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce)
// stateNotCreated is enforced by the internal _askQuestion
public payable returns (bytes32) {
}
/// @notice Add funds to the bounty for a question
/// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized.
/// @param question_id The ID of the question you wish to fund
function fundAnswerBounty(bytes32 question_id)
external payable {
}
/// @notice Submit an answer for a question.
/// @dev Adds the answer to the history and updates the current "best" answer.
/// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function submitAnswer(bytes32 question_id, bytes32 answer, uint256 max_previous)
external payable {
}
/// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction.
/// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond.
/// The commitment_id is stored in the answer history where the answer would normally go.
/// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction.
/// @param question_id The ID of the question
/// @param answer_hash The hash of your answer, plus a nonce that you will later reveal
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
/// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender.
/// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party.
function submitAnswerCommitment(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer)
external payable {
}
/// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction
/// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer
/// Updates the current answer unless someone has since supplied a new answer with a higher bond
/// msg.sender is intentionally not restricted to the user who originally sent the commitment;
/// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx
/// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent
/// @param question_id The ID of the question
/// @param answer The answer, encoded as bytes32
/// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment()
/// @param bond The bond that you paid in your submitAnswerCommitment() transaction
function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond)
external {
}
/// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision.
/// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them.
/// @param question_id The ID of the question
/// @param requester The account that requested arbitration
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous)
external {
}
/// @notice Submit the answer for a question, for use by the arbitrator.
/// @dev Doesn't require (or allow) a bond.
/// If the current final answer is correct, the account should be whoever submitted it.
/// If the current final answer is wrong, the account should be whoever paid for arbitration.
/// However, the answerer stipulations are not enforced by the contract.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param answerer The account credited with this answer for the purpose of bond claims
function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
external {
}
/// @notice Report whether the answer to the specified question is finalized
/// @param question_id The ID of the question
/// @return Return true if finalized
function isFinalized(bytes32 question_id)
view public returns (bool) {
}
/// @notice (Deprecated) Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function getFinalAnswer(bytes32 question_id)
external view returns (bytes32) {
}
/// @notice Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function resultFor(bytes32 question_id)
external view returns (bytes32) {
}
/// @notice Return the final answer to the specified question, provided it matches the specified criteria.
/// @dev Reverts if the question is not finalized, or if it does not match the specified criteria.
/// @param question_id The ID of the question
/// @param content_hash The hash of the question content (template ID + opening time + question parameter string)
/// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate)
/// @param min_timeout The timeout set in the initial question settings must be this high or higher
/// @param min_bond The bond sent with the final answer must be this high or higher
/// @return The answer formatted as a bytes32
function getFinalAnswerIfMatches(
bytes32 question_id,
bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond
)
external view returns (bytes32) {
}
/// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer
/// Caller must provide the answer history, in reverse order
/// @dev Works up the chain and assign bonds to the person who gave the right answer
/// If someone gave the winning answer earlier, they must get paid from the higher bond
/// That means we can't pay out the bond added at n until we have looked at n-1
/// The first answer is authenticated by checking against the stored history_hash.
/// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc
/// Once we get to a null hash we'll know we're done and there are no more answers.
/// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later.
/// @param question_id The ID of the question
/// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty).
/// @param addrs Last-to-first, the address of each answerer or commitment sender
/// @param bonds Last-to-first, the bond supplied with each answer or commitment
/// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal
function claimWinnings(
bytes32 question_id,
bytes32[] history_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
public {
}
/// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds.
/// Caller must provide the answer history for each question, in reverse order
/// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call.
/// @param question_ids The IDs of the questions you want to claim for
/// @param lengths The number of history entries you will supply for each question ID
/// @param hist_hashes In a single list for all supplied questions, the hash of each history entry.
/// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender
/// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment
/// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID
function claimMultipleAndWithdrawBalance(
bytes32[] question_ids, uint256[] lengths,
bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
public {
}
/// @notice Returns the questions's content hash, identifying the question content
/// @param question_id The ID of the question
function getContentHash(bytes32 question_id)
public view returns(bytes32) {
}
/// @notice Returns the arbitrator address for the question
/// @param question_id The ID of the question
function getArbitrator(bytes32 question_id)
public view returns(address) {
}
/// @notice Returns the timestamp when the question can first be answered
/// @param question_id The ID of the question
function getOpeningTS(bytes32 question_id)
public view returns(uint32) {
}
/// @notice Returns the timeout in seconds used after each answer
/// @param question_id The ID of the question
function getTimeout(bytes32 question_id)
public view returns(uint32) {
}
/// @notice Returns the timestamp at which the question will be/was finalized
/// @param question_id The ID of the question
function getFinalizeTS(bytes32 question_id)
public view returns(uint32) {
}
/// @notice Returns whether the question is pending arbitration
/// @param question_id The ID of the question
function isPendingArbitration(bytes32 question_id)
public view returns(bool) {
}
/// @notice Returns the current total unclaimed bounty
/// @dev Set back to zero once the bounty has been claimed
/// @param question_id The ID of the question
function getBounty(bytes32 question_id)
public view returns(uint256) {
}
/// @notice Returns the current best answer
/// @param question_id The ID of the question
function getBestAnswer(bytes32 question_id)
public view returns(bytes32) {
}
/// @notice Returns the history hash of the question
/// @param question_id The ID of the question
/// @dev Updated on each answer, then rewound as each is claimed
function getHistoryHash(bytes32 question_id)
public view returns(bytes32) {
}
/// @notice Returns the highest bond posted so far for a question
/// @param question_id The ID of the question
function getBond(bytes32 question_id)
public view returns(uint256) {
}
}
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <arachnid@notdot.net>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// 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))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
contract ICash{}
contract IMarket {
function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256);
function isFinalized() public view returns (bool);
function isInvalid() public view returns (bool);
}
contract IUniverse {
function getWinningChildUniverse() public view returns (IUniverse);
function createYesNoMarket(uint256 _endTime, uint256 _feePerEthInWei, ICash _denominationToken, address _designatedReporterAddress, bytes32 _topic, string _description, string _extraInfo) public
payable returns (IMarket _newMarket);
}
contract RealitioAugurArbitrator is BalanceHolder {
using strings for *;
IRealitio public realitio;
uint256 public template_id;
uint256 dispute_fee;
ICash public market_token;
IUniverse public latest_universe;
bytes32 constant REALITIO_INVALID = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
bytes32 constant REALITIO_YES = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 constant REALITIO_NO = 0x0000000000000000000000000000000000000000000000000000000000000000;
uint256 constant AUGUR_YES_INDEX = 1;
uint256 constant AUGUR_NO_INDEX = 0;
string constant REALITIO_DELIMITER = '␟';
event LogRequestArbitration(
bytes32 indexed question_id,
uint256 fee_paid,
address requester,
uint256 remaining
);
struct RealitioQuestion {
uint256 bounty;
address disputer;
IMarket augur_market;
address owner;
}
mapping(bytes32 => RealitioQuestion) public realitio_questions;
modifier onlyInitialized() {
require(dispute_fee > 0, "The contract cannot be used until a dispute fee has been set");
_;
}
modifier onlyUninitialized() {
require(dispute_fee == 0, "The contract can only be initialized once");
_;
}
/// @notice Initialize a new contract
/// @param _realitio The address of the realitio contract you arbitrate for
/// @param _template_id The ID of the realitio template we support.
/// @param _dispute_fee The fee this contract will charge for resolution
/// @param _genesis_universe The earliest supported Augur universe
/// @param _market_token The token used by the market we create, typically Augur's wrapped ETH
function initialize(IRealitio _realitio, uint256 _template_id, uint256 _dispute_fee, IUniverse _genesis_universe, ICash _market_token)
onlyUninitialized
external {
require(_dispute_fee > 0, "You must provide a dispute fee");
require(_realitio != IRealitio(0x0), "You must provide a realitio address");
require(_genesis_universe != IUniverse(0x0), "You must provide a genesis universe");
require(_market_token != ICash(0x0), "You must provide an augur cash token");
dispute_fee = _dispute_fee;
template_id = _template_id;
realitio = _realitio;
latest_universe = _genesis_universe;
market_token = _market_token;
}
/// @notice Register a new child universe after a fork
/// @dev Anyone can create Augur universes but the "correct" ones should be in a single line from the official genesis universe
/// @dev If a universe goes into a forking state, someone will need to call this before you can create new markets.
function addForkedUniverse()
onlyInitialized
external {
IUniverse child_universe = IUniverse(latest_universe).getWinningChildUniverse();
latest_universe = child_universe;
}
/// @notice Trim the realitio question content to the part before the initial delimiter.
/// @dev The Realitio question is a list of parameters for a template.
/// @dev We throw away the subsequent parameters of the question.
/// @dev The first item in the (supported) template must be the title.
/// @dev Subsequent items (category, lang) aren't needed in Augur.
/// @dev This does not support more complex templates, eg selects which also need a list of answrs.
function _trimQuestion(string q)
internal pure returns (string) {
return q.toSlice().split(REALITIO_DELIMITER.toSlice()).toString();
}
function _callAugurMarketCreate(bytes32 question_id, string question, address designated_reporter)
internal {
realitio_questions[question_id].augur_market = latest_universe.createYesNoMarket.value(msg.value)( now, 0, market_token, designated_reporter, 0x0, _trimQuestion(question), "");
realitio_questions[question_id].owner = msg.sender;
}
/// @notice Create a market in Augur and store the creator as its owner
/// @dev Anyone can call this, and calling this will give them the rights to claim the bounty
/// @dev They will need have sent this contract some REP for the no-show bond.
/// @param question The question content (a delimited parameter list)
/// @param timeout The timeout between rounds, set when the question was created
/// @param opening_ts The opening timestamp for the question, set when the question was created
/// @param asker The address that created the question, ie the msg.sender of the original realitio.askQuestion call
/// @param nonce The nonce for the question, set when the question was created
/// @param designated_reporter The Augur designated reporter. We let the market creator choose this, if it's bad the Augur dispute resolution should sort it out
function createMarket(
string question, uint32 timeout, uint32 opening_ts, address asker, uint256 nonce,
address designated_reporter
)
onlyInitialized
external payable {
// Reconstruct the question ID from the content
bytes32 question_id = keccak256(keccak256(template_id, opening_ts, question), this, timeout, asker, nonce);
require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested (paid for)");
require(realitio_questions[question_id].augur_market == IMarket(0x0), "The market must not have been created yet");
// Create a market in Augur
_callAugurMarketCreate(question_id, question, designated_reporter);
}
/// @notice Return data needed to verify the last history item
/// @dev Filters the question struct from Realitio to stuff we need
/// @dev Broken out into its own function to avoid stack depth limitations
/// @param question_id The realitio question
/// @param last_history_hash The history hash when you gave your answer
/// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment
/// @param last_bond The bond paid in the last answer given
/// @param last_answerer The account that submitted the last answer (or its commitment)
/// @param is_commitment Whether the last answer was submitted with commit->reveal
function _verifyInput(
bytes32 question_id,
bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment
) internal view returns (bool, bytes32) {
require(realitio.isPendingArbitration(question_id), "The question must be pending arbitration in realitio");
bytes32 history_hash = realitio.getHistoryHash(question_id);
require(history_hash == keccak256(last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment), "The history parameters supplied must match the history hash in the realitio contract");
}
/// @notice Given the last history entry, get whether they had a valid answer if so what it was
/// @dev These just need to be fetched from Realitio, but they can't be fetched directly because we don't store them to save gas
/// @dev To get the final answer, we need to reconstruct the final answer using the history hash
/// @dev TODO: This should probably be in a library offered by Realitio
/// @param question_id The ID of the realitio question
/// @param last_history_hash The history hash when you gave your answer
/// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment
/// @param last_bond The bond paid in the last answer given
/// @param last_answerer The account that submitted the last answer (or its commitment)
/// @param is_commitment Whether the last answer was submitted with commit->reveal
function _answerData(
bytes32 question_id,
bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment
) internal view returns (bool, bytes32) {
bool is_pending_arbitration;
bytes32 history_hash;
// If the question hasn't been answered, nobody is ever right
if (last_bond == 0) {
return (false, bytes32(0));
}
bytes32 last_answer;
bool is_answered;
if (is_commitment) {
uint256 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
(reveal_ts, is_revealed, revealed_answer) = realitio.commitments(last_answer_or_commitment_id);
if (is_revealed) {
last_answer = revealed_answer;
is_answered = true;
} else {
// Shouldn't normally happen, but if the last answerer might still reveal when we are called, bail out and wait for them.
require(reveal_ts < uint32(now), "Arbitration cannot be done until the last answerer has had time to reveal their commitment");
is_answered = false;
}
} else {
last_answer = last_answer_or_commitment_id;
is_answered = true;
}
return (is_answered, last_answer);
}
/// @notice Get the answer from the Augur market and map it to a Realitio value
/// @param market The Augur market
function realitioAnswerFromAugurMarket(
IMarket market
)
onlyInitialized
public view returns (bytes32) {
bytes32 answer;
if (market.isInvalid()) {
answer = REALITIO_INVALID;
} else {
uint256 no_val = market.getWinningPayoutNumerator(AUGUR_NO_INDEX);
uint256 yes_val = market.getWinningPayoutNumerator(AUGUR_YES_INDEX);
if (yes_val == no_val) {
answer = REALITIO_INVALID;
} else {
if (yes_val > no_val) {
answer = REALITIO_YES;
} else {
answer = REALITIO_NO;
}
}
}
return answer;
}
/// @notice Report the answer from a finalized Augur market to a Realitio contract with a question awaiting arbitration
/// @dev Pays the arbitration bounty to whoever created the Augur market. Probably the same person will call this function, but they don't have to.
/// @dev We need to know who gave the final answer and what it was, as they need to be supplied as the arbitration winner if the last answer is right
/// @dev These just need to be fetched from Realitio, but they can't be fetched directly because to save gas, Realitio doesn't store them
/// @dev To get the final answer, we need to reconstruct the final answer using the history hash
/// @param question_id The ID of the question you're reporting on
/// @param last_history_hash The history hash when you gave your answer
/// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment
/// @param last_bond The bond paid in the last answer given
/// @param last_answerer The account that submitted the last answer (or its commitment)
/// @param is_commitment Whether the last answer was submitted with commit->reveal
function reportAnswer(
bytes32 question_id,
bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment
)
onlyInitialized
public {
IMarket market = realitio_questions[question_id].augur_market;
// There must be an open bounty
require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested for this question");
bool is_answered; // the answer was provided, not just left as an unrevealed commit
bytes32 last_answer;
_verifyInput(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment);
(is_answered, last_answer) = _answerData(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment);
require(market.isFinalized(), "The augur market must have been finalized");
bytes32 answer = realitioAnswerFromAugurMarket(market);
address winner;
if (is_answered && last_answer == answer) {
winner = last_answerer;
} else {
// If the final answer is wrong, we assign the person who paid for arbitration.
// See https://realitio.github.io/docs/html/arbitrators.html for why.
winner = realitio_questions[question_id].disputer;
}
realitio.submitAnswerByArbitrator(question_id, answer, winner);
address owner = realitio_questions[question_id].owner;
balanceOf[owner] += realitio_questions[question_id].bounty;
delete realitio_questions[question_id];
}
/// @notice Return the dispute fee for the specified question. 0 indicates that we won't arbitrate it.
/// @dev Uses a general default, but can be over-ridden on a question-by-question basis.
function getDisputeFee(bytes32)
external view returns (uint256) {
return dispute_fee;
}
/// @notice Request arbitration, freezing the question until we send submitAnswerByArbitrator
/// @dev The bounty can be paid only in part, in which case the last person to pay will be considered the payer
/// @dev Will trigger an error if the notification fails, eg because the question has already been finalized
/// @param question_id The question in question
/// @param max_previous The highest bond level we should accept (used to check the state hasn't changed)
function requestArbitration(bytes32 question_id, uint256 max_previous)
onlyInitialized
external payable returns (bool) {
require(msg.value >= dispute_fee, "The payment must cover the fee");
realitio.notifyOfArbitrationRequest(question_id, msg.sender, max_previous);
realitio_questions[question_id].bounty = msg.value;
realitio_questions[question_id].disputer = msg.sender;
LogRequestArbitration(question_id, msg.value, msg.sender, 0);
}
}
|
Request arbitration, freezing the question until we send submitAnswerByArbitrator The bounty can be paid only in part, in which case the last person to pay will be considered the payer Will trigger an error if the notification fails, eg because the question has already been finalized question_id The question in question max_previous The highest bond level we should accept (used to check the state hasn't changed)
|
function requestArbitration(bytes32 question_id, uint256 max_previous)
onlyInitialized
external payable returns (bool) {
require(msg.value >= dispute_fee, "The payment must cover the fee");
realitio.notifyOfArbitrationRequest(question_id, msg.sender, max_previous);
realitio_questions[question_id].bounty = msg.value;
realitio_questions[question_id].disputer = msg.sender;
LogRequestArbitration(question_id, msg.value, msg.sender, 0);
}
| 1,809,064
|
./partial_match/1/0x26E20682B06fCa0Ca16A62DA119C30c2581F1979/sources/BeepleCollectionTwo1Edition.sol
|
Returns an URI for a given token ID. Throws if the token ID does not exist. May return an empty string. tokenId uint256 ID of the token to query/
|
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
| 2,830,141
|
pragma solidity 0.4.18;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
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;
}
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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20Basic.sol
/**
* @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) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev 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];
}
/**
* 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
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
// File: contracts/OAKToken.sol
contract OAKToken is MintableToken {
string public name = "Acorn Collective Token";
string public symbol = "OAK";
uint256 public decimals = 18;
mapping(address => bool) public kycRequired;
// overriding MintableToken#mint to add kyc logic
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
kycRequired[_to] = true;
return super.mint(_to, _amount);
}
// overriding MintableToken#transfer to add kyc logic
function transfer(address _to, uint _value) public returns (bool) {
require(!kycRequired[msg.sender]);
return super.transfer(_to, _value);
}
// overriding MintableToken#transferFrom to add kyc logic
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(!kycRequired[_from]);
return super.transferFrom(_from, _to, _value);
}
function kycVerify(address participant) onlyOwner public {
kycRequired[participant] = false;
KycVerified(participant);
}
event KycVerified(address indexed participant);
}
// File: contracts/Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
OAKToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
event CrowdSaleTokenContractCreation();
// creates the token to be sold.
function createTokenContract() internal returns (OAKToken) {
OAKToken newToken = new OAKToken();
CrowdSaleTokenContractCreation();
return newToken;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
// File: contracts/FinalizableCrowdsale.sol
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: contracts/OAKTokenCrowdsale.sol
contract OAKTokenCrowdsale is FinalizableCrowdsale, Pausable {
uint256 public restrictedPercent;
address public restricted;
uint256 public soldTokens;
uint256 public hardCap;
uint256 public vipRate;
uint256 public totalTokenSupply;
mapping(address => bool) public vip;
//TokenTimelock logic
uint256 public Y1_lockedTokenReleaseTime;
uint256 public Y1_lockedTokenAmount;
uint256 public Y2_lockedTokenReleaseTime;
uint256 public Y2_lockedTokenAmount;
// constructor
function OAKTokenCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public
Crowdsale(_startTime, _endTime, _rate, _wallet) {
// total token supply for sales
totalTokenSupply = 75000000 * 10 ** 18;
// hardCap for pre-sale
hardCap = 7000000 * 10 ** 18;
vipRate = _rate;
soldTokens = 0;
restrictedPercent = 20;
restricted = msg.sender;
}
// update hardCap for sale
function setHardCap(uint256 _hardCap) public onlyOwner {
require(!isFinalized);
require(_hardCap >= 0 && _hardCap <= totalTokenSupply);
hardCap = _hardCap;
}
// update address where funds are collected
function setWalletAddress(address _wallet) public onlyOwner {
require(!isFinalized);
wallet = _wallet;
}
// update token units a buyer gets per wei
function setRate(uint256 _rate) public onlyOwner {
require(!isFinalized);
require(_rate > 0);
rate = _rate;
}
// update token units a vip buyer gets per wei
function setVipRate(uint256 _vipRate) public onlyOwner {
require(!isFinalized);
require(_vipRate > 0);
vipRate = _vipRate;
}
// add VIP buyer address
function setVipAddress(address _address) public onlyOwner {
vip[_address] = true;
}
// remove VIP buyer address
function unsetVipAddress(address _address) public onlyOwner {
vip[_address] = false;
}
// update startTime, endTime for post-sales
function setSalePeriod(uint256 _startTime, uint256 _endTime) public onlyOwner {
require(!isFinalized);
require(_startTime > 0);
require(_endTime > _startTime);
startTime = _startTime;
endTime = _endTime;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// overriding Crowdsale#buyTokens to add pausable sales and vip logic
function buyTokens(address beneficiary) public whenNotPaused payable {
require(beneficiary != address(0));
require(!isFinalized);
uint256 weiAmount = msg.value;
uint tokens;
if(vip[msg.sender] == true){
tokens = weiAmount.mul(vipRate);
}else{
tokens = weiAmount.mul(rate);
}
require(validPurchase(tokens));
soldTokens = soldTokens.add(tokens);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// overriding Crowdsale#validPurchase to add capped sale logic
// @return true if the transaction can buy tokens
function validPurchase(uint256 tokens) internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool withinCap = soldTokens.add(tokens) <= hardCap;
bool withinTotalSupply = soldTokens.add(tokens) <= totalTokenSupply;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase && withinCap && withinTotalSupply;
}
// overriding FinalizableCrowdsale#finalization to add 20% of sold token for owner
function finalization() internal {
// mint locked token to Crowdsale contract
uint256 restrictedTokens = soldTokens.div(100).mul(restrictedPercent);
token.mint(this, restrictedTokens);
token.kycVerify(this);
Y1_lockedTokenReleaseTime = now + 1 years;
Y1_lockedTokenAmount = restrictedTokens.div(2);
Y2_lockedTokenReleaseTime = now + 2 years;
Y2_lockedTokenAmount = restrictedTokens.div(2);
// stop minting new tokens
token.finishMinting();
// transfer the contract ownership to OAKTokenCrowdsale.owner
token.transferOwnership(owner);
}
// release the 1st year locked token
function Y1_release() onlyOwner public {
require(Y1_lockedTokenAmount > 0);
require(now > Y1_lockedTokenReleaseTime);
// transfer the locked token to restricted
token.transfer(restricted, Y1_lockedTokenAmount);
Y1_lockedTokenAmount = 0;
}
// release the 2nd year locked token
function Y2_release() onlyOwner public {
require(Y1_lockedTokenAmount == 0);
require(Y2_lockedTokenAmount > 0);
require(now > Y2_lockedTokenReleaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
// transfer the locked token to restricted
token.transfer(restricted, amount);
Y2_lockedTokenAmount = 0;
}
function kycVerify(address participant) onlyOwner public {
token.kycVerify(participant);
}
function addPrecommitment(address participant, uint balance) onlyOwner public {
require(!isFinalized);
require(balance > 0);
// Check if the total token supply will be exceeded
require(soldTokens.add(balance) <= totalTokenSupply);
soldTokens = soldTokens.add(balance);
token.mint(participant, balance);
}
}
|
overriding MintableTokentransferFrom to add kyc logic
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(!kycRequired[_from]);
return super.transferFrom(_from, _to, _value);
}
| 15,171,661
|
./full_match/5/0xc962E67D9490E154D81181879ddf4CD3b65D2132/sources/contracts/base/FallbackManager.sol
|
Internal function to set the fallback handler. handler contract to handle fallback calls.// solhint-disable-next-line no-inline-assembly
|
function internalSetFallbackHandler(address handler) internal {
If a fallback handler is set to self, then the following attack vector is opened:
Imagine we have a function like this:
function withdraw() internal authorized {
withdrawalAddress.call.value(address(this).balance)("");
}
If the fallback method is triggered, the fallback handler appends the msg.sender address to the calldata and calls the fallback handler.
A potential attacker could call a Safe with the 3 bytes signature of a withdraw function. Since 3 bytes do not create a valid signature,
the call would end in a fallback handler. Since it appends the msg.sender address to the calldata, the attacker could craft an address
where the first 3 bytes of the previous calldata + the first byte of the address make up a valid function signature. The subsequent call would result in unsanctioned access to Safe's internal protected methods.
For some reason, solidity matches the first 4 bytes of the calldata to a function signature, regardless if more data follow these 4 bytes.
require(handler != address(this), "GS400");
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
assembly {
sstore(slot, handler)
}
}
| 1,889,559
|
./partial_match/3/0x40425Ec0329201354193850B75737ad44f9073A5/sources/MicahsToken.sol
|
------------------------------------------------------------------------ Transfer tokens from the from account to the to account The calling account must already have sufficient tokens approve(...)-d for spending from the from account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
|
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| 5,257,192
|
./full_match/5/0x837bD61CE00E657Ed53a998b5E3e77A5a3bb608a/sources/project_/contracts/poolAddress.sol
|
Create and store our loan into the mapping Store loan inside borrower loans mapping Increment loan id
|
function loanRequest(
address _lendingToken,
uint256 _poolId,
uint256 _principal,
uint32 _duration,
uint16 _APR,
address _receiver
) public returns (uint256 loanId_) {
(bool isVerified, ) = poolRegistry(poolRegistryAddress)
.borrowerVarification(_poolId, msg.sender);
require(isVerified, "Not verified borrower");
require(
!poolRegistry(poolRegistryAddress).ClosedPool(_poolId),
"Pool is closed"
);
loanId_ = loanId;
poolLoans[_poolId] = loanId_;
Loan storage loan = loans[loanId];
loan.borrower = msg.sender;
loan.receiver = _receiver != address(0) ? _receiver : loan.borrower;
loan.poolId = _poolId;
loan.loanDetails.lendingToken = ERC20(_lendingToken);
loan.loanDetails.principal = _principal;
loan.loanDetails.loanDuration = _duration;
loan.loanDetails.timestamp = uint32(block.timestamp);
loan.terms.paymentCycle = poolRegistry(poolRegistryAddress)
.getPaymentCycleDuration(_poolId);
loan.terms.APR = _APR;
loanDefaultDuration[loanId] = poolRegistry(poolRegistryAddress)
.getPaymentDefaultDuration(_poolId);
loanExpirationTime[loanId] = poolRegistry(poolRegistryAddress)
.getloanExpirationTime(_poolId);
loan.terms.paymentCycleAmount = LibCalculations.payment(
_principal,
_duration,
loan.terms.paymentCycle,
_APR
);
loan.state = LoanState.PENDING;
emit SubmittedLoan(
loanId,
loan.borrower,
loan.receiver,
loan.terms.paymentCycleAmount
);
borrowerLoans[loan.borrower].push(loanId);
loanId++;
}
| 11,588,803
|
/**
*Submitted for verification at Etherscan.io on 2020-08-19
*/
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2020 zapper, nodar, suhail, seb, sumit, apoorv
// 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 2 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.
//
///@author Zapper
///@notice This contract adds liquidity to Uniswap V2 pools using ETH or any ERC20 Token.
// SPDX-License-Identifier: GPLv2
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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
);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
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"
);
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 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"
);
}
}
}
// File: contracts\UniswapV2\UniswapV2_ETH_ERC_Zap_In_V3.sol
// File: UniswapV2Router.sol
pragma solidity 0.5.12;
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// File: OpenZepplinReentrancyGuard.sol
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.
*
* _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;
}
}
// File: Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: OpenZepplinOwnable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address payable public _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address payable 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address payable newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// import "@uniswap/lib/contracts/libraries/Babylonian.sol";
library Babylonian {
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
interface IUniswapV1Factory {
function getExchange(address token)
external
view
returns (address exchange);
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface IUniswapExchange {
// converting ERC20 to ERC20 and transfer
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external returns (uint256 tokens_bought);
function tokenToTokenSwapInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address token_addr
) external returns (uint256 tokens_bought);
function getEthToTokenInputPrice(uint256 eth_sold)
external
view
returns (uint256 tokens_bought);
function getTokenToEthInputPrice(uint256 tokens_sold)
external
view
returns (uint256 eth_bought);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external returns (uint256 eth_bought);
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline)
external
payable
returns (uint256 tokens_bought);
function ethToTokenTransferInput(
uint256 min_tokens,
uint256 deadline,
address recipient
) external payable returns (uint256 tokens_bought);
function balanceOf(address _owner) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
contract UniswapV2_ZapIn_General_V2_3 is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for IERC20;
bool public stopped = false;
uint16 public goodwill;
address
private constant zgoodwillAddress = 0xE737b6AfEC2320f616297e59445b60a11e3eF75F;
IUniswapV2Router02 private constant uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
IUniswapV1Factory
private constant UniSwapV1FactoryAddress = IUniswapV1Factory(
0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95
);
IUniswapV2Factory
private constant UniSwapV2FactoryAddress = IUniswapV2Factory(
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
);
address
private constant wethTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
constructor(uint16 _goodwill) public {
goodwill = _goodwill;
}
// circuit breaker modifiers
modifier stopInEmergency {
if (stopped) {
revert("Temporarily Paused");
} else {
_;
}
}
/**
@notice This function is used to invest in given Uniswap V2 pair through ETH/ERC20 Tokens
@param _FromTokenContractAddress The ERC20 token used for investment (address(0x00) if ether)
@param _ToUnipoolToken0 The Uniswap V2 pair token0 address
@param _ToUnipoolToken1 The Uniswap V2 pair token1 address
@param _amount The amount of fromToken to invest
@param _minPoolTokens Reverts if less tokens received than this
@return Amount of LP bought
*/
function ZapIn(
address _toWhomToIssue,
address _FromTokenContractAddress,
address _ToUnipoolToken0,
address _ToUnipoolToken1,
uint256 _amount,
uint256 _minPoolTokens
) public payable nonReentrant stopInEmergency returns (uint256) {
uint256 toInvest;
if (_FromTokenContractAddress == address(0)) {
require(msg.value > 0, "Error: ETH not sent");
toInvest = msg.value;
} else {
require(msg.value == 0, "Error: ETH sent");
require(_amount > 0, "Error: Invalid ERC amount");
IERC20(_FromTokenContractAddress).safeTransferFrom(
msg.sender,
address(this),
_amount
);
toInvest = _amount;
}
uint256 LPBought = _performZapIn(
_toWhomToIssue,
_FromTokenContractAddress,
_ToUnipoolToken0,
_ToUnipoolToken1,
toInvest
);
require(LPBought >= _minPoolTokens, "ERR: High Slippage");
//get pair address
address _ToUniPoolAddress = UniSwapV2FactoryAddress.getPair(
_ToUnipoolToken0,
_ToUnipoolToken1
);
//transfer goodwill
uint256 goodwillPortion = _transferGoodwill(
_ToUniPoolAddress,
LPBought
);
IERC20(_ToUniPoolAddress).safeTransfer(
_toWhomToIssue,
SafeMath.sub(LPBought, goodwillPortion)
);
return SafeMath.sub(LPBought, goodwillPortion);
}
function _performZapIn(
address _toWhomToIssue,
address _FromTokenContractAddress,
address _ToUnipoolToken0,
address _ToUnipoolToken1,
uint256 _amount
) internal returns (uint256) {
uint256 token0Bought;
uint256 token1Bought;
if (canSwapFromV2(_ToUnipoolToken0, _ToUnipoolToken1)) {
(token0Bought, token1Bought) = exchangeTokensV2(
_FromTokenContractAddress,
_ToUnipoolToken0,
_ToUnipoolToken1,
_amount
);
} else if (
canSwapFromV1(_ToUnipoolToken0, _ToUnipoolToken1, _amount, _amount)
) {
(token0Bought, token1Bought) = exchangeTokensV1(
_FromTokenContractAddress,
_ToUnipoolToken0,
_ToUnipoolToken1,
_amount
);
}
require(token0Bought > 0 && token1Bought > 0, "Could not exchange");
IERC20(_ToUnipoolToken0).safeApprove(
address(uniswapV2Router),
token0Bought
);
IERC20(_ToUnipoolToken1).safeApprove(
address(uniswapV2Router),
token1Bought
);
(uint256 amountA, uint256 amountB, uint256 LP) = uniswapV2Router
.addLiquidity(
_ToUnipoolToken0,
_ToUnipoolToken1,
token0Bought,
token1Bought,
1,
1,
address(this),
now + 60
);
//Reset allowance to zero
IERC20(_ToUnipoolToken0).safeApprove(address(uniswapV2Router), 0);
IERC20(_ToUnipoolToken1).safeApprove(address(uniswapV2Router), 0);
uint256 residue;
if (SafeMath.sub(token0Bought, amountA) > 0) {
if (canSwapFromV2(_ToUnipoolToken0, _FromTokenContractAddress)) {
residue = swapFromV2(
_ToUnipoolToken0,
_FromTokenContractAddress,
SafeMath.sub(token0Bought, amountA)
);
} else {
IERC20(_ToUnipoolToken0).safeTransfer(
_toWhomToIssue,
SafeMath.sub(token0Bought, amountA)
);
}
}
if (SafeMath.sub(token1Bought, amountB) > 0) {
if (canSwapFromV2(_ToUnipoolToken1, _FromTokenContractAddress)) {
residue += swapFromV2(
_ToUnipoolToken1,
_FromTokenContractAddress,
SafeMath.sub(token1Bought, amountB)
);
} else {
IERC20(_ToUnipoolToken1).safeTransfer(
_toWhomToIssue,
SafeMath.sub(token1Bought, amountB)
);
}
}
if (residue > 0) {
if (_FromTokenContractAddress != address(0)) {
IERC20(_FromTokenContractAddress).safeTransfer(
_toWhomToIssue,
residue
);
} else {
(bool success, ) = _toWhomToIssue.call.value(residue)("");
require(success, "Residual ETH Transfer failed.");
}
}
return LP;
}
function exchangeTokensV1(
address _FromTokenContractAddress,
address _ToUnipoolToken0,
address _ToUnipoolToken1,
uint256 _amount
) internal returns (uint256 token0Bought, uint256 token1Bought) {
IUniswapV2Pair pair = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_ToUnipoolToken0, _ToUnipoolToken1)
);
(uint256 res0, uint256 res1, ) = pair.getReserves();
if (_FromTokenContractAddress == address(0)) {
token0Bought = _eth2Token(_ToUnipoolToken0, _amount);
uint256 amountToSwap = calculateSwapInAmount(res0, token0Bought);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = SafeMath.div(token0Bought, 2);
token1Bought = _eth2Token(_ToUnipoolToken1, amountToSwap);
token0Bought = SafeMath.sub(token0Bought, amountToSwap);
} else {
if (_ToUnipoolToken0 == _FromTokenContractAddress) {
uint256 amountToSwap = calculateSwapInAmount(res0, _amount);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = SafeMath.div(_amount, 2);
token1Bought = _token2Token(
_FromTokenContractAddress,
address(this),
_ToUnipoolToken1,
amountToSwap
);
token0Bought = SafeMath.sub(_amount, amountToSwap);
} else if (_ToUnipoolToken1 == _FromTokenContractAddress) {
uint256 amountToSwap = calculateSwapInAmount(res1, _amount);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = SafeMath.div(_amount, 2);
token0Bought = _token2Token(
_FromTokenContractAddress,
address(this),
_ToUnipoolToken0,
amountToSwap
);
token1Bought = SafeMath.sub(_amount, amountToSwap);
} else {
token0Bought = _token2Token(
_FromTokenContractAddress,
address(this),
_ToUnipoolToken0,
_amount
);
uint256 amountToSwap = calculateSwapInAmount(
res0,
token0Bought
);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = SafeMath.div(_amount, 2);
token1Bought = _token2Token(
_FromTokenContractAddress,
address(this),
_ToUnipoolToken1,
amountToSwap
);
token0Bought = SafeMath.sub(token0Bought, amountToSwap);
}
}
}
function exchangeTokensV2(
address _FromTokenContractAddress,
address _ToUnipoolToken0,
address _ToUnipoolToken1,
uint256 _amount
) internal returns (uint256 token0Bought, uint256 token1Bought) {
IUniswapV2Pair pair = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_ToUnipoolToken0, _ToUnipoolToken1)
);
(uint256 res0, uint256 res1, ) = pair.getReserves();
if (
canSwapFromV2(_FromTokenContractAddress, _ToUnipoolToken0) &&
canSwapFromV2(_ToUnipoolToken0, _ToUnipoolToken1)
) {
token0Bought = swapFromV2(
_FromTokenContractAddress,
_ToUnipoolToken0,
_amount
);
uint256 amountToSwap = calculateSwapInAmount(res0, token0Bought);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = SafeMath.div(token0Bought, 2);
token1Bought = swapFromV2(
_ToUnipoolToken0,
_ToUnipoolToken1,
amountToSwap
);
token0Bought = SafeMath.sub(token0Bought, amountToSwap);
} else if (
canSwapFromV2(_FromTokenContractAddress, _ToUnipoolToken1) &&
canSwapFromV2(_ToUnipoolToken0, _ToUnipoolToken1)
) {
token1Bought = swapFromV2(
_FromTokenContractAddress,
_ToUnipoolToken1,
_amount
);
uint256 amountToSwap = calculateSwapInAmount(res1, token1Bought);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = SafeMath.div(token1Bought, 2);
token0Bought = swapFromV2(
_ToUnipoolToken1,
_ToUnipoolToken0,
amountToSwap
);
token1Bought = SafeMath.sub(token1Bought, amountToSwap);
}
}
//checks if tokens can be exchanged with UniV1
function canSwapFromV1(
address _fromToken,
address _toToken,
uint256 fromAmount,
uint256 toAmount
) public view returns (bool) {
require(
_fromToken != address(0) || _toToken != address(0),
"Invalid Exchange values"
);
if (_fromToken == address(0)) {
IUniswapExchange toExchange = IUniswapExchange(
UniSwapV1FactoryAddress.getExchange(_toToken)
);
uint256 tokenBalance = IERC20(_toToken).balanceOf(
address(toExchange)
);
uint256 ethBalance = address(toExchange).balance;
if (tokenBalance > toAmount && ethBalance > fromAmount) return true;
} else if (_toToken == address(0)) {
IUniswapExchange fromExchange = IUniswapExchange(
UniSwapV1FactoryAddress.getExchange(_fromToken)
);
uint256 tokenBalance = IERC20(_fromToken).balanceOf(
address(fromExchange)
);
uint256 ethBalance = address(fromExchange).balance;
if (tokenBalance > fromAmount && ethBalance > toAmount) return true;
} else {
IUniswapExchange toExchange = IUniswapExchange(
UniSwapV1FactoryAddress.getExchange(_toToken)
);
IUniswapExchange fromExchange = IUniswapExchange(
UniSwapV1FactoryAddress.getExchange(_fromToken)
);
uint256 balance1 = IERC20(_fromToken).balanceOf(
address(fromExchange)
);
uint256 balance2 = IERC20(_toToken).balanceOf(address(toExchange));
if (balance1 > fromAmount && balance2 > toAmount) return true;
}
return false;
}
//checks if tokens can be exchanged with UniV2
function canSwapFromV2(address _fromToken, address _toToken)
public
view
returns (bool)
{
require(
_fromToken != address(0) || _toToken != address(0),
"Invalid Exchange values"
);
if (_fromToken == _toToken) return true;
if (_fromToken == address(0) || _fromToken == wethTokenAddress) {
if (_toToken == wethTokenAddress || _toToken == address(0))
return true;
IUniswapV2Pair pair = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_toToken, wethTokenAddress)
);
if (_haveReserve(pair)) return true;
} else if (_toToken == address(0) || _toToken == wethTokenAddress) {
if (_fromToken == wethTokenAddress || _fromToken == address(0))
return true;
IUniswapV2Pair pair = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_fromToken, wethTokenAddress)
);
if (_haveReserve(pair)) return true;
} else {
IUniswapV2Pair pair1 = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_fromToken, wethTokenAddress)
);
IUniswapV2Pair pair2 = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_toToken, wethTokenAddress)
);
IUniswapV2Pair pair3 = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_fromToken, _toToken)
);
if (_haveReserve(pair1) && _haveReserve(pair2)) return true;
if (_haveReserve(pair3)) return true;
}
return false;
}
//checks if the UNI v2 contract have reserves to swap tokens
function _haveReserve(IUniswapV2Pair pair) internal view returns (bool) {
if (address(pair) != address(0)) {
(uint256 res0, uint256 res1, ) = pair.getReserves();
if (res0 > 0 && res1 > 0) {
return true;
}
}
}
function calculateSwapInAmount(uint256 reserveIn, uint256 userIn)
public
pure
returns (uint256)
{
return
Babylonian
.sqrt(
reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009))
)
.sub(reserveIn.mul(1997)) / 1994;
}
//swaps _fromToken for _toToken
//for eth, address(0) otherwise ERC token address
function swapFromV2(
address _fromToken,
address _toToken,
uint256 amount
) internal returns (uint256) {
require(
_fromToken != address(0) || _toToken != address(0),
"Invalid Exchange values"
);
if (_fromToken == _toToken) return amount;
require(canSwapFromV2(_fromToken, _toToken), "Cannot be exchanged");
require(amount > 0, "Invalid amount");
if (_fromToken == address(0)) {
if (_toToken == wethTokenAddress) {
IWETH(wethTokenAddress).deposit.value(amount)();
return amount;
}
address[] memory path = new address[](2);
path[0] = wethTokenAddress;
path[1] = _toToken;
uint256[] memory amounts = uniswapV2Router
.swapExactETHForTokens
.value(amount)(0, path, address(this), now + 180);
return amounts[1];
} else if (_toToken == address(0)) {
if (_fromToken == wethTokenAddress) {
IWETH(wethTokenAddress).withdraw(amount);
return amount;
}
address[] memory path = new address[](2);
IERC20(_fromToken).safeApprove(address(uniswapV2Router), amount);
path[0] = _fromToken;
path[1] = wethTokenAddress;
uint256[] memory amounts = uniswapV2Router.swapExactTokensForETH(
amount,
0,
path,
address(this),
now + 180
);
IERC20(_fromToken).safeApprove(address(uniswapV2Router), 0);
return amounts[1];
} else {
IERC20(_fromToken).safeApprove(address(uniswapV2Router), amount);
uint256 returnedAmount = _swapTokenToTokenV2(
_fromToken,
_toToken,
amount
);
IERC20(_fromToken).safeApprove(address(uniswapV2Router), 0);
require(returnedAmount > 0, "Error in swap");
return returnedAmount;
}
}
//swaps 2 ERC tokens (UniV2)
function _swapTokenToTokenV2(
address _fromToken,
address _toToken,
uint256 amount
) internal returns (uint256) {
IUniswapV2Pair pair1 = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_fromToken, wethTokenAddress)
);
IUniswapV2Pair pair2 = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_toToken, wethTokenAddress)
);
IUniswapV2Pair pair3 = IUniswapV2Pair(
UniSwapV2FactoryAddress.getPair(_fromToken, _toToken)
);
uint256[] memory amounts;
if (_haveReserve(pair3)) {
address[] memory path = new address[](2);
path[0] = _fromToken;
path[1] = _toToken;
amounts = uniswapV2Router.swapExactTokensForTokens(
amount,
0,
path,
address(this),
now + 180
);
return amounts[1];
} else if (_haveReserve(pair1) && _haveReserve(pair2)) {
address[] memory path = new address[](3);
path[0] = _fromToken;
path[1] = wethTokenAddress;
path[2] = _toToken;
amounts = uniswapV2Router.swapExactTokensForTokens(
amount,
0,
path,
address(this),
now + 180
);
return amounts[2];
}
return 0;
}
/**
@notice This function is used to buy tokens from eth
@param _tokenContractAddress Token address which we want to buy
@param _amount The amount of eth we want to exchange
@return The quantity of token bought
*/
function _eth2Token(address _tokenContractAddress, uint256 _amount)
internal
returns (uint256 tokenBought)
{
IUniswapExchange FromUniSwapExchangeContractAddress = IUniswapExchange(
UniSwapV1FactoryAddress.getExchange(_tokenContractAddress)
);
tokenBought = FromUniSwapExchangeContractAddress
.ethToTokenSwapInput
.value(_amount)(0, SafeMath.add(now, 300));
}
/**
@notice This function is used to swap token with ETH
@param _FromTokenContractAddress The token address to swap from
@param tokens2Trade The quantity of tokens to swap
@return The amount of eth bought
*/
function _token2Eth(
address _FromTokenContractAddress,
uint256 tokens2Trade,
address _toWhomToIssue
) internal returns (uint256 ethBought) {
IUniswapExchange FromUniSwapExchangeContractAddress = IUniswapExchange(
UniSwapV1FactoryAddress.getExchange(_FromTokenContractAddress)
);
IERC20(_FromTokenContractAddress).safeApprove(
address(FromUniSwapExchangeContractAddress),
tokens2Trade
);
ethBought = FromUniSwapExchangeContractAddress.tokenToEthTransferInput(
tokens2Trade,
0,
SafeMath.add(now, 300),
_toWhomToIssue
);
require(ethBought > 0, "Error in swapping Eth: 1");
IERC20(_FromTokenContractAddress).safeApprove(
address(FromUniSwapExchangeContractAddress),
0
);
}
/**
@notice This function is used to swap tokens
@param _FromTokenContractAddress The token address to swap from
@param _ToWhomToIssue The address to transfer after swap
@param _ToTokenContractAddress The token address to swap to
@param tokens2Trade The quantity of tokens to swap
@return The amount of tokens returned after swap
*/
function _token2Token(
address _FromTokenContractAddress,
address _ToWhomToIssue,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
IUniswapExchange FromUniSwapExchangeContractAddress = IUniswapExchange(
UniSwapV1FactoryAddress.getExchange(_FromTokenContractAddress)
);
IERC20(_FromTokenContractAddress).safeApprove(
address(FromUniSwapExchangeContractAddress),
tokens2Trade
);
tokenBought = FromUniSwapExchangeContractAddress
.tokenToTokenTransferInput(
tokens2Trade,
0,
0,
SafeMath.add(now, 300),
_ToWhomToIssue,
_ToTokenContractAddress
);
require(tokenBought > 0, "Error in swapping ERC: 1");
IERC20(_FromTokenContractAddress).safeApprove(
address(FromUniSwapExchangeContractAddress),
0
);
}
/**
@notice This function is used to calculate and transfer goodwill
@param _tokenContractAddress Token in which goodwill is deducted
@param tokens2Trade The total amount of tokens to be zapped in
@return The quantity of goodwill deducted
*/
function _transferGoodwill(
address _tokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 goodwillPortion) {
goodwillPortion = SafeMath.div(
SafeMath.mul(tokens2Trade, goodwill),
10000
);
if (goodwillPortion == 0) {
return 0;
}
IERC20(_tokenContractAddress).safeTransfer(
zgoodwillAddress,
goodwillPortion
);
}
function set_new_goodwill(uint16 _new_goodwill) public onlyOwner {
require(
_new_goodwill >= 0 && _new_goodwill < 10000,
"GoodWill Value not allowed"
);
goodwill = _new_goodwill;
}
function inCaseTokengetsStuck(IERC20 _TokenAddress) public onlyOwner {
uint256 qty = _TokenAddress.balanceOf(address(this));
_TokenAddress.safeTransfer(owner(), qty);
}
// - to Pause the contract
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
// - to withdraw any ETH balance sitting in the contract
function withdraw() public onlyOwner {
uint256 contractBalance = address(this).balance;
address payable _to = owner().toPayable();
_to.transfer(contractBalance);
}
function() external payable {}
}
|
converting ERC20 to ERC20 and transfer
|
interface IUniswapExchange {
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external returns (uint256 tokens_bought);
function tokenToTokenSwapInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address token_addr
) external returns (uint256 tokens_bought);
function getEthToTokenInputPrice(uint256 eth_sold)
external
view
returns (uint256 tokens_bought);
function getTokenToEthInputPrice(uint256 tokens_sold)
external
view
returns (uint256 eth_bought);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external returns (uint256 eth_bought);
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline)
external
payable
returns (uint256 tokens_bought);
function ethToTokenTransferInput(
uint256 min_tokens,
uint256 deadline,
address recipient
) external payable returns (uint256 tokens_bought);
function balanceOf(address _owner) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
}
| 1,498,294
|
./partial_match/1/0x236fd03Cf1Be356b6B9DEF63c00293fA053fA121/sources/TokenGeyserManager.sol
|
SPDX-License-Identifier: MIT Staking interface, as defined by EIP-900./
|
interface IStaking {
event Staked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
event Unstaked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
function unstake(address staker, uint256 amount, bytes calldata data) external;
function totalStakedFor(address addr) external view returns (uint256);
function totalStaked() external view returns (uint256);
function token() external view returns (address);
function supportsHistory() external pure returns (bool);
}
| 3,914,334
|
./full_match/5/0xeF78f20cDE58EfC8193C5A3077696d115809Ca5F/sources/src/ERC721SeaDrop.sol
|
Update the server-side signers for this nft contract on SeaDrop. Only the owner can use this function. seaDropImpl The allowed SeaDrop contract. signer The signer to update. signedMintValidationParams Minimum and maximum parameters to enforce for signed mints./ Ensure the sender is only the owner or contract itself. Ensure the SeaDrop is allowed. Update the signer.
|
function updateSignedMintValidationParams(
address seaDropImpl,
address signer,
SignedMintValidationParams memory signedMintValidationParams
) external virtual override {
_onlyOwnerOrSelf();
_onlyAllowedSeaDrop(seaDropImpl);
ISeaDrop(seaDropImpl).updateSignedMintValidationParams(
signer,
signedMintValidationParams
);
}
| 1,887,598
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./interfaces/IDAOAccessControl.sol";
/// @title DAO Access Control
/// @notice Use this contract for managing DAO role based permissions
contract DAOAccessControl is IDAOAccessControl, ERC165, UUPSUpgradeable {
string public constant DAO_ROLE = "DAO_ROLE";
string public constant OPEN_ROLE = "OPEN_ROLE";
mapping(string => RoleData) private _roles;
mapping(address => mapping(bytes4 => string[])) private _actionsToRoles;
/// @notice Modifier that checks that an account has a specific role. Reverts
/// with a standardized message including the required role.
modifier onlyRole(string memory role) {
_checkRole(role, msg.sender);
_;
}
/// @notice Initialize DAO action and role permissions
/// @param dao Address to receive DAO role
/// @param roles What permissions are assigned to
/// @param roleAdmins Roles which have the ability to remove or add members
/// @param members Addresses to be granted the specified roles
/// @param targets Contract addresses for actions to be defined on
/// @param functionDescs Function descriptions used to define actions
/// @param actionRoles Roles being granted permission for an action
function initialize(
address dao,
string[] memory roles,
string[] memory roleAdmins,
address[][] memory members,
address[] memory targets,
string[] memory functionDescs,
string[][] memory actionRoles
) external initializer {
if (
roles.length != roleAdmins.length ||
roles.length != members.length ||
targets.length != functionDescs.length ||
targets.length != functionDescs.length
) revert UnequalArrayLengths();
_grantRole(DAO_ROLE, dao);
_grantRolesAndAdmins(roles, roleAdmins, members);
_addActionsRoles(targets, functionDescs, actionRoles);
__UUPSUpgradeable_init();
}
/// @notice Grants roles to the specified addresses and defines admin roles
/// @param roles The roles being granted
/// @param roleAdmins The roles being granted as admins of the specified of roles
/// @param members Addresses being granted each specified role
function grantRolesAndAdmins(
string[] memory roles,
string[] memory roleAdmins,
address[][] memory members
) external onlyRole(DAO_ROLE) {
_grantRolesAndAdmins(roles, roleAdmins, members);
}
/// @notice Grants roles to the specified addresses
/// @param roles The roles being granted
/// @param members Addresses being granted each specified role
function grantRoles(string[] memory roles, address[][] memory members)
external
onlyRole(DAO_ROLE)
{
_grantRoles(roles, members);
}
/// @notice Grants a role to the specified address
/// @param role The role being granted
/// @param account The address being granted the specified role
function grantRole(string memory role, address account)
external
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/// @notice Revokes a role from the specified address
/// @param role The role being revoked
/// @param account The address the role is being revoked from
function revokeRole(string memory role, address account)
external
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/// @notice Enables an address to remove one of its own roles
/// @param role The role being renounced
/// @param account The address renouncing the role
function renounceRole(string memory role, address account) external {
if (account != msg.sender) {
revert OnlySelfRenounce();
}
_revokeRole(role, account);
}
/// @notice Authorizes roles to execute the specified actions
/// @param targets The contract addresses that the action functions are implemented on
/// @param functionDescs The function descriptions used to define the actions
/// @param roles Roles being granted permission for an action
function addActionsRoles(
address[] memory targets,
string[] memory functionDescs,
string[][] memory roles
) external onlyRole(DAO_ROLE) {
_addActionsRoles(targets, functionDescs, roles);
}
/// @notice Removes autorization for roles to execute the specified actions
/// @param targets The contract addresses that the action functions are implemented on
/// @param functionDescs The function description used to define the actions
/// @param roles Roles that action permissions are being removed on
function removeActionsRoles(
address[] memory targets,
string[] memory functionDescs,
string[][] memory roles
) external onlyRole(DAO_ROLE) {
if (targets.length != functionDescs.length)
revert UnequalArrayLengths();
if (targets.length != roles.length) revert UnequalArrayLengths();
uint256 actionsLength = targets.length;
for (uint256 i = 0; i < actionsLength; ) {
uint256 rolesLength = roles[i].length;
for (uint256 j = 0; j < rolesLength; ) {
_removeActionRole(targets[i], functionDescs[i], roles[i][j]);
unchecked {
j++;
}
}
unchecked {
i++;
}
}
}
/// @notice Checks if a caller has the permissions to execute the specific action
/// @param caller Address attempting to execute the action
/// @param target Contract address corresponding to the action
/// @param sig The function signature used to define the action
function actionIsAuthorized(
address caller,
address target,
bytes4 sig
) external view returns (bool isAuthorized) {
string[] memory roles = _actionsToRoles[target][sig];
uint256 roleLength = roles.length;
for (uint256 i = 0; i < roleLength; ) {
if (hasRole(roles[i], caller)) {
isAuthorized = true;
break;
}
unchecked {
i++;
}
}
}
/// @notice Returns the roles autorized to execute the specified action
/// @param target Contract address corresponding to the action
/// @param functionDesc The function description used to define the action
function getActionRoles(address target, string memory functionDesc)
external
view
returns (string[] memory roles)
{
bytes4 encodedSig = bytes4(keccak256(abi.encodePacked(functionDesc)));
return _actionsToRoles[target][encodedSig];
}
/// @notice Checks if a specific role is authorized for an action
/// @param role Role that authorization is being checked on
/// @param target Contract address corresponding to the action
/// @param functionDesc Function description used to define the action
/// @return isAuthorized Indicates whether the role is authorized to execute the action
function isRoleAuthorized(
string calldata role,
address target,
string memory functionDesc
) external view returns (bool isAuthorized) {
bytes4 encodedSig = bytes4(keccak256(abi.encodePacked(functionDesc)));
string[] memory roles = _actionsToRoles[target][encodedSig];
uint256 rolesLength = roles.length;
for (uint256 i = 0; i < rolesLength; ) {
if (
keccak256(abi.encodePacked(role)) ==
keccak256(abi.encodePacked(roles[i]))
) {
isAuthorized = true;
break;
}
unchecked {
i++;
}
}
}
/// @notice Returns whether the account has been granted the role
/// @param role Role that authorization is being checked on
/// @param account Address that the role authorization is being check on
/// @return boolean Indicates whether the address has been granted the role
function hasRole(string memory role, address account)
public
view
returns (bool)
{
if (
keccak256(bytes(role)) ==
keccak256(bytes(OPEN_ROLE))
) {
return true;
} else {
return _roles[role].members[account];
}
}
/// @notice Returns the role that is the admin of the specified role
/// @param role Role that the admin role is being returned for
/// @return string The admin role of the specified role
function getRoleAdmin(string memory role)
public
view
returns (string memory)
{
return _roles[role].adminRole;
}
/// @notice Returns whether a given interface ID is supported
/// @param interfaceId An interface ID bytes4 as defined by ERC-165
/// @return bool Indicates whether the interface is supported
function supportsInterface(bytes4 interfaceId)
public
view
override
returns (bool)
{
return
interfaceId == type(IDAOAccessControl).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @notice Sets a role as the admin of another role
/// @param role The role the admin is being set for
/// @param adminRole The role that is being assigned as an admin
function _setRoleAdmin(string memory role, string memory adminRole)
internal
{
string memory previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/// @notice Grants a role to the specified address
/// @param role The role being granted
/// @param account The address being granted the specified role
function _grantRole(string memory role, address account) internal {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
/// @notice Revokes a role from the specified address
/// @param role The role being revoked
/// @param account The address the role is being revoked from
function _revokeRole(string memory role, address account) internal {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
/// @notice Grants roles to the specified addresses and defines admin roles
/// @param roles The roles being granted
/// @param roleAdmins The roles being granted as admins of the specified of roles
/// @param members Addresses being granted each specified role
function _grantRolesAndAdmins(
string[] memory roles,
string[] memory roleAdmins,
address[][] memory members
) internal {
if (roles.length != roleAdmins.length) revert UnequalArrayLengths();
if (roles.length != members.length) revert UnequalArrayLengths();
uint256 rolesLength = roles.length;
for (uint256 i = 0; i < rolesLength; ) {
_setRoleAdmin(roles[i], roleAdmins[i]);
uint256 membersLength = members[i].length;
for (uint256 j = 0; j < membersLength; ) {
_grantRole(roles[i], members[i][j]);
unchecked {
j++;
}
}
unchecked {
i++;
}
}
}
/// @notice Grants roles to the specified addresses and defines admin roles
/// @param roles The roles being granted
/// @param members Addresses being granted each specified role
function _grantRoles(string[] memory roles, address[][] memory members)
internal
{
if (roles.length != members.length) revert UnequalArrayLengths();
uint256 rolesLength = roles.length;
for (uint256 i = 0; i < rolesLength; ) {
uint256 membersLength = members[i].length;
for (uint256 j = 0; j < membersLength; ) {
_grantRole(roles[i], members[i][j]);
unchecked {
j++;
}
}
unchecked {
i++;
}
}
}
/// @notice Authorizes roles to execute the specified actions
/// @param targets The contract addresses that the action functions are implemented on
/// @param functionDescs The function descriptions used to define the actions
/// @param roles Roles being granted permission for an action
function _addActionsRoles(
address[] memory targets,
string[] memory functionDescs,
string[][] memory roles
) internal {
if (targets.length != functionDescs.length)
revert UnequalArrayLengths();
if (targets.length != roles.length) revert UnequalArrayLengths();
uint256 targetsLength = targets.length;
for (uint256 i = 0; i < targetsLength; ) {
uint256 rolesLength = roles[i].length;
for (uint256 j = 0; j < rolesLength; ) {
_addActionRole(targets[i], functionDescs[i], roles[i][j]);
unchecked {
j++;
}
}
unchecked {
i++;
}
}
}
/// @notice Authorizes a role to execute the specified action
/// @param target The contract address that the action function is implemented on
/// @param functionDesc The function description used to define the action
/// @param role Role being granted permission for an action
function _addActionRole(
address target,
string memory functionDesc,
string memory role
) internal {
bytes4 encodedSig = bytes4(keccak256(abi.encodePacked(functionDesc)));
_actionsToRoles[target][encodedSig].push(role);
emit ActionRoleAdded(target, functionDesc, encodedSig, role);
}
/// @notice Removes authorization of a role to execute the specified action
/// @param target The contract address that the action function is implemented on
/// @param functionDesc The function description used to define the action
/// @param role Role that the action authorization is being removed on
function _removeActionRole(
address target,
string memory functionDesc,
string memory role
) internal {
bytes4 encodedSig = bytes4(keccak256(abi.encodePacked(functionDesc)));
uint256 rolesLength = _actionsToRoles[target][encodedSig].length;
for (uint256 i = 0; i < rolesLength; ) {
if (
keccak256(
abi.encodePacked(_actionsToRoles[target][encodedSig][i])
) == keccak256(abi.encodePacked(role))
) {
_actionsToRoles[target][encodedSig][i] = _actionsToRoles[
target
][encodedSig][rolesLength - 1];
_actionsToRoles[target][encodedSig].pop();
emit ActionRoleRemoved(target, functionDesc, encodedSig, role);
break;
}
unchecked {
i++;
}
}
}
/// @notice Reverts when msg.sender is not authorized to upgrade the contract
/// @notice Only addresses that have the DAO_ROLE role are authorized
/// @notice Called by upgradeTo and upgradeToAndCall
/// @param newImplementation New implementation contract address being upgraded to
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(DAO_ROLE)
{}
/// @notice Reverts with a standard message if account is missing role
/// @param role Role being checked
/// @param account Address that role is being checked on
function _checkRole(string memory role, address account) internal view {
if (!hasRole(role, account)) {
revert MissingRole(account, role);
}
}
}
|
Grants roles to the specified addresses and defines admin roles roles The roles being granted roleAdmins The roles being granted as admins of the specified of roles members Addresses being granted each specified role
|
function _grantRolesAndAdmins(
string[] memory roles,
string[] memory roleAdmins,
address[][] memory members
) internal {
if (roles.length != roleAdmins.length) revert UnequalArrayLengths();
if (roles.length != members.length) revert UnequalArrayLengths();
uint256 rolesLength = roles.length;
for (uint256 i = 0; i < rolesLength; ) {
_setRoleAdmin(roles[i], roleAdmins[i]);
uint256 membersLength = members[i].length;
for (uint256 j = 0; j < membersLength; ) {
_grantRole(roles[i], members[i][j]);
unchecked {
j++;
}
}
unchecked {
i++;
}
}
}
| 13,084,548
|
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.7.6;
pragma abicoder v2;
// interface
import {IController} from "../interfaces/IController.sol";
import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {IWETH9} from "../interfaces/IWETH9.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IController} from "../interfaces/IController.sol";
// contract
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {StrategyBase} from "./base/StrategyBase.sol";
import {StrategyFlashSwap} from "./base/StrategyFlashSwap.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
// lib
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// StrategyMath licensed under AGPL-3.0-only
import {StrategyMath} from "./base/StrategyMath.sol";
import {Power2Base} from "../libs/Power2Base.sol";
/**
* @dev CrabStrategy contract
* @notice Contract for Crab strategy
* @author Opyn team
*/
contract CrabStrategy is StrategyBase, StrategyFlashSwap, ReentrancyGuard, Ownable {
using StrategyMath for uint256;
using Address for address payable;
/// @dev the cap in ETH for the strategy, above which deposits will be rejected
uint256 public strategyCap;
/// @dev the TWAP_PERIOD used in the PowerPerp Controller contract
uint32 public constant POWER_PERP_PERIOD = 420 seconds;
/// @dev twap period to use for hedge calculations
uint32 public hedgingTwapPeriod = 420 seconds;
/// @dev enum to differentiate between uniswap swap callback function source
enum FLASH_SOURCE {
FLASH_DEPOSIT,
FLASH_WITHDRAW,
FLASH_HEDGE_SELL,
FLASH_HEDGE_BUY
}
/// @dev ETH:WSqueeth uniswap pool
address public immutable ethWSqueethPool;
/// @dev strategy uniswap oracle
address public immutable oracle;
address public immutable ethQuoteCurrencyPool;
address public immutable quoteCurrency;
/// @dev strategy will only allow hedging if collateral to trade is at least a set percentage of the total strategy collateral
uint256 public deltaHedgeThreshold = 1e15;
/// @dev time difference to trigger a hedge (seconds)
uint256 public hedgeTimeThreshold;
/// @dev price movement to trigger a hedge (0.1*1e18 = 10%)
uint256 public hedgePriceThreshold;
/// @dev hedge auction duration (seconds)
uint256 public auctionTime;
/// @dev start auction price multiplier for hedge buy auction and reserve price for hedge sell auction (scaled 1e18)
uint256 public minPriceMultiplier;
/// @dev start auction price multiplier for hedge sell auction and reserve price for hedge buy auction (scaled 1e18)
uint256 public maxPriceMultiplier;
/// @dev timestamp when last hedge executed
uint256 public timeAtLastHedge;
/// @dev WSqueeth/Eth price when last hedge executed
uint256 public priceAtLastHedge;
/// @dev set to true when redeemShortShutdown has been called
bool private hasRedeemedInShutdown;
struct FlashDepositData {
uint256 totalDeposit;
}
struct FlashWithdrawData {
uint256 crabAmount;
}
struct FlashHedgeData {
uint256 wSqueethAmount;
uint256 ethProceeds;
uint256 minWSqueeth;
uint256 minEth;
}
event Deposit(address indexed depositor, uint256 wSqueethAmount, uint256 lpAmount);
event Withdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount, uint256 ethWithdrawn);
event WithdrawShutdown(address indexed withdrawer, uint256 crabAmount, uint256 ethWithdrawn);
event FlashDeposit(address indexed depositor, uint256 depositedAmount, uint256 tradedAmountOut);
event FlashWithdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount);
event FlashDepositCallback(address indexed depositor, uint256 flashswapDebt, uint256 excess);
event FlashWithdrawCallback(address indexed withdrawer, uint256 flashswapDebt, uint256 excess);
event TimeHedgeOnUniswap(
address indexed hedger,
uint256 hedgeTimestamp,
uint256 auctionTriggerTimestamp,
uint256 minWSqueeth,
uint256 minEth
);
event PriceHedgeOnUniswap(
address indexed hedger,
uint256 hedgeTimestamp,
uint256 auctionTriggerTimestamp,
uint256 minWSqueeth,
uint256 minEth
);
event TimeHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp);
event PriceHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp);
event Hedge(
address indexed hedger,
bool auctionType,
uint256 hedgerPrice,
uint256 auctionPrice,
uint256 wSqueethHedgeTargetAmount,
uint256 ethHedgetargetAmount
);
event HedgeOnUniswap(
address indexed hedger,
bool auctionType,
uint256 auctionPrice,
uint256 wSqueethHedgeTargetAmount,
uint256 ethHedgetargetAmount
);
event ExecuteSellAuction(address indexed buyer, uint256 wSqueethSold, uint256 ethBought, bool isHedgingOnUniswap);
event ExecuteBuyAuction(address indexed seller, uint256 wSqueethBought, uint256 ethSold, bool isHedgingOnUniswap);
event SetStrategyCap(uint256 newCapAmount);
event SetDeltaHedgeThreshold(uint256 newDeltaHedgeThreshold);
event SetHedgingTwapPeriod(uint32 newHedgingTwapPeriod);
event SetHedgeTimeThreshold(uint256 newHedgeTimeThreshold);
event SetHedgePriceThreshold(uint256 newHedgePriceThreshold);
event SetAuctionTime(uint256 newAuctionTime);
event SetMinPriceMultiplier(uint256 newMinPriceMultiplier);
event SetMaxPriceMultiplier(uint256 newMaxPriceMultiplier);
/**
* @notice strategy constructor
* @dev this will open a vault in the power token contract and store the vault ID
* @param _wSqueethController power token controller address
* @param _oracle oracle address
* @param _weth weth address
* @param _uniswapFactory uniswap factory address
* @param _ethWSqueethPool eth:wSqueeth uniswap pool address
* @param _hedgeTimeThreshold hedge time threshold (seconds)
* @param _hedgePriceThreshold hedge price threshold (0.1*1e18 = 10%)
* @param _auctionTime auction duration (seconds)
* @param _minPriceMultiplier minimum auction price multiplier (0.9*1e18 = min auction price is 90% of twap)
* @param _maxPriceMultiplier maximum auction price multiplier (1.1*1e18 = max auction price is 110% of twap)
*/
constructor(
address _wSqueethController,
address _oracle,
address _weth,
address _uniswapFactory,
address _ethWSqueethPool,
uint256 _hedgeTimeThreshold,
uint256 _hedgePriceThreshold,
uint256 _auctionTime,
uint256 _minPriceMultiplier,
uint256 _maxPriceMultiplier
) StrategyBase(_wSqueethController, _weth, "Crab Strategy", "Crab") StrategyFlashSwap(_uniswapFactory) {
require(_oracle != address(0), "invalid oracle address");
require(_ethWSqueethPool != address(0), "invalid ETH:WSqueeth address");
require(_hedgeTimeThreshold > 0, "invalid hedge time threshold");
require(_hedgePriceThreshold > 0, "invalid hedge price threshold");
require(_auctionTime > 0, "invalid auction time");
require(_minPriceMultiplier < 1e18, "min price multiplier too high");
require(_minPriceMultiplier > 0, "invalid min price multiplier");
require(_maxPriceMultiplier > 1e18, "max price multiplier too low");
oracle = _oracle;
ethWSqueethPool = _ethWSqueethPool;
hedgeTimeThreshold = _hedgeTimeThreshold;
hedgePriceThreshold = _hedgePriceThreshold;
auctionTime = _auctionTime;
minPriceMultiplier = _minPriceMultiplier;
maxPriceMultiplier = _maxPriceMultiplier;
ethQuoteCurrencyPool = IController(_wSqueethController).ethQuoteCurrencyPool();
quoteCurrency = IController(_wSqueethController).quoteCurrency();
}
/**
* @notice receive function to allow ETH transfer to this contract
*/
receive() external payable {
require(msg.sender == weth || msg.sender == address(powerTokenController), "Cannot receive eth");
}
/**
* @notice owner can set the strategy cap in ETH collateral terms
* @dev deposits are rejected if it would put the strategy above the cap amount
* @dev strategy collateral can be above the cap amount due to hedging activities
* @param _capAmount the maximum strategy collateral in ETH, checked on deposits
*/
function setStrategyCap(uint256 _capAmount) external onlyOwner {
strategyCap = _capAmount;
emit SetStrategyCap(_capAmount);
}
/**
* @notice called to redeem the net value of a vault post shutdown
* @dev needs to be called 1 time before users can exit the strategy using withdrawShutdown
*/
function redeemShortShutdown() external {
hasRedeemedInShutdown = true;
powerTokenController.redeemShort(vaultId);
}
/**
* @notice flash deposit into strategy, providing ETH, selling wSqueeth and receiving strategy tokens
* @dev this function will execute a flash swap where it receives ETH, deposits and mints using flash swap proceeds and msg.value, and then repays the flash swap with wSqueeth
* @dev _ethToDeposit must be less than msg.value plus the proceeds from the flash swap
* @dev the difference between _ethToDeposit and msg.value provides the minimum that a user can receive for their sold wSqueeth
* @param _ethToDeposit total ETH that will be deposited in to the strategy which is a combination of msg.value and flash swap proceeds
*/
function flashDeposit(uint256 _ethToDeposit) external payable nonReentrant {
(uint256 cachedStrategyDebt, uint256 cachedStrategyCollateral) = _syncStrategyState();
_checkStrategyCap(_ethToDeposit, cachedStrategyCollateral);
(uint256 wSqueethToMint, ) = _calcWsqueethToMintAndFee(
_ethToDeposit,
cachedStrategyDebt,
cachedStrategyCollateral
);
if (cachedStrategyDebt == 0 && cachedStrategyCollateral == 0) {
// store hedge data as strategy is delta neutral at this point
// only execute this upon first deposit
uint256 wSqueethEthPrice = IOracle(oracle).getTwap(
ethWSqueethPool,
wPowerPerp,
weth,
hedgingTwapPeriod,
true
);
timeAtLastHedge = block.timestamp;
priceAtLastHedge = wSqueethEthPrice;
}
_exactInFlashSwap(
wPowerPerp,
weth,
IUniswapV3Pool(ethWSqueethPool).fee(),
wSqueethToMint,
_ethToDeposit.sub(msg.value),
uint8(FLASH_SOURCE.FLASH_DEPOSIT),
abi.encodePacked(_ethToDeposit)
);
emit FlashDeposit(msg.sender, _ethToDeposit, wSqueethToMint);
}
/**
* @notice flash withdraw from strategy, providing strategy tokens, buying wSqueeth, burning and receiving ETH
* @dev this function will execute a flash swap where it receives wSqueeth, burns, withdraws ETH and then repays the flash swap with ETH
* @param _crabAmount strategy token amount to burn
* @param _maxEthToPay maximum ETH to pay to buy back the owed wSqueeth debt
*/
function flashWithdraw(uint256 _crabAmount, uint256 _maxEthToPay) external nonReentrant {
uint256 exactWSqueethNeeded = _getDebtFromStrategyAmount(_crabAmount);
_exactOutFlashSwap(
weth,
wPowerPerp,
IUniswapV3Pool(ethWSqueethPool).fee(),
exactWSqueethNeeded,
_maxEthToPay,
uint8(FLASH_SOURCE.FLASH_WITHDRAW),
abi.encodePacked(_crabAmount)
);
emit FlashWithdraw(msg.sender, _crabAmount, exactWSqueethNeeded);
}
/**
* @notice deposit ETH into strategy
* @dev provide ETH, return wSqueeth and strategy token
*/
function deposit() external payable nonReentrant {
uint256 amount = msg.value;
(uint256 wSqueethToMint, uint256 depositorCrabAmount) = _deposit(msg.sender, amount, false);
emit Deposit(msg.sender, wSqueethToMint, depositorCrabAmount);
}
/**
* @notice withdraw WETH from strategy
* @dev provide strategy tokens and wSqueeth, returns eth
* @param _crabAmount amount of strategy token to burn
*/
function withdraw(uint256 _crabAmount) external nonReentrant {
uint256 wSqueethAmount = _getDebtFromStrategyAmount(_crabAmount);
uint256 ethToWithdraw = _withdraw(msg.sender, _crabAmount, wSqueethAmount, false);
// send back ETH collateral
payable(msg.sender).sendValue(ethToWithdraw);
emit Withdraw(msg.sender, _crabAmount, wSqueethAmount, ethToWithdraw);
}
/**
* @notice called to exit a vault if the Squeeth Power Perp contracts are shutdown
* @param _crabAmount amount of strategy token to burn
*/
function withdrawShutdown(uint256 _crabAmount) external nonReentrant {
require(powerTokenController.isShutDown(), "Squeeth contracts not shut down");
require(hasRedeemedInShutdown, "Crab must redeemShortShutdown");
uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply());
uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, address(this).balance);
_burn(msg.sender, _crabAmount);
payable(msg.sender).sendValue(ethToWithdraw);
emit WithdrawShutdown(msg.sender, _crabAmount, ethToWithdraw);
}
/**
* @notice hedge startegy based on time threshold with uniswap arbing
* @dev this function atomically hedges on uniswap and provides a bounty to the caller based on the difference
* @dev between uniswap execution price and the price of the hedging auction
* @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth
* @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth
*/
function timeHedgeOnUniswap(uint256 _minWSqueeth, uint256 _minEth) external {
(bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge();
require(isTimeHedgeAllowed, "Time hedging is not allowed");
_hedgeOnUniswap(auctionTriggerTime, _minWSqueeth, _minEth);
emit TimeHedgeOnUniswap(msg.sender, block.timestamp, auctionTriggerTime, _minWSqueeth, _minEth);
}
/**
* @notice hedge startegy based on price threshold with uniswap arbing
* @dev this function atomically hedges on uniswap and provides a bounty to the caller based on the difference
* @dev between uniswap execution price and the price of the hedging auction
* @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started
* @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth
* @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth
*/
function priceHedgeOnUniswap(
uint256 _auctionTriggerTime,
uint256 _minWSqueeth,
uint256 _minEth
) external payable {
require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed");
_hedgeOnUniswap(_auctionTriggerTime, _minWSqueeth, _minEth);
emit PriceHedgeOnUniswap(msg.sender, block.timestamp, _auctionTriggerTime, _minWSqueeth, _minEth);
}
/**
* @notice strategy hedging based on time threshold
* @dev need to attach msg.value if buying WSqueeth
* @param _isStrategySellingWSqueeth sell or buy auction, true for sell auction
* @param _limitPrice hedger limit auction price, should be the max price when auction is sell auction, min price when it is a buy auction
*/
function timeHedge(bool _isStrategySellingWSqueeth, uint256 _limitPrice) external payable nonReentrant {
(bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge();
require(isTimeHedgeAllowed, "Time hedging is not allowed");
_hedge(auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice);
emit TimeHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionTriggerTime);
}
/**
* @notice strategy hedging based on price threshold
* @dev need to attach msg.value if buying WSqueeth
* @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started
* @param _isStrategySellingWSqueeth specify the direction of the trade that you expect, this choice impacts the limit price chosen
* @param _limitPrice the min or max price that you will trade at, depending on if buying or selling
*/
function priceHedge(
uint256 _auctionTriggerTime,
bool _isStrategySellingWSqueeth,
uint256 _limitPrice
) external payable nonReentrant {
require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed");
_hedge(_auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice);
emit PriceHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, _auctionTriggerTime);
}
/**
* @notice check if hedging based on price threshold is allowed
* @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started
* @return true if hedging is allowed
*/
function checkPriceHedge(uint256 _auctionTriggerTime) external view returns (bool) {
return _isPriceHedge(_auctionTriggerTime);
}
/**
* @notice check if hedging based on time threshold is allowed
* @return isTimeHedgeAllowed true if hedging is allowed
* @return auctionTriggertime auction trigger timestamp
*/
function checkTimeHedge() external view returns (bool, uint256) {
return _isTimeHedge();
}
/**
* @notice get wSqueeth debt amount associated with strategy token amount
* @param _crabAmount strategy token amount
* @return wSqueeth amount
*/
function getWsqueethFromCrabAmount(uint256 _crabAmount) external view returns (uint256) {
return _getDebtFromStrategyAmount(_crabAmount);
}
/**
* @notice owner can set the delta hedge threshold as a percent scaled by 1e18 of ETH collateral
* @dev the strategy will not allow a hedge if the trade size is below this threshold
* @param _deltaHedgeThreshold minimum hedge size in a percent of ETH collateral
*/
function setDeltaHedgeThreshold(uint256 _deltaHedgeThreshold) external onlyOwner {
deltaHedgeThreshold = _deltaHedgeThreshold;
emit SetDeltaHedgeThreshold(_deltaHedgeThreshold);
}
/**
* @notice owner can set the twap period in seconds that is used for calculating twaps for hedging
* @param _hedgingTwapPeriod the twap period, in seconds
*/
function setHedgingTwapPeriod(uint32 _hedgingTwapPeriod) external onlyOwner {
require(_hedgingTwapPeriod >= 180, "twap period is too short");
hedgingTwapPeriod = _hedgingTwapPeriod;
emit SetHedgingTwapPeriod(_hedgingTwapPeriod);
}
/**
* @notice owner can set the hedge time threshold in seconds that determines how often the strategy can be hedged
* @param _hedgeTimeThreshold the hedge time threshold, in seconds
*/
function setHedgeTimeThreshold(uint256 _hedgeTimeThreshold) external onlyOwner {
require(_hedgeTimeThreshold > 0, "invalid hedge time threshold");
hedgeTimeThreshold = _hedgeTimeThreshold;
emit SetHedgeTimeThreshold(_hedgeTimeThreshold);
}
/**
* @notice owner can set the hedge time threshold in percent, scaled by 1e18 that determines the deviation in wPowerPerp price that can trigger a rebalance
* @param _hedgePriceThreshold the hedge price threshold, in percent, scaled by 1e18
*/
function setHedgePriceThreshold(uint256 _hedgePriceThreshold) external onlyOwner {
require(_hedgePriceThreshold > 0, "invalid hedge price threshold");
hedgePriceThreshold = _hedgePriceThreshold;
emit SetHedgePriceThreshold(_hedgePriceThreshold);
}
/**
* @notice owner can set the auction time, in seconds, that a hedge auction runs for
* @param _auctionTime the length of the hedge auction in seconds
*/
function setAuctionTime(uint256 _auctionTime) external onlyOwner {
require(_auctionTime > 0, "invalid auction time");
auctionTime = _auctionTime;
emit SetAuctionTime(_auctionTime);
}
/**
* @notice owner can set the min price multiplier in a percentage scaled by 1e18 (9e17 is 90%)
* @dev the min price multiplier is multiplied by the TWAP price to get the intial auction price
* @param _minPriceMultiplier the min price multiplier, a percentage, scaled by 1e18
*/
function setMinPriceMultiplier(uint256 _minPriceMultiplier) external onlyOwner {
require(_minPriceMultiplier < 1e18, "min price multiplier too high");
minPriceMultiplier = _minPriceMultiplier;
emit SetMinPriceMultiplier(_minPriceMultiplier);
}
/**
* @notice owner can set the max price multiplier in a percentage scaled by 1e18 (11e18 is 110%)
* @dev the max price multiplier is multiplied by the TWAP price to get the final auction price
* @param _maxPriceMultiplier the max price multiplier, a percentage, scaled by 1e18
*/
function setMaxPriceMultiplier(uint256 _maxPriceMultiplier) external onlyOwner {
require(_maxPriceMultiplier > 1e18, "max price multiplier too low");
maxPriceMultiplier = _maxPriceMultiplier;
emit SetMaxPriceMultiplier(_maxPriceMultiplier);
}
/**
* @notice get current auction details
* @param _auctionTriggerTime timestamp where auction started
* @return if strategy is selling wSqueeth, wSqueeth amount to auction, ETH proceeds, auction price, if auction direction has switched
*/
function getAuctionDetails(uint256 _auctionTriggerTime)
external
view
returns (
bool,
uint256,
uint256,
uint256,
bool
)
{
(uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState();
uint256 currentWSqueethPrice = IOracle(oracle).getTwap(
ethWSqueethPool,
wPowerPerp,
weth,
hedgingTwapPeriod,
true
);
uint256 feeAdjustment = _calcFeeAdjustment();
(bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment);
uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction);
(bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType(
strategyDebt,
ethDelta,
auctionWSqueethEthPrice,
feeAdjustment
);
bool isAuctionDirectionChanged = isSellingAuction != isStillSellingAuction;
uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice);
return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice, isAuctionDirectionChanged);
}
/**
* @notice check if a user deposit puts the strategy above the cap
* @dev reverts if a deposit amount puts strategy over the cap
* @dev it is possible for the strategy to be over the cap from trading/hedging activities, but withdrawals are still allowed
* @param _depositAmount the user deposit amount in ETH
* @param _strategyCollateral the updated strategy collateral
*/
function _checkStrategyCap(uint256 _depositAmount, uint256 _strategyCollateral) internal view {
require(_strategyCollateral.add(_depositAmount) <= strategyCap, "Deposit exceeds strategy cap");
}
/**
* @notice uniswap flash swap callback function
* @dev this function will be called by flashswap callback function uniswapV3SwapCallback()
* @param _caller address of original function caller
* @param _amountToPay amount to pay back for flashswap
* @param _callData arbitrary data attached to callback
* @param _callSource identifier for which function triggered callback
*/
function _strategyFlash(
address _caller,
address, /*_tokenIn*/
address, /*_tokenOut*/
uint24, /*_fee*/
uint256 _amountToPay,
bytes memory _callData,
uint8 _callSource
) internal override {
if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_DEPOSIT) {
FlashDepositData memory data = abi.decode(_callData, (FlashDepositData));
// convert WETH to ETH as Uniswap uses WETH
IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this)));
//use user msg.value and unwrapped WETH from uniswap flash swap proceeds to deposit into strategy
//will revert if data.totalDeposit is > eth balance in contract
_deposit(_caller, data.totalDeposit, true);
//repay the flash swap
IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay);
emit FlashDepositCallback(_caller, _amountToPay, address(this).balance);
//return excess eth to the user that was not needed for slippage
if (address(this).balance > 0) {
payable(_caller).sendValue(address(this).balance);
}
} else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_WITHDRAW) {
FlashWithdrawData memory data = abi.decode(_callData, (FlashWithdrawData));
//use flash swap wSqueeth proceeds to withdraw ETH along with user crabAmount
uint256 ethToWithdraw = _withdraw(
_caller,
data.crabAmount,
IWPowerPerp(wPowerPerp).balanceOf(address(this)),
true
);
//use some amount of withdrawn ETH to repay flash swap
IWETH9(weth).deposit{value: _amountToPay}();
IWETH9(weth).transfer(ethWSqueethPool, _amountToPay);
//excess ETH not used to repay flash swap is transferred to the user
uint256 proceeds = ethToWithdraw.sub(_amountToPay);
emit FlashWithdrawCallback(_caller, _amountToPay, proceeds);
if (proceeds > 0) {
payable(_caller).sendValue(proceeds);
}
} else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_SELL) {
//strategy is selling wSqueeth for ETH
FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData));
// convert WETH to ETH as Uniswap uses WETH
IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this)));
//mint wSqueeth to pay hedger and repay flash swap, deposit ETH
_executeSellAuction(_caller, data.ethProceeds, data.wSqueethAmount, data.ethProceeds, true);
//determine excess wSqueeth that the auction would have sold but is not needed to repay flash swap
uint256 wSqueethProfit = data.wSqueethAmount.sub(_amountToPay);
//minimum profit check for hedger
require(wSqueethProfit >= data.minWSqueeth, "profit is less than min wSqueeth");
//repay flash swap and transfer profit to hedger
IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay);
IWPowerPerp(wPowerPerp).transfer(_caller, wSqueethProfit);
} else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_BUY) {
//strategy is buying wSqueeth for ETH
FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData));
//withdraw ETH to pay hedger and repay flash swap, burn wSqueeth
_executeBuyAuction(_caller, data.wSqueethAmount, data.ethProceeds, true);
//determine excess ETH that the auction would have paid but is not needed to repay flash swap
uint256 ethProfit = data.ethProceeds.sub(_amountToPay);
//minimum profit check for hedger
require(ethProfit >= data.minEth, "profit is less than min ETH");
//repay flash swap and transfer profit to hedger
IWETH9(weth).deposit{value: _amountToPay}();
IWETH9(weth).transfer(ethWSqueethPool, _amountToPay);
payable(_caller).sendValue(ethProfit);
}
}
/**
* @notice deposit into strategy
* @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user
* @param _depositor depositor address
* @param _amount amount of ETH collateral to deposit
* @param _isFlashDeposit true if called by flashDeposit
* @return wSqueethToMint minted amount of WSqueeth
* @return depositorCrabAmount minted CRAB strategy token amount
*/
function _deposit(
address _depositor,
uint256 _amount,
bool _isFlashDeposit
) internal returns (uint256, uint256) {
(uint256 strategyDebt, uint256 strategyCollateral) = _syncStrategyState();
_checkStrategyCap(_amount, strategyCollateral);
(uint256 wSqueethToMint, uint256 ethFee) = _calcWsqueethToMintAndFee(_amount, strategyDebt, strategyCollateral);
uint256 depositorCrabAmount = _calcSharesToMint(_amount.sub(ethFee), strategyCollateral, totalSupply());
if (strategyDebt == 0 && strategyCollateral == 0) {
// store hedge data as strategy is delta neutral at this point
// only execute this upon first deposit
uint256 wSqueethEthPrice = IOracle(oracle).getTwap(
ethWSqueethPool,
wPowerPerp,
weth,
hedgingTwapPeriod,
true
);
timeAtLastHedge = block.timestamp;
priceAtLastHedge = wSqueethEthPrice;
}
// mint wSqueeth and send it to msg.sender
_mintWPowerPerp(_depositor, wSqueethToMint, _amount, _isFlashDeposit);
// mint LP to depositor
_mintStrategyToken(_depositor, depositorCrabAmount);
return (wSqueethToMint, depositorCrabAmount);
}
/**
* @notice withdraw WETH from strategy
* @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user
* @param _crabAmount amount of strategy token to burn
* @param _wSqueethAmount amount of wSqueeth to burn
* @param _isFlashWithdraw flag if called by flashWithdraw
* @return ETH amount to withdraw
*/
function _withdraw(
address _from,
uint256 _crabAmount,
uint256 _wSqueethAmount,
bool _isFlashWithdraw
) internal returns (uint256) {
(, uint256 strategyCollateral) = _syncStrategyState();
uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply());
uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, strategyCollateral);
_burnWPowerPerp(_from, _wSqueethAmount, ethToWithdraw, _isFlashWithdraw);
_burn(_from, _crabAmount);
return ethToWithdraw;
}
/**
* @notice hedging function to adjust collateral and debt to be eth delta neutral
* @param _auctionTriggerTime timestamp where auction started
* @param _isStrategySellingWSqueeth auction type, true for sell auction
* @param _limitPrice hedger accepted auction price, should be the max price when auction is sell auction, min price when it is a buy auction
*/
function _hedge(
uint256 _auctionTriggerTime,
bool _isStrategySellingWSqueeth,
uint256 _limitPrice
) internal {
(
bool isSellingAuction,
uint256 wSqueethToAuction,
uint256 ethProceeds,
uint256 auctionWSqueethEthPrice
) = _startAuction(_auctionTriggerTime);
require(_isStrategySellingWSqueeth == isSellingAuction, "wrong auction type");
if (isSellingAuction) {
// Receiving ETH and paying wSqueeth
require(auctionWSqueethEthPrice <= _limitPrice, "Auction price > max price");
require(msg.value >= ethProceeds, "Low ETH amount received");
_executeSellAuction(msg.sender, msg.value, wSqueethToAuction, ethProceeds, false);
} else {
require(msg.value == 0, "ETH attached for buy auction");
// Receiving wSqueeth and paying ETH
require(auctionWSqueethEthPrice >= _limitPrice, "Auction price < min price");
_executeBuyAuction(msg.sender, wSqueethToAuction, ethProceeds, false);
}
emit Hedge(
msg.sender,
_isStrategySellingWSqueeth,
_limitPrice,
auctionWSqueethEthPrice,
wSqueethToAuction,
ethProceeds
);
}
/**
* @notice execute arb between auction price and uniswap price
* @param _auctionTriggerTime auction starting time
* @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth
* @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth
*/
function _hedgeOnUniswap(
uint256 _auctionTriggerTime,
uint256 _minWSqueeth,
uint256 _minEth
) internal {
(
bool isSellingAuction,
uint256 wSqueethToAuction,
uint256 ethProceeds,
uint256 auctionWSqueethEthPrice
) = _startAuction(_auctionTriggerTime);
if (isSellingAuction) {
_exactOutFlashSwap(
wPowerPerp,
weth,
IUniswapV3Pool(ethWSqueethPool).fee(),
ethProceeds,
wSqueethToAuction,
uint8(FLASH_SOURCE.FLASH_HEDGE_SELL),
abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth)
);
} else {
_exactOutFlashSwap(
weth,
wPowerPerp,
IUniswapV3Pool(ethWSqueethPool).fee(),
wSqueethToAuction,
ethProceeds,
uint8(FLASH_SOURCE.FLASH_HEDGE_BUY),
abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth)
);
}
emit HedgeOnUniswap(msg.sender, isSellingAuction, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds);
}
/**
* @notice execute sell auction based on the parameters calculated
* @dev if _isHedgingOnUniswap, wSqueeth minted is kept to repay flashswap, otherwise sent to seller
* @param _buyer buyer address
* @param _buyerAmount buyer ETH amount sent
* @param _wSqueethToSell wSqueeth amount to sell
* @param _ethToBuy ETH amount to buy
* @param _isHedgingOnUniswap true if arbing with uniswap price
*/
function _executeSellAuction(
address _buyer,
uint256 _buyerAmount,
uint256 _wSqueethToSell,
uint256 _ethToBuy,
bool _isHedgingOnUniswap
) internal {
if (_isHedgingOnUniswap) {
_mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, true);
} else {
_mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, false);
uint256 remainingEth = _buyerAmount.sub(_ethToBuy);
if (remainingEth > 0) {
payable(_buyer).sendValue(remainingEth);
}
}
emit ExecuteSellAuction(_buyer, _wSqueethToSell, _ethToBuy, _isHedgingOnUniswap);
}
/**
* @notice execute buy auction based on the parameters calculated
* @dev if _isHedgingOnUniswap, ETH proceeds are not sent to seller
* @param _seller seller address
* @param _wSqueethToBuy wSqueeth amount to buy
* @param _ethToSell ETH amount to sell
* @param _isHedgingOnUniswap true if arbing with uniswap price
*/
function _executeBuyAuction(
address _seller,
uint256 _wSqueethToBuy,
uint256 _ethToSell,
bool _isHedgingOnUniswap
) internal {
_burnWPowerPerp(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap);
if (!_isHedgingOnUniswap) {
payable(_seller).sendValue(_ethToSell);
}
emit ExecuteBuyAuction(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap);
}
/**
* @notice determine auction direction, price, and ensure auction hasn't switched directions
* @param _auctionTriggerTime auction starting time
* @return auction type
* @return WSqueeth amount to sell or buy
* @return ETH to sell/buy
* @return auction WSqueeth/ETH price
*/
function _startAuction(uint256 _auctionTriggerTime)
internal
returns (
bool,
uint256,
uint256,
uint256
)
{
(uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState();
uint256 currentWSqueethPrice = IOracle(oracle).getTwap(
ethWSqueethPool,
wPowerPerp,
weth,
hedgingTwapPeriod,
true
);
uint256 feeAdjustment = _calcFeeAdjustment();
(bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment);
uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction);
(bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType(
strategyDebt,
ethDelta,
auctionWSqueethEthPrice,
feeAdjustment
);
require(isSellingAuction == isStillSellingAuction, "auction direction changed");
uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice);
timeAtLastHedge = block.timestamp;
priceAtLastHedge = currentWSqueethPrice;
return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice);
}
/**
* @notice sync strategy debt and collateral amount from vault
* @return synced debt amount
* @return synced collateral amount
*/
function _syncStrategyState() internal view returns (uint256, uint256) {
(, , uint256 syncedStrategyCollateral, uint256 syncedStrategyDebt) = _getVaultDetails();
return (syncedStrategyDebt, syncedStrategyCollateral);
}
/**
* @notice calculate the fee adjustment factor, which is the amount of ETH owed per 1 wSqueeth minted
* @dev the fee is a based off the index value of squeeth and uses a twap scaled down by the PowerPerp's INDEX_SCALE
* @return the fee adjustment factor
*/
function _calcFeeAdjustment() internal view returns (uint256) {
uint256 wSqueethEthPrice = Power2Base._getTwap(
oracle,
ethWSqueethPool,
wPowerPerp,
weth,
POWER_PERP_PERIOD,
false
);
uint256 feeRate = IController(powerTokenController).feeRate();
return wSqueethEthPrice.mul(feeRate).div(10000);
}
/**
* @notice calculate amount of wSqueeth to mint and fee paid from deposited amount
* @param _depositedAmount amount of deposited WETH
* @param _strategyDebtAmount amount of strategy debt
* @param _strategyCollateralAmount collateral amount in strategy
* @return amount of minted wSqueeth and ETH fee paid on minted squeeth
*/
function _calcWsqueethToMintAndFee(
uint256 _depositedAmount,
uint256 _strategyDebtAmount,
uint256 _strategyCollateralAmount
) internal view returns (uint256, uint256) {
uint256 wSqueethToMint;
uint256 feeAdjustment = _calcFeeAdjustment();
if (_strategyDebtAmount == 0 && _strategyCollateralAmount == 0) {
require(totalSupply() == 0, "Crab contracts shut down");
uint256 wSqueethEthPrice = IOracle(oracle).getTwap(
ethWSqueethPool,
wPowerPerp,
weth,
hedgingTwapPeriod,
true
);
uint256 squeethDelta = wSqueethEthPrice.wmul(2e18);
wSqueethToMint = _depositedAmount.wdiv(squeethDelta.add(feeAdjustment));
} else {
wSqueethToMint = _depositedAmount.wmul(_strategyDebtAmount).wdiv(
_strategyCollateralAmount.add(_strategyDebtAmount.wmul(feeAdjustment))
);
}
uint256 fee = wSqueethToMint.wmul(feeAdjustment);
return (wSqueethToMint, fee);
}
/**
* @notice check if hedging based on time threshold is allowed
* @return true if time hedging is allowed
* @return auction trigger timestamp
*/
function _isTimeHedge() internal view returns (bool, uint256) {
uint256 auctionTriggerTime = timeAtLastHedge.add(hedgeTimeThreshold);
return (block.timestamp >= auctionTriggerTime, auctionTriggerTime);
}
/**
* @notice check if hedging based on price threshold is allowed
* @param _auctionTriggerTime timestamp where auction started
* @return true if hedging is allowed
*/
function _isPriceHedge(uint256 _auctionTriggerTime) internal view returns (bool) {
if (_auctionTriggerTime < timeAtLastHedge) return false;
uint32 secondsToPriceHedgeTrigger = uint32(block.timestamp.sub(_auctionTriggerTime));
uint256 wSqueethEthPriceAtTriggerTime = IOracle(oracle).getHistoricalTwap(
ethWSqueethPool,
wPowerPerp,
weth,
secondsToPriceHedgeTrigger + hedgingTwapPeriod,
secondsToPriceHedgeTrigger
);
uint256 cachedRatio = wSqueethEthPriceAtTriggerTime.wdiv(priceAtLastHedge);
uint256 priceThreshold = cachedRatio > 1e18 ? (cachedRatio).sub(1e18) : uint256(1e18).sub(cachedRatio);
return priceThreshold >= hedgePriceThreshold;
}
/**
* @notice calculate auction price based on auction direction, start time and wSqueeth price
* @param _auctionTriggerTime timestamp where auction started
* @param _wSqueethEthPrice WSqueeth/ETH price
* @param _isSellingAuction auction type (true for selling, false for buying auction)
* @return auction price
*/
function _getAuctionPrice(
uint256 _auctionTriggerTime,
uint256 _wSqueethEthPrice,
bool _isSellingAuction
) internal view returns (uint256) {
uint256 auctionCompletionRatio = block.timestamp.sub(_auctionTriggerTime) >= auctionTime
? 1e18
: (block.timestamp.sub(_auctionTriggerTime)).wdiv(auctionTime);
uint256 priceMultiplier;
if (_isSellingAuction) {
priceMultiplier = maxPriceMultiplier.sub(
auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier))
);
} else {
priceMultiplier = minPriceMultiplier.add(
auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier))
);
}
return _wSqueethEthPrice.wmul(priceMultiplier);
}
/**
* @notice check the direction of auction and the target amount of wSqueeth to hedge
* @param _debt strategy debt
* @param _ethDelta ETH delta (amount of ETH in strategy)
* @param _wSqueethEthPrice WSqueeth/ETH price
* @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted
* @return auction type(sell or buy) and auction initial target hedge in wSqueeth
*/
function _checkAuctionType(
uint256 _debt,
uint256 _ethDelta,
uint256 _wSqueethEthPrice,
uint256 _feeAdjustment
) internal view returns (bool, uint256) {
uint256 wSqueethDelta = _debt.wmul(2e18).wmul(_wSqueethEthPrice);
(uint256 targetHedge, bool isSellingAuction) = _getTargetHedgeAndAuctionType(
wSqueethDelta,
_ethDelta,
_wSqueethEthPrice,
_feeAdjustment
);
require(targetHedge.wmul(_wSqueethEthPrice).wdiv(_ethDelta) > deltaHedgeThreshold, "strategy is delta neutral");
return (isSellingAuction, targetHedge);
}
/**
* @dev calculate amount of strategy token to mint for depositor
* @param _amount amount of ETH deposited
* @param _strategyCollateralAmount amount of strategy collateral
* @param _crabTotalSupply total supply of strategy token
* @return amount of strategy token to mint
*/
function _calcSharesToMint(
uint256 _amount,
uint256 _strategyCollateralAmount,
uint256 _crabTotalSupply
) internal pure returns (uint256) {
uint256 depositorShare = _amount.wdiv(_strategyCollateralAmount.add(_amount));
if (_crabTotalSupply != 0) return _crabTotalSupply.wmul(depositorShare).wdiv(uint256(1e18).sub(depositorShare));
return _amount;
}
/**
* @notice calculates the ownership proportion for strategy debt and collateral relative to a total amount of strategy tokens
* @param _crabAmount strategy token amount
* @param _totalSupply strategy total supply
* @return ownership proportion of a strategy token amount relative to the total strategy tokens
*/
function _calcCrabRatio(uint256 _crabAmount, uint256 _totalSupply) internal pure returns (uint256) {
return _crabAmount.wdiv(_totalSupply);
}
/**
* @notice calculate ETH to withdraw from strategy given a ownership proportion
* @param _crabRatio crab ratio
* @param _strategyCollateralAmount amount of collateral in strategy
* @return amount of ETH allowed to withdraw
*/
function _calcEthToWithdraw(uint256 _crabRatio, uint256 _strategyCollateralAmount) internal pure returns (uint256) {
return _strategyCollateralAmount.wmul(_crabRatio);
}
/**
* @notice determine target hedge and auction type (selling/buying auction)
* @dev target hedge is the amount of WSqueeth the auction needs to sell or buy to be eth delta neutral
* @param _wSqueethDelta WSqueeth delta
* @param _ethDelta ETH delta
* @param _wSqueethEthPrice WSqueeth/ETH price
* @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted
* @return target hedge in wSqueeth
* @return auction type: true if auction is selling WSqueeth, false if buying WSqueeth
*/
function _getTargetHedgeAndAuctionType(
uint256 _wSqueethDelta,
uint256 _ethDelta,
uint256 _wSqueethEthPrice,
uint256 _feeAdjustment
) internal pure returns (uint256, bool) {
return
(_wSqueethDelta > _ethDelta)
? ((_wSqueethDelta.sub(_ethDelta)).wdiv(_wSqueethEthPrice), false)
: ((_ethDelta.sub(_wSqueethDelta)).wdiv(_wSqueethEthPrice.add(_feeAdjustment)), true);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import {VaultLib} from "../libs/VaultLib.sol";
interface IController {
function ethQuoteCurrencyPool() external view returns (address);
function feeRate() external view returns (uint256);
function getFee(
uint256 _vaultId,
uint256 _wPowerPerpAmount,
uint256 _collateralAmount
) external view returns (uint256);
function quoteCurrency() external view returns (address);
function vaults(uint256 _vaultId) external view returns (VaultLib.Vault memory);
function shortPowerPerp() external view returns (address);
function wPowerPerp() external view returns (address);
function getExpectedNormalizationFactor() external view returns (uint256);
function mintPowerPerpAmount(
uint256 _vaultId,
uint256 _powerPerpAmount,
uint256 _uniTokenId
) external payable returns (uint256 vaultId, uint256 wPowerPerpAmount);
function mintWPowerPerpAmount(
uint256 _vaultId,
uint256 _wPowerPerpAmount,
uint256 _uniTokenId
) external payable returns (uint256 vaultId);
/**
* Deposit collateral into a vault
*/
function deposit(uint256 _vaultId) external payable;
/**
* Withdraw collateral from a vault.
*/
function withdraw(uint256 _vaultId, uint256 _amount) external payable;
function burnWPowerPerpAmount(
uint256 _vaultId,
uint256 _wPowerPerpAmount,
uint256 _withdrawAmount
) external;
function burnOnPowerPerpAmount(
uint256 _vaultId,
uint256 _powerPerpAmount,
uint256 _withdrawAmount
) external returns (uint256 wPowerPerpAmount);
function liquidate(uint256 _vaultId, uint256 _maxDebtAmount) external returns (uint256);
function updateOperator(uint256 _vaultId, address _operator) external;
/**
* External function to update the normalized factor as a way to pay funding.
*/
function applyFunding() external;
function redeemShort(uint256 _vaultId) external;
function reduceDebtShutdown(uint256 _vaultId) external;
function isShutDown() external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWPowerPerp is IERC20 {
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
interface IOracle {
function getHistoricalTwap(
address _pool,
address _base,
address _quote,
uint32 _period,
uint32 _periodToHistoricPrice
) external view returns (uint256);
function getTwap(
address _pool,
address _base,
address _quote,
uint32 _period,
bool _checkPeriod
) external view returns (uint256);
function getMaxPeriod(address _pool) external view returns (uint32);
function getTimeWeightedAverageTickSafe(address _pool, uint32 _period)
external
view
returns (int24 timeWeightedAverageTick);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH9 is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.7.6;
pragma abicoder v2;
// interface
import {IController} from "../../interfaces/IController.sol";
import {IWPowerPerp} from "../../interfaces/IWPowerPerp.sol";
// contract
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// lib
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// StrategyMath licensed under AGPL-3.0-only
import {StrategyMath} from "./StrategyMath.sol";
import {VaultLib} from "../../libs/VaultLib.sol";
/**
* @dev StrategyBase contract
* @notice base contract for PowerToken strategy
* @author opyn team
*/
contract StrategyBase is ERC20 {
using StrategyMath for uint256;
using Address for address payable;
/// @dev power token controller
IController public powerTokenController;
/// @dev WETH token
address public immutable weth;
address public immutable wPowerPerp;
/// @dev power token strategy vault ID
uint256 public immutable vaultId;
/**
* @notice constructor for StrategyBase
* @dev this will open a vault in the power token contract and store the vault ID
* @param _powerTokenController power token controller address
* @param _weth weth token address
* @param _name token name for strategy ERC20 token
* @param _symbol token symbol for strategy ERC20 token
*/
constructor(address _powerTokenController, address _weth, string memory _name, string memory _symbol) ERC20(_name, _symbol) {
require(_powerTokenController != address(0), "invalid controller address");
require(_weth != address(0), "invalid weth address");
weth = _weth;
powerTokenController = IController(_powerTokenController);
wPowerPerp = address(powerTokenController.wPowerPerp());
vaultId = powerTokenController.mintWPowerPerpAmount(0, 0, 0);
}
/**
* @notice get power token strategy vault ID
* @return vault ID
*/
function getStrategyVaultId() external view returns (uint256) {
return vaultId;
}
/**
* @notice get the vault composition of the strategy
* @return operator
* @return nft collateral id
* @return collateral amount
* @return short amount
*/
function getVaultDetails() external view returns (address, uint256, uint256, uint256) {
return _getVaultDetails();
}
/**
* @notice mint WPowerPerp and deposit collateral
* @dev this function will not send WPowerPerp to msg.sender if _keepWSqueeth == true
* @param _to receiver address
* @param _wAmount amount of WPowerPerp to mint
* @param _collateral amount of collateral to deposit
* @param _keepWsqueeth keep minted wSqueeth in this contract if it is set to true
*/
function _mintWPowerPerp(
address _to,
uint256 _wAmount,
uint256 _collateral,
bool _keepWsqueeth
) internal {
powerTokenController.mintWPowerPerpAmount{value: _collateral}(vaultId, _wAmount, 0);
if (!_keepWsqueeth) {
IWPowerPerp(wPowerPerp).transfer(_to, _wAmount);
}
}
/**
* @notice burn WPowerPerp and withdraw collateral
* @dev this function will not take WPowerPerp from msg.sender if _isOwnedWSqueeth == true
* @param _from WPowerPerp holder address
* @param _amount amount of wPowerPerp to burn
* @param _collateralToWithdraw amount of collateral to withdraw
* @param _isOwnedWSqueeth transfer WPowerPerp from holder if it is set to false
*/
function _burnWPowerPerp(
address _from,
uint256 _amount,
uint256 _collateralToWithdraw,
bool _isOwnedWSqueeth
) internal {
if (!_isOwnedWSqueeth) {
IWPowerPerp(wPowerPerp).transferFrom(_from, address(this), _amount);
}
powerTokenController.burnWPowerPerpAmount(vaultId, _amount, _collateralToWithdraw);
}
/**
* @notice mint strategy token
* @param _to recepient address
* @param _amount token amount
*/
function _mintStrategyToken(address _to, uint256 _amount) internal {
_mint(_to, _amount);
}
/**
* @notice get strategy debt amount for a specific strategy token amount
* @param _strategyAmount strategy amount
* @return debt amount
*/
function _getDebtFromStrategyAmount(uint256 _strategyAmount) internal view returns (uint256) {
(, , ,uint256 strategyDebt) = _getVaultDetails();
return strategyDebt.wmul(_strategyAmount).wdiv(totalSupply());
}
/**
* @notice get the vault composition of the strategy
* @return operator
* @return nft collateral id
* @return collateral amount
* @return short amount
*/
function _getVaultDetails() internal view returns (address, uint256, uint256, uint256) {
VaultLib.Vault memory strategyVault = powerTokenController.vaults(vaultId);
return (strategyVault.operator, strategyVault.NftCollateralId, strategyVault.collateralAmount, strategyVault.shortAmount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
// interface
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
// lib
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';
import '@uniswap/v3-periphery/contracts/libraries/Path.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/libraries/SafeCast.sol';
contract StrategyFlashSwap is IUniswapV3SwapCallback {
using Path for bytes;
using SafeCast for uint256;
using LowGasSafeMath for uint256;
using LowGasSafeMath for int256;
/// @dev Uniswap factory address
address public immutable factory;
struct SwapCallbackData {
bytes path;
address caller;
uint8 callSource;
bytes callData;
}
/**
* @dev constructor
* @param _factory uniswap factory address
*/
constructor(
address _factory
) {
require(_factory != address(0), "invalid factory address");
factory = _factory;
}
/**
* @notice uniswap swap callback function for flashes
* @param amount0Delta amount of token0
* @param amount1Delta amount of token1
* @param _data callback data encoded as SwapCallbackData struct
*/
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
//ensure that callback comes from uniswap pool
CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);
//determine the amount that needs to be repaid as part of the flashswap
uint256 amountToPay =
amount0Delta > 0
? uint256(amount0Delta)
: uint256(amount1Delta);
//calls the strategy function that uses the proceeds from flash swap and executes logic to have an amount of token to repay the flash swap
_strategyFlash(data.caller, tokenIn, tokenOut, fee, amountToPay, data.callData, data.callSource);
}
/**
* @notice execute an exact-in flash swap (specify an exact amount to pay)
* @param _tokenIn token address to sell
* @param _tokenOut token address to receive
* @param _fee pool fee
* @param _amountIn amount to sell
* @param _amountOutMinimum minimum amount to receive
* @param _callSource function call source
* @param _data arbitrary data assigned with the call
*/
function _exactInFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountIn, uint256 _amountOutMinimum, uint8 _callSource, bytes memory _data) internal {
//calls internal uniswap swap function that will trigger a callback for the flash swap
uint256 amountOut = _exactInputInternal(
_amountIn,
address(this),
uint160(0),
SwapCallbackData({path: abi.encodePacked(_tokenIn, _fee, _tokenOut), caller: msg.sender, callSource: _callSource, callData: _data})
);
//slippage limit check
require(amountOut >= _amountOutMinimum, "amount out less than min");
}
/**
* @notice execute an exact-out flash swap (specify an exact amount to receive)
* @param _tokenIn token address to sell
* @param _tokenOut token address to receive
* @param _fee pool fee
* @param _amountOut exact amount to receive
* @param _amountInMaximum maximum amount to sell
* @param _callSource function call source
* @param _data arbitrary data assigned with the call
*/
function _exactOutFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountOut, uint256 _amountInMaximum, uint8 _callSource, bytes memory _data) internal {
//calls internal uniswap swap function that will trigger a callback for the flash swap
uint256 amountIn = _exactOutputInternal(
_amountOut,
address(this),
uint160(0),
SwapCallbackData({path: abi.encodePacked(_tokenOut, _fee, _tokenIn), caller: msg.sender, callSource: _callSource, callData: _data})
);
//slippage limit check
require(amountIn <= _amountInMaximum, "amount in greater than max");
}
/**
* @notice function to be called by uniswap callback.
* @dev this function should be overridden by the child contract
* param _caller initial strategy function caller
* param _tokenIn token address sold
* param _tokenOut token address bought
* param _fee pool fee
* param _amountToPay amount to pay for the pool second token
* param _callData arbitrary data assigned with the flashswap call
* param _callSource function call source
*/
function _strategyFlash(address /*_caller*/, address /*_tokenIn*/, address /*_tokenOut*/, uint24 /*_fee*/, uint256 /*_amountToPay*/, bytes memory _callData, uint8 _callSource) internal virtual {}
/**
* @notice internal function for exact-in swap on uniswap (specify exact amount to pay)
* @param _amountIn amount of token to pay
* @param _recipient recipient for receive
* @param _sqrtPriceLimitX96 price limit
* @return amount of token bought (amountOut)
*/
function _exactInputInternal(
uint256 _amountIn,
address _recipient,
uint160 _sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256) {
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
//uniswap token0 has a lower address than token1
//if tokenIn<tokenOut, we are selling an exact amount of token0 in exchange for token1
//zeroForOne determines which token is being sold and which is being bought
bool zeroForOne = tokenIn < tokenOut;
//swap on uniswap, including data to trigger call back for flashswap
(int256 amount0, int256 amount1) =
_getPool(tokenIn, tokenOut, fee).swap(
_recipient,
zeroForOne,
_amountIn.toInt256(),
_sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: _sqrtPriceLimitX96,
abi.encode(data)
);
//determine the amountOut based on which token has a lower address
return uint256(-(zeroForOne ? amount1 : amount0));
}
/**
* @notice internal function for exact-out swap on uniswap (specify exact amount to receive)
* @param _amountOut amount of token to receive
* @param _recipient recipient for receive
* @param _sqrtPriceLimitX96 price limit
* @return amount of token sold (amountIn)
*/
function _exactOutputInternal(
uint256 _amountOut,
address _recipient,
uint160 _sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256) {
(address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool();
//uniswap token0 has a lower address than token1
//if tokenIn<tokenOut, we are buying an exact amount of token1 in exchange for token0
//zeroForOne determines which token is being sold and which is being bought
bool zeroForOne = tokenIn < tokenOut;
//swap on uniswap, including data to trigger call back for flashswap
(int256 amount0Delta, int256 amount1Delta) =
_getPool(tokenIn, tokenOut, fee).swap(
_recipient,
zeroForOne,
-_amountOut.toInt256(),
_sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: _sqrtPriceLimitX96,
abi.encode(data)
);
//determine the amountIn and amountOut based on which token has a lower address
(uint256 amountIn, uint256 amountOutReceived) = zeroForOne
? (uint256(amount0Delta), uint256(-amount1Delta))
: (uint256(amount1Delta), uint256(-amount0Delta));
// it's technically possible to not receive the full output amount,
// so if no price limit has been specified, require this possibility away
if (_sqrtPriceLimitX96 == 0) require(amountOutReceived == _amountOut);
return amountIn;
}
/**
* @notice returns the uniswap pool for the given token pair and fee
* @dev the pool contract may or may not exist
* @param tokenA address of first token
* @param tokenB address of second token
* @param fee fee tier for pool
*/
function _getPool(
address tokenA,
address tokenB,
uint24 fee
) private view returns (IUniswapV3Pool) {
return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @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: AGPL-3.0-only
/// 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;
/**
* @notice Copied from https://github.com/dapphub/ds-math/blob/e70a364787804c1ded9801ed6c27b440a86ebd32/src/math.sol
* @dev change contract to library, added div() function
*/
library StrategyMath {
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 div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
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);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
//interface
import {IOracle} from "../interfaces/IOracle.sol";
//lib
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
library Power2Base {
using SafeMath for uint256;
uint32 private constant TWAP_PERIOD = 420 seconds;
uint256 private constant INDEX_SCALE = 1e4;
uint256 private constant ONE = 1e18;
uint256 private constant ONE_ONE = 1e36;
/**
* @notice return the scaled down index of the power perp in USD, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @return for squeeth, return ethPrice^2
*/
function _getIndex(
uint32 _period,
address _oracle,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getScaledTwap(
_oracle,
_ethQuoteCurrencyPool,
_weth,
_quoteCurrency,
_period,
false
);
return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE);
}
/**
* @notice return the unscaled index of the power perp in USD, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @return for squeeth, return ethPrice^2
*/
function _getUnscaledIndex(
uint32 _period,
address _oracle,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getTwap(_oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false);
return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE);
}
/**
* @notice return the mark price of power perp in quoteCurrency, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @param _wSqueeth wSqueeth address
* @param _normalizationFactor current normalization factor
* @return for squeeth, return ethPrice * squeethPriceInEth
*/
function _getDenormalizedMark(
uint32 _period,
address _oracle,
address _wSqueethEthPool,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency,
address _wSqueeth,
uint256 _normalizationFactor
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getScaledTwap(
_oracle,
_ethQuoteCurrencyPool,
_weth,
_quoteCurrency,
_period,
false
);
uint256 wsqueethEthPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, _period, false);
return wsqueethEthPrice.mul(ethQuoteCurrencyPrice).div(_normalizationFactor);
}
/**
* @notice get the fair collateral value for a _debtAmount of wSqueeth
* @dev the actual amount liquidator can get should have a 10% bonus on top of this value.
* @param _debtAmount wSqueeth amount paid by liquidator
* @param _oracle oracle address
* @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth
* @param _wSqueeth wSqueeth address
* @param _weth weth address
* @return returns value of debt in ETH
*/
function _getDebtValueInEth(
uint256 _debtAmount,
address _oracle,
address _wSqueethEthPool,
address _wSqueeth,
address _weth
) internal view returns (uint256) {
uint256 wSqueethPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, TWAP_PERIOD, false);
return _debtAmount.mul(wSqueethPrice).div(ONE);
}
/**
* @notice request twap from our oracle, scaled down by INDEX_SCALE
* @param _oracle oracle address
* @param _pool uniswap v3 pool address
* @param _base base currency. to get eth/usd price, eth is base token
* @param _quote quote currency. to get eth/usd price, usd is the quote currency
* @param _period number of seconds in the past to start calculating time-weighted average.
* @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts
* @return twap price scaled down by INDEX_SCALE
*/
function _getScaledTwap(
address _oracle,
address _pool,
address _base,
address _quote,
uint32 _period,
bool _checkPeriod
) internal view returns (uint256) {
uint256 twap = _getTwap(_oracle, _pool, _base, _quote, _period, _checkPeriod);
return twap.div(INDEX_SCALE);
}
/**
* @notice request twap from our oracle
* @dev this will revert if period is > max period for the pool
* @param _oracle oracle address
* @param _pool uniswap v3 pool address
* @param _base base currency. to get eth/quoteCurrency price, eth is base token
* @param _quote quote currency. to get eth/quoteCurrency price, quoteCurrency is the quote currency
* @param _period number of seconds in the past to start calculating time-weighted average
* @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts
* @return human readable price. scaled by 1e18
*/
function _getTwap(
address _oracle,
address _pool,
address _base,
address _quote,
uint32 _period,
bool _checkPeriod
) internal view returns (uint256) {
// period reaching this point should be check, otherwise might revert
return IOracle(_oracle).getTwap(_pool, _base, _quote, _period, _checkPeriod);
}
/**
* @notice get the index value of wsqueeth in wei, used when system settles
* @dev the index of squeeth is ethPrice^2, so each squeeth will need to pay out {ethPrice} eth
* @param _wsqueethAmount amount of wsqueeth used in settlement
* @param _indexPriceForSettlement index price for settlement
* @param _normalizationFactor current normalization factor
* @return amount in wei that should be paid to the token holder
*/
function _getLongSettlementValue(
uint256 _wsqueethAmount,
uint256 _indexPriceForSettlement,
uint256 _normalizationFactor
) internal pure returns (uint256) {
return _wsqueethAmount.mul(_normalizationFactor).mul(_indexPriceForSettlement).div(ONE_ONE);
}
}
//SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
//interface
import {INonfungiblePositionManager} from "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
//lib
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {TickMathExternal} from "./TickMathExternal.sol";
import {SqrtPriceMathPartial} from "./SqrtPriceMathPartial.sol";
import {Uint256Casting} from "./Uint256Casting.sol";
/**
* Error code:
* V1: Vault already had nft
* V2: Vault has no NFT
*/
library VaultLib {
using SafeMath for uint256;
using Uint256Casting for uint256;
uint256 constant ONE_ONE = 1e36;
// the collateralization ratio (CR) is checked with the numerator and denominator separately
// a user is safe if - collateral value >= (COLLAT_RATIO_NUMER/COLLAT_RATIO_DENOM)* debt value
uint256 public constant CR_NUMERATOR = 3;
uint256 public constant CR_DENOMINATOR = 2;
struct Vault {
// the address that can update the vault
address operator;
// uniswap position token id deposited into the vault as collateral
// 2^32 is 4,294,967,296, which means the vault structure will work with up to 4 billion positions
uint32 NftCollateralId;
// amount of eth (wei) used in the vault as collateral
// 2^96 / 1e18 = 79,228,162,514, which means a vault can store up to 79 billion eth
// when we need to do calculations, we always cast this number to uint256 to avoid overflow
uint96 collateralAmount;
// amount of wPowerPerp minted from the vault
uint128 shortAmount;
}
/**
* @notice add eth collateral to a vault
* @param _vault in-memory vault
* @param _amount amount of eth to add
*/
function addEthCollateral(Vault memory _vault, uint256 _amount) internal pure {
_vault.collateralAmount = uint256(_vault.collateralAmount).add(_amount).toUint96();
}
/**
* @notice add uniswap position token collateral to a vault
* @param _vault in-memory vault
* @param _tokenId uniswap position token id
*/
function addUniNftCollateral(Vault memory _vault, uint256 _tokenId) internal pure {
require(_vault.NftCollateralId == 0, "V1");
require(_tokenId != 0, "C23");
_vault.NftCollateralId = _tokenId.toUint32();
}
/**
* @notice remove eth collateral from a vault
* @param _vault in-memory vault
* @param _amount amount of eth to remove
*/
function removeEthCollateral(Vault memory _vault, uint256 _amount) internal pure {
_vault.collateralAmount = uint256(_vault.collateralAmount).sub(_amount).toUint96();
}
/**
* @notice remove uniswap position token collateral from a vault
* @param _vault in-memory vault
*/
function removeUniNftCollateral(Vault memory _vault) internal pure {
require(_vault.NftCollateralId != 0, "V2");
_vault.NftCollateralId = 0;
}
/**
* @notice add debt to vault
* @param _vault in-memory vault
* @param _amount amount of debt to add
*/
function addShort(Vault memory _vault, uint256 _amount) internal pure {
_vault.shortAmount = uint256(_vault.shortAmount).add(_amount).toUint128();
}
/**
* @notice remove debt from vault
* @param _vault in-memory vault
* @param _amount amount of debt to remove
*/
function removeShort(Vault memory _vault, uint256 _amount) internal pure {
_vault.shortAmount = uint256(_vault.shortAmount).sub(_amount).toUint128();
}
/**
* @notice check if a vault is properly collateralized
* @param _vault the vault we want to check
* @param _positionManager address of the uniswap position manager
* @param _normalizationFactor current _normalizationFactor
* @param _ethQuoteCurrencyPrice current eth price scaled by 1e18
* @param _minCollateral minimum collateral that needs to be in a vault
* @param _wsqueethPoolTick current price tick for wsqueeth pool
* @param _isWethToken0 whether weth is token0 in the wsqueeth pool
* @return true if the vault is sufficiently collateralized
* @return true if the vault is considered as a dust vault
*/
function getVaultStatus(
Vault memory _vault,
address _positionManager,
uint256 _normalizationFactor,
uint256 _ethQuoteCurrencyPrice,
uint256 _minCollateral,
int24 _wsqueethPoolTick,
bool _isWethToken0
) internal view returns (bool, bool) {
if (_vault.shortAmount == 0) return (true, false);
uint256 debtValueInETH = uint256(_vault.shortAmount).mul(_normalizationFactor).mul(_ethQuoteCurrencyPrice).div(
ONE_ONE
);
uint256 totalCollateral = _getEffectiveCollateral(
_vault,
_positionManager,
_normalizationFactor,
_ethQuoteCurrencyPrice,
_wsqueethPoolTick,
_isWethToken0
);
bool isDust = totalCollateral < _minCollateral;
bool isAboveWater = totalCollateral.mul(CR_DENOMINATOR) >= debtValueInETH.mul(CR_NUMERATOR);
return (isAboveWater, isDust);
}
/**
* @notice get the total effective collateral of a vault, which is:
* collateral amount + uniswap position token equivelent amount in eth
* @param _vault the vault we want to check
* @param _positionManager address of the uniswap position manager
* @param _normalizationFactor current _normalizationFactor
* @param _ethQuoteCurrencyPrice current eth price scaled by 1e18
* @param _wsqueethPoolTick current price tick for wsqueeth pool
* @param _isWethToken0 whether weth is token0 in the wsqueeth pool
* @return the total worth of collateral in the vault
*/
function _getEffectiveCollateral(
Vault memory _vault,
address _positionManager,
uint256 _normalizationFactor,
uint256 _ethQuoteCurrencyPrice,
int24 _wsqueethPoolTick,
bool _isWethToken0
) internal view returns (uint256) {
if (_vault.NftCollateralId == 0) return _vault.collateralAmount;
// the user has deposited uniswap position token as collateral, see how much eth / wSqueeth the uniswap position token has
(uint256 nftEthAmount, uint256 nftWsqueethAmount) = _getUniPositionBalances(
_positionManager,
_vault.NftCollateralId,
_wsqueethPoolTick,
_isWethToken0
);
// convert squeeth amount from uniswap position token as equivalent amount of collateral
uint256 wSqueethIndexValueInEth = nftWsqueethAmount.mul(_normalizationFactor).mul(_ethQuoteCurrencyPrice).div(
ONE_ONE
);
// add eth value from uniswap position token as collateral
return nftEthAmount.add(wSqueethIndexValueInEth).add(_vault.collateralAmount);
}
/**
* @notice determine how much eth / wPowerPerp the uniswap position contains
* @param _positionManager address of the uniswap position manager
* @param _tokenId uniswap position token id
* @param _wPowerPerpPoolTick current price tick
* @param _isWethToken0 whether weth is token0 in the pool
* @return ethAmount the eth amount this LP token contains
* @return wPowerPerpAmount the wPowerPerp amount this LP token contains
*/
function _getUniPositionBalances(
address _positionManager,
uint256 _tokenId,
int24 _wPowerPerpPoolTick,
bool _isWethToken0
) internal view returns (uint256 ethAmount, uint256 wPowerPerpAmount) {
(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
) = _getUniswapPositionInfo(_positionManager, _tokenId);
(uint256 amount0, uint256 amount1) = _getToken0Token1Balances(
tickLower,
tickUpper,
_wPowerPerpPoolTick,
liquidity
);
return
_isWethToken0
? (amount0 + tokensOwed0, amount1 + tokensOwed1)
: (amount1 + tokensOwed1, amount0 + tokensOwed0);
}
/**
* @notice get uniswap position token info
* @param _positionManager address of the uniswap position position manager
* @param _tokenId uniswap position token id
* @return tickLower lower tick of the position
* @return tickUpper upper tick of the position
* @return liquidity raw liquidity amount of the position
* @return tokensOwed0 amount of token 0 can be collected as fee
* @return tokensOwed1 amount of token 1 can be collected as fee
*/
function _getUniswapPositionInfo(address _positionManager, uint256 _tokenId)
internal
view
returns (
int24,
int24,
uint128,
uint128,
uint128
)
{
INonfungiblePositionManager positionManager = INonfungiblePositionManager(_positionManager);
(
,
,
,
,
,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
uint128 tokensOwed0,
uint128 tokensOwed1
) = positionManager.positions(_tokenId);
return (tickLower, tickUpper, liquidity, tokensOwed0, tokensOwed1);
}
/**
* @notice get balances of token0 / token1 in a uniswap position
* @dev knowing liquidity, tick range, and current tick gives balances
* @param _tickLower address of the uniswap position manager
* @param _tickUpper uniswap position token id
* @param _tick current price tick used for calculation
* @return amount0 the amount of token0 in the uniswap position token
* @return amount1 the amount of token1 in the uniswap position token
*/
function _getToken0Token1Balances(
int24 _tickLower,
int24 _tickUpper,
int24 _tick,
uint128 _liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
// get the current price and tick from wPowerPerp pool
uint160 sqrtPriceX96 = TickMathExternal.getSqrtRatioAtTick(_tick);
if (_tick < _tickLower) {
amount0 = SqrtPriceMathPartial.getAmount0Delta(
TickMathExternal.getSqrtRatioAtTick(_tickLower),
TickMathExternal.getSqrtRatioAtTick(_tickUpper),
_liquidity,
true
);
} else if (_tick < _tickUpper) {
amount0 = SqrtPriceMathPartial.getAmount0Delta(
sqrtPriceX96,
TickMathExternal.getSqrtRatioAtTick(_tickUpper),
_liquidity,
true
);
amount1 = SqrtPriceMathPartial.getAmount1Delta(
TickMathExternal.getSqrtRatioAtTick(_tickLower),
sqrtPriceX96,
_liquidity,
true
);
} else {
amount1 = SqrtPriceMathPartial.getAmount1Delta(
TickMathExternal.getSqrtRatioAtTick(_tickLower),
TickMathExternal.getSqrtRatioAtTick(_tickUpper),
_liquidity,
true
);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMathExternal {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) external pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "@uniswap/v3-core/contracts/libraries/UnsafeMath.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Exposes two functions from @uniswap/v3-core SqrtPriceMath
/// that use square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMathPartial {
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) external pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
return
roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) external pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
roundUp
? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
: FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
}
//SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
library Uint256Casting {
/**
* @notice cast a uint256 to a uint128, revert on overflow
* @param y the uint256 to be downcasted
* @return z the downcasted integer, now type uint128
*/
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y, "OF128");
}
/**
* @notice cast a uint256 to a uint96, revert on overflow
* @param y the uint256 to be downcasted
* @return z the downcasted integer, now type uint96
*/
function toUint96(uint256 y) internal pure returns (uint96 z) {
require((z = uint96(y)) == y, "OF96");
}
/**
* @notice cast a uint256 to a uint32, revert on overflow
* @param y the uint256 to be downcasted
* @return z the downcasted integer, now type uint32
*/
function toUint32(uint256 y) internal pure returns (uint32 z) {
require((z = uint32(y)) == y, "OF32");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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 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.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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_) {
_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: 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Returns the number of pools in the path
/// @param path The encoded swap path
/// @return The number of pools in the path
function numPools(bytes memory path) internal pure returns (uint256) {
// Ignore the first token address. From then on every fee and token offset indicates a pool.
return ((path.length - ADDR_SIZE) / NEXT_OFFSET);
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import './PoolAddress.sol';
/// @notice Provides validation for callbacks from Uniswap V3 Pools
library CallbackValidation {
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The V3 pool contract address
function verifyCallback(
address factory,
address tokenA,
address tokenB,
uint24 fee
) internal view returns (IUniswapV3Pool pool) {
return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));
}
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param poolKey The identifying key of the V3 pool
/// @return pool The V3 pool contract address
function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey)
internal
view
returns (IUniswapV3Pool pool)
{
pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
require(msg.sender == address(pool));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
|
owner can set the twap period in seconds that is used for calculating twaps for hedging _hedgingTwapPeriod the twap period, in seconds/
|
function setHedgingTwapPeriod(uint32 _hedgingTwapPeriod) external onlyOwner {
require(_hedgingTwapPeriod >= 180, "twap period is too short");
hedgingTwapPeriod = _hedgingTwapPeriod;
emit SetHedgingTwapPeriod(_hedgingTwapPeriod);
}
| 1,220,067
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0 <0.9.0;
import "./IRegistry.sol";
import "./IDelegation.sol";
import "./ERC165.sol";
contract Registry is IRegistry {
uint64 private idSequence = 1000;
string private constant ADDRESS_CHANGE_TYPE =
"AddressChange(uint32 nonce,address addr,string handle)";
bytes32 private constant ADDRESS_CHANGE_TYPEHASH =
keccak256(abi.encodePacked(ADDRESS_CHANGE_TYPE));
string private constant HANDLE_CHANGE_TYPE =
"HandleChange(uint32 nonce,string oldHandle,string newHandle)";
bytes32 private constant HANDLE_CHANGE_TYPEHASH =
keccak256(abi.encodePacked(HANDLE_CHANGE_TYPE));
string private constant EIP712_DOMAIN =
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)";
bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN));
bytes32 private constant SALT =
0x01597239a39b73c524db27009bfe992afd78e195ca64846a6fa0ce65ce37b2df;
bytes32 private immutable domainSeparatorHash;
// Id and identity contract address to be mapped to handle
struct Registration {
uint32 nonce;
uint64 id;
address identityAddress;
}
// Map from handle to registration
mapping(string => Registration) private registrations;
// Create domain separator on construction
constructor() {
domainSeparatorHash = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256("Registry"),
keccak256("1"),
block.chainid,
address(this),
SALT
)
);
}
/**
* @dev Register a new DSNP Id
* @param addr Address for the new DSNP Id to point at
* @param handle The handle for discovery
* @return id of registration
*/
function register(address addr, string calldata handle) external override returns (uint64) {
// Checks
Registration storage reg = registrations[handle];
require(reg.id == 0, "Handle already exists");
// Effects
// Set id to latest sequence number then increment
reg.id = idSequence++;
reg.identityAddress = addr;
// emit registration event
emit DSNPRegistryUpdate(reg.id, addr, handle);
// Interactions
ERC165 delegation = ERC165(addr);
require(
delegation.supportsInterface(type(IDelegation).interfaceId),
"contract does not support IDelegation interface"
);
return reg.id;
}
/**
* @dev Alter a DSNP Id resolution address
* @param newAddr Original or new address to resolve to
* @param handle The handle to modify
*/
function changeAddress(address newAddr, string calldata handle) external override {
// Checks
Registration storage reg = registrations[handle];
require(reg.id != 0, "Handle does not exist");
// Effects
address oldAddr = reg.identityAddress;
reg.identityAddress = newAddr;
emit DSNPRegistryUpdate(reg.id, newAddr, handle);
// Interactions
// ensure old delegation contract authorizes this change
IDelegation oldAuth = IDelegation(oldAddr);
require(
oldAuth.isAuthorizedTo(
msg.sender,
IDelegation.Permission.OWNERSHIP_TRANSFER,
block.number
),
"Access denied"
);
// ensure new delegation contract implements IDelegation interface
ERC165 delegation = ERC165(newAddr);
require(
delegation.supportsInterface(type(IDelegation).interfaceId),
"contract does not support IDelegation interface"
);
}
/**
* @dev Alter a DSNP Id resolution address by EIP-712 Signature
* @param v EIP-155 calculated Signature v value
* @param r ECDSA Signature r value
* @param s ECDSA Signature s value
* @param change Change data containing nonce, new address and handle
*/
function changeAddressByEIP712Sig(
uint8 v,
bytes32 r,
bytes32 s,
AddressChange calldata change
) external override {
// Checks
Registration storage reg = registrations[change.handle];
require(reg.id != 0, "Handle does not exist");
require(reg.nonce == change.nonce, "Nonces do not match");
address signer = addressChangeSigner(v, r, s, change);
// Effects
reg.nonce++;
address oldAddr = reg.identityAddress;
reg.identityAddress = change.addr;
emit DSNPRegistryUpdate(reg.id, change.addr, change.handle);
// Interactions
// ensure old delegation contract authorizes this change
IDelegation oldAuth = IDelegation(oldAddr);
require(
oldAuth.isAuthorizedTo(signer, IDelegation.Permission.OWNERSHIP_TRANSFER, block.number),
"Access denied"
);
// ensure new delegation contract implements IDelegation interface
ERC165 delegation = ERC165(change.addr);
require(
delegation.supportsInterface(type(IDelegation).interfaceId),
"contract does not support IDelegation interface"
);
}
/**
* @dev Alter a DSNP Id handle
* @param oldHandle The previous handle for modification
* @param newHandle The new handle to use for discovery
*/
function changeHandle(string calldata oldHandle, string calldata newHandle) external override {
// Checks
Registration storage oldReg = registrations[oldHandle];
require(oldReg.id != 0, "Old handle does not exist");
Registration storage newReg = registrations[newHandle];
require(newReg.id == 0, "New handle already exists");
// Effects
// assign to new registration
newReg.id = oldReg.id;
newReg.identityAddress = oldReg.identityAddress;
// signal that the old handle is unassigned and available
oldReg.id = 0;
// notify the change
emit DSNPRegistryUpdate(newReg.id, newReg.identityAddress, newHandle);
// Interactions
IDelegation authorization = IDelegation(oldReg.identityAddress);
require(
authorization.isAuthorizedTo(
msg.sender,
IDelegation.Permission.OWNERSHIP_TRANSFER,
block.number
),
"Access denied"
);
}
/**
* @dev Alter a DSNP Id handle by EIP-712 Signature
* @param v EIP-155 calculated Signature v value
* @param r ECDSA Signature r value
* @param s ECDSA Signature s value
* @param change Change data containing nonce, old handle and new handle
*/
function changeHandleByEIP712Sig(
uint8 v,
bytes32 r,
bytes32 s,
HandleChange calldata change
) external override {
// Checks
Registration storage oldReg = registrations[change.oldHandle];
require(oldReg.id != 0, "Old handle does not exist");
require(oldReg.nonce == change.nonce, "Nonces do not match");
Registration storage newReg = registrations[change.newHandle];
require(newReg.id == 0, "New handle already exists");
address signer = handleChangeSigner(v, r, s, change);
// Effects
// assign to new registration
newReg.id = oldReg.id;
newReg.identityAddress = oldReg.identityAddress;
// signal that the old handle is unassigned and available
oldReg.id = 0;
// increment nonce so this transaction cannot be replayed
oldReg.nonce++;
// notify the change
emit DSNPRegistryUpdate(newReg.id, newReg.identityAddress, change.newHandle);
// Interactions
IDelegation authorization = IDelegation(oldReg.identityAddress);
require(
authorization.isAuthorizedTo(
signer,
IDelegation.Permission.OWNERSHIP_TRANSFER,
block.number
),
"Access denied"
);
}
/**
* @dev Resolve a handle to a DSNP Id and contract address
* @param handle The handle to resolve
*
* Returns zeros if not found
* @return A tuple of the DSNP Id and the Address of the contract
*/
function resolveRegistration(string calldata handle)
external
view
override
returns (uint64, address)
{
Registration memory reg = registrations[handle];
if (reg.id == 0) return (0, address(0));
return (reg.id, reg.identityAddress);
}
/**
* @dev Resolve a handle to nonce
* @param handle The handle to resolve
*
* @return nonce value for handle
*/
function resolveHandleToNonce(string calldata handle) external view override returns (uint32) {
Registration memory reg = registrations[handle];
require(reg.id != 0, "Handle does not exist");
return reg.nonce;
}
/**
* @dev Recover the message signer from an AddressChange and a signature.
* @param v EIP-155 calculated Signature v value
* @param r ECDSA Signature r value
* @param s ECDSA Signature s value
* @param change Change data containing nonce, handle and new address
* @return signer address (or some arbitrary address if signature is incorrect)
*/
function addressChangeSigner(
uint8 v,
bytes32 r,
bytes32 s,
AddressChange calldata change
) internal view returns (address) {
bytes32 typeHash = keccak256(
abi.encode(
ADDRESS_CHANGE_TYPEHASH,
change.nonce,
change.addr,
keccak256(bytes(change.handle))
)
);
return signerFromHashStruct(v, r, s, typeHash);
}
/**
* @dev Recover the message signer from a HandleChange and a signature.
* @param v EIP-155 calculated Signature v value
* @param r ECDSA Signature r value
* @param s ECDSA Signature s value
* @param change Change data containing nonce, old handle and new handle
* @return signer address (or some arbitrary address if signature is incorrect)
*/
function handleChangeSigner(
uint8 v,
bytes32 r,
bytes32 s,
HandleChange calldata change
) internal view returns (address) {
bytes32 typeHash = keccak256(
abi.encode(
HANDLE_CHANGE_TYPEHASH,
change.nonce,
keccak256(bytes(change.oldHandle)),
keccak256(bytes(change.newHandle))
)
);
return signerFromHashStruct(v, r, s, typeHash);
}
/**
* @dev Recover the message signer from a signature and a type hash for this domain.
* @param v EIP-155 calculated Signature v value
* @param r ECDSA Signature r value
* @param s ECDSA Signature s value
* @param hashStruct Hash of encoded type struct
* @return signer address (or some arbitrary address if signature is incorrect)
*/
function signerFromHashStruct(
uint8 v,
bytes32 r,
bytes32 s,
bytes32 hashStruct
) internal view returns (address) {
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparatorHash, hashStruct));
return ecrecover(digest, v, r, s);
}
}
|
Recover the message signer from a signature and a type hash for this domain. v EIP-155 calculated Signature v value r ECDSA Signature r value s ECDSA Signature s value hashStruct Hash of encoded type struct return signer address (or some arbitrary address if signature is incorrect)/
|
function signerFromHashStruct(
uint8 v,
bytes32 r,
bytes32 s,
bytes32 hashStruct
) internal view returns (address) {
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparatorHash, hashStruct));
return ecrecover(digest, v, r, s);
}
| 15,870,276
|
./partial_match/1/0x035928bCf0974d8935CDbcA36E96ac679C36865E/sources/Ether5.sol
|
function to allow users to withdraw their earningssettle the daily dividendcan only withdraw if they have some earnings.
|
public {
address _playerAddress = msg.sender;
settleIncome(_playerAddress);
uint256 _earnings =
player[_playerAddress].dailyIncome +
player[_playerAddress].directReferralIncome +
player[_playerAddress].roiReferralIncome;
function withdrawIncome()
if(_earnings > 0) {
require(address(this).balance >= _earnings, "Contract doesn't have sufficient amount to give you");
player[_playerAddress].dailyIncome = 0;
player[_playerAddress].directReferralIncome = 0;
player[_playerAddress].roiReferralIncome = 0;
player[_playerAddress].investorPoolIncome = 0;
player[_playerAddress].sponsorPoolIncome = 0;
player[_playerAddress].superIncome = 0;
address(uint160(_playerAddress)).transfer(_earnings);
emit withdrawEvent(_playerAddress, _earnings, now);
}
}
| 4,305,988
|
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/_equilibria/root/token/types/Token18.sol
|
self Token to transfer grantee Address to allow spending amount Amount of tokens to approve to spend/
|
function approve(Token18 self, address grantee, UFixed18 amount) internal {
IERC20(Token18.unwrap(self)).safeApprove(grantee, UFixed18.unwrap(amount));
}
| 1,912,846
|
./partial_match/1/0xCcE0385E33f408357ca9E59470361b5B74c61129/sources/Token.sol
|
require current msg sender to be owner, reverts otherwise
|
function _onlyOwner() internal view {
}
| 16,196,622
|
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableMapUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "contracts/interfaces/apwine/tokens/IFutureYieldToken.sol";
import "contracts/interfaces/apwine/IFuture.sol";
import "contracts/interfaces/apwine/IRegistry.sol";
import "contracts/interfaces/apwine/utils/IAPWineNaming.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
/**
* @title Controller contract
* @notice The controller dictates the future mechanisms and serves as an interface for main user interaction with futures
*/
contract Controller is Initializable, AccessControlUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using SafeMathUpgradeable for uint256;
/* ACR Roles*/
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/* Attributes */
IRegistry public registry;
mapping(uint256 => uint256) private nextPeriodSwitchByDuration;
mapping(uint256 => uint256) private unlockClaimableFactorByDuration; // represented as x/1000
EnumerableSetUpgradeable.UintSet private durations;
mapping(uint256 => EnumerableSetUpgradeable.AddressSet) private futuresByDuration;
mapping(uint256 => uint256) private periodIndexByDurations;
EnumerableSetUpgradeable.AddressSet private pausedFutures;
/* Events */
event PlatformRegistered(address _platformControllerAddress);
event PlatformUnregistered(address _platformControllerAddress);
event NextPeriodSwitchSet(uint256 _periodDuration, uint256 _nextSwitchTimestamp);
event FutureRegistered(address _newFutureAddress);
event FutureUnregistered(address _future);
event NewUnlockClaimableFactor(uint256 _periodDuration, uint256 _newYieldUnlockFactor);
event StartingDelaySet(uint256 _startingDelay);
/* PlatformController Settings */
uint256 public STARTING_DELAY;
/* Modifiers */
modifier futureIsValid(address _future) {
require(registry.isRegisteredFuture(_future), "incorrect future address");
_;
}
/* Initializer */
/**
* @notice Initializer of the Controller contract
* @param _admin the address of the admin
*/
function initialize(address _admin, address _registry) public initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(ADMIN_ROLE, _admin);
registry = IRegistry(_registry);
}
/**
* @notice Change the delay for starting a new period
* @param _startingDelay the new delay (+-) to start the next period
*/
function setPeriodStartingDelay(uint256 _startingDelay) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
STARTING_DELAY = _startingDelay;
emit StartingDelaySet(_startingDelay);
}
/**
* @notice Set the next period switch timestamp for the future with corresponding duration
* @param _periodDuration the period duration
* @param _nextPeriodTimestamp the next period switch timestamp
*/
function setNextPeriodSwitchTimestamp(uint256 _periodDuration, uint256 _nextPeriodTimestamp) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set next period timestamp");
nextPeriodSwitchByDuration[_periodDuration] = _nextPeriodTimestamp;
emit NextPeriodSwitchSet(_periodDuration, _nextPeriodTimestamp);
}
/**
* @notice Set a new factor for the portion of the yield that is claimable when withdrawing funds during an ongoing period
* @param _periodDuration the duration of the periods
* @param _claimableYieldFactor the portion of the yield that is claimable
*/
function setUnlockClaimableFactor(uint256 _periodDuration, uint256 _claimableYieldFactor) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set the unlock yield factor");
unlockClaimableFactorByDuration[_periodDuration] = _claimableYieldFactor;
emit NewUnlockClaimableFactor(_periodDuration, _claimableYieldFactor);
}
/* User Methods */
/**
* @notice Register an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be registered to
* @param _amount the amount to register
*/
function register(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).register(msg.sender, _amount);
require(ERC20(IFuture(_future).getIBTAddress()).transferFrom(msg.sender, _future, _amount), "invalid amount");
}
/**
* @notice Unregister an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be unregistered from
* @param _amount the amount to unregister
*/
function unregister(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).unregister(msg.sender, _amount);
}
/**
* @notice Withdraw deposited funds from APWine
* @param _future the address of the future to withdraw the IBT from
* @param _amount the amount to withdraw
*/
function withdrawLockFunds(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).withdrawLockFunds(msg.sender, _amount);
}
/**
* @notice Claim FYT of the msg.sender
* @param _future the future from which to claim the FYT
*/
function claimFYT(address _future) public futureIsValid(_future) {
IFuture(_future).claimFYT(msg.sender);
}
/**
* @notice Register the sender to the corresponding platformController
* @param _user the address of the user
* @param futuresAddresses the addresses of the futures to claim the FYT from
*/
function claimSelectedYield(address _user, address[] memory futuresAddresses) public {
for (uint256 i = 0; i < futuresAddresses.length; i++) {
require(registry.isRegisteredFuture(futuresAddresses[i]), "Incorrect future address");
IFuture(futuresAddresses[i]).claimFYT(_user);
}
}
/* User Getter */
/**
* @notice Get the list of futures from which a user can claim FYT
* @param _user the user to check
*/
function getFuturesWithClaimableFYT(address _user) external view returns (address[] memory) {
address[] memory selectedFutures = new address[](registry.futureCount());
uint8 index = 0;
for (uint256 i = 0; i < registry.futureCount(); i++) {
if (IFuture(registry.getFutureAt(i)).hasClaimableFYT(_user)) {
selectedFutures[i] = registry.getFutureAt(i);
index += 1;
}
}
return selectedFutures;
}
/* Getter */
/**
* @notice Getter for the registry address of the protocol
* @return the address of the protocol registry
*/
function getRegistryAddress() external view returns (address) {
return address(registry);
}
/**
* @notice Getter for the symbol of the APWine IBT of one future
* @param _ibtSymbol the IBT of the external protocol
* @param _platform the external protocol name
* @param _periodDuration the duration of the periods for the future
* @return the generated symbol of the APWine IBT
*/
function getFutureIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) public view returns (string memory) {
return IAPWineNaming(registry.getNamingUtils()).genIBTSymbol(_ibtSymbol, _platform, _periodDuration);
}
/**
* @notice Getter for the symbol of the FYT of one future
* @param _apwibtSymbol the APWine IBT symbol for this future
* @param _periodDuration the duration of the periods for this future
* @return the generated symbol of the FYT
*/
function getFYTSymbol(string memory _apwibtSymbol, uint256 _periodDuration) public view returns (string memory) {
return
IAPWineNaming(registry.getNamingUtils()).genFYTSymbolFromIBT(
uint8(periodIndexByDurations[_periodDuration]),
_apwibtSymbol
);
}
/**
* @notice Getter for the period index depending on the period duration of the future
* @param _periodDuration the duration of the periods
* @return the period index
*/
function getPeriodIndex(uint256 _periodDuration) public view returns (uint256) {
return periodIndexByDurations[_periodDuration];
}
/**
* @notice Getter for the beginning timestamp of the next period for the futures with a defined period duration
* @param _periodDuration the duration of the periods
* @return the timestamp of the beginning of the next period
*/
function getNextPeriodStart(uint256 _periodDuration) public view returns (uint256) {
return nextPeriodSwitchByDuration[_periodDuration];
}
/**
* @notice Getter for the factor of claimable yield when unlocking
* @param _periodDuration the duration of the periods
* @return the factor of the claimable yield of the last period
*/
function getUnlockYieldFactor(uint256 _periodDuration) public view returns (uint256) {
return unlockClaimableFactorByDuration[_periodDuration];
}
/**
* @notice Getter for the list of future durations registered in the contract
* @return the list of future durations
*/
function getDurations() public view returns (uint256[] memory) {
uint256[] memory durationsList = new uint256[](durations.length());
for (uint256 i = 0; i < durations.length(); i++) {
durationsList[i] = durations.at(i);
}
return durationsList;
}
/**
* @notice Getter for the futures by period duration
* @param _periodDuration the period duration of the futures to return
*/
function getFuturesWithDuration(uint256 _periodDuration) public view returns (address[] memory) {
uint256 listLength = futuresByDuration[_periodDuration].length();
address[] memory filteredFutures = new address[](listLength);
for (uint256 i = 0; i < listLength; i++) {
filteredFutures[i] = futuresByDuration[_periodDuration].at(i);
}
return filteredFutures;
}
/* Future admin methods */
/**
* @notice Register a newly created future in the registry
* @param _newFuture the address of the new future
*/
function registerNewFuture(address _newFuture) public {
require(
hasRole(ADMIN_ROLE, msg.sender) || registry.isRegisteredFutureFactory(msg.sender),
"Caller cannot register a future"
);
registry.addFuture(_newFuture);
uint256 futureDuration = IFuture(_newFuture).PERIOD_DURATION();
if (!durations.contains(futureDuration)) durations.add(futureDuration);
futuresByDuration[futureDuration].add(_newFuture);
emit FutureRegistered(_newFuture);
}
/**
* @notice Unregister a future from the registry
* @param _future the address of the future to unregister
*/
function unregisterFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
registry.removeFuture(_future);
uint256 futureDuration = IFuture(_future).PERIOD_DURATION();
if (!durations.contains(futureDuration)) durations.remove(futureDuration);
futuresByDuration[futureDuration].remove(_future);
emit FutureUnregistered(_future);
}
/**
* @notice Start all futures that have a defined period duration to synchronize them
* @param _periodDuration the period duration of the futures to start
*/
function startFuturesByPeriodDuration(uint256 _periodDuration) public {
for (uint256 i = 0; i < futuresByDuration[_periodDuration].length(); i++) {
if (!pausedFutures.contains(futuresByDuration[_periodDuration].at(i))) {
IFuture(futuresByDuration[_periodDuration].at(i)).startNewPeriod();
}
}
nextPeriodSwitchByDuration[_periodDuration] = nextPeriodSwitchByDuration[_periodDuration].add(_periodDuration);
periodIndexByDurations[_periodDuration] = periodIndexByDurations[_periodDuration].add(1);
}
/* Security functions */
/**
* @notice Interrupt a future avoiding news registrations
* @param _future the address of the future to pause
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function pauseFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
IFuture(_future).pausePeriods();
pausedFutures.add(_future);
}
/**
* @notice Resume a future that has been paused
* @param _future the address of the future to resume
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function resumeFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
IFuture(_future).resumePeriods();
pausedFutures.remove(_future);
}
}
// 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 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(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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 Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.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());
}
}
uint256[49] private __gap;
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IFutureYieldToken is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @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) external;
/**
* @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;
}
pragma solidity 0.7.6;
interface IFuture {
struct Registration {
uint256 startIndex;
uint256 scaledBalance;
}
/**
* @notice Getter for the PAUSE future parameter
* @return true if new periods are paused, false otherwise
*/
function PAUSED() external view returns (bool);
/**
* @notice Getter for the PERIOD future parameter
* @return returns the period duration of the future
*/
function PERIOD_DURATION() external view returns (uint256);
/**
* @notice Getter for the PLATFORM_NAME future parameter
* @return returns the platform of the future
*/
function PLATFORM_NAME() external view returns (uint256);
/**
* @notice Initializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _deployerAddress the future deployer address
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) external;
/**
* @notice Set future wallet address
* @param _futureVault the address of the new future wallet
* @dev needs corresponding permissions for sender
*/
function setFutureVault(address _futureVault) external;
/**
* @notice Set futureWallet address
* @param _futureWallet the address of the new futureWallet
* @dev needs corresponding permissions for sender
*/
function setFutureWallet(address _futureWallet) external;
/**
* @notice Set liquidity gauge address
* @param _liquidityGauge the address of the new liquidity gauge
* @dev needs corresponding permissions for sender
*/
function setLiquidityGauge(address _liquidityGauge) external;
/**
* @notice Set apwibt address
* @param _apwibt the address of the new apwibt
* @dev used only for exceptional purpose
*/
function setAPWIBT(address _apwibt) external;
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) external;
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user addresss
* @param _amount amount of IBT to be unregistered
*/
function unregister(address _user, uint256 _amount) external;
/**
* @notice Sender unlocks the locked funds corresponding to their apwIBT holding
* @param _user the user address
* @param _amount amount of funds to unlocked
* @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked
*/
function withdrawLockFunds(address _user, uint256 _amount) external;
/**
* @notice Send the user their owed FYT (and apwIBT if there are some claimable)
* @param _user address of the user to send the FYT to
*/
function claimFYT(address _user) external;
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() external;
/**
* @notice Check if a user has unclaimed FYT
* @param _user the user to check
* @return true if the user can claim some FYT, false otherwise
*/
function hasClaimableFYT(address _user) external view returns (bool);
/**
* @notice Check if a user has unclaimed apwIBT
* @param _user the user to check
* @return true if the user can claim some apwIBT, false otherwise
*/
function hasClaimableAPWIBT(address _user) external view returns (bool);
/**
* @notice Getter for user registered amount
* @param _user user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) external view returns (uint256);
/**
* @notice Getter for user IBT amount that is unlockable
* @param _user user to unlock the IBT from
* @return the amount of IBT the user can unlock
*/
function getUnlockableFunds(address _user) external view returns (uint256);
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user user to check the unrealized yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user the user to check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of FYT that the user can claim for a certain period
* @param _user user to check the check the claimable FYT of
* @param _periodID period ID to check the claimable FYT of
* @return the amount of FYT claimable by the user for this period ID
*/
function getClaimableFYTForPeriod(address _user, uint256 _periodID) external view returns (uint256);
/**
* @notice Getter for next period index
* @return next period index
* @dev index starts at 1
*/
function getNextPeriodIndex() external view returns (uint256);
/**
* @notice Getter for controller address
* @return the controller address
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for future wallet address
* @return future wallet address
*/
function getFutureVaultAddress() external view returns (address);
/**
* @notice Getter for futureWallet address
* @return futureWallet address
*/
function getFutureWalletAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge address
* @return liquidity gauge address
*/
function getLiquidityGaugeAddress() external view returns (address);
/**
* @notice Getter for the IBT address
* @return IBT address
*/
function getIBTAddress() external view returns (address);
/**
* @notice Getter for future apwIBT address
* @return apwIBT address
*/
function getAPWIBTAddress() external view returns (address);
/**
* @notice Getter for FYT address of a particular period
* @param _periodIndex period index
* @return FYT address
*/
function getFYTofPeriod(uint256 _periodIndex) external view returns (address);
/* Admin functions*/
/**
* @notice Pause registrations and the creation of new periods
*/
function pausePeriods() external;
/**
* @notice Resume registrations and the creation of new periods
*/
function resumePeriods() external;
}
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface IRegistry {
/**
* @notice Initializer of the contract
* @param _admin the address of the admin of the contract
*/
function initialize(address _admin) external;
/* Setters */
/**
* @notice Setter for the treasury address
* @param _newTreasury the address of the new treasury
*/
function setTreasury(address _newTreasury) external;
/**
* @notice Setter for the gauge controller address
* @param _newGaugeController the address of the new gauge controller
*/
function setGaugeController(address _newGaugeController) external;
/**
* @notice Setter for the controller address
* @param _newController the address of the new controller
*/
function setController(address _newController) external;
/**
* @notice Setter for the APW token address
* @param _newAPW the address of the APW token
*/
function setAPW(address _newAPW) external;
/**
* @notice Setter for the proxy factory address
* @param _proxyFactory the address of the new proxy factory
*/
function setProxyFactory(address _proxyFactory) external;
/**
* @notice Setter for the liquidity gauge address
* @param _liquidityGaugeLogic the address of the new liquidity gauge logic
*/
function setLiquidityGaugeLogic(address _liquidityGaugeLogic) external;
/**
* @notice Setter for the APWine IBT logic address
* @param _APWineIBTLogic the address of the new APWine IBT logic
*/
function setAPWineIBTLogic(address _APWineIBTLogic) external;
/**
* @notice Setter for the APWine FYT logic address
* @param _FYTLogic the address of the new APWine FYT logic
*/
function setFYTLogic(address _FYTLogic) external;
/**
* @notice Setter for the maths utils address
* @param _mathsUtils the address of the new math utils
*/
function setMathsUtils(address _mathsUtils) external;
/**
* @notice Setter for the naming utils address
* @param _namingUtils the address of the new naming utils
*/
function setNamingUtils(address _namingUtils) external;
/**
* @notice Getter for the controller address
* @return the address of the controller
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for the treasury address
* @return the address of the treasury
*/
function getTreasuryAddress() external view returns (address);
/**
* @notice Getter for the gauge controller address
* @return the address of the gauge controller
*/
function getGaugeControllerAddress() external view returns (address);
/**
* @notice Getter for the DAO address
* @return the address of the DAO that has admin rights on the APW token
*/
function getDAOAddress() external returns (address);
/**
* @notice Getter for the APW token address
* @return the address the APW token
*/
function getAPWAddress() external view returns (address);
/**
* @notice Getter for the vesting contract address
* @return the vesting contract address
*/
function getVestingAddress() external view returns (address);
/**
* @notice Getter for the proxy factory address
* @return the proxy factory address
*/
function getProxyFactoryAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge logic address
* @return the liquidity gauge logic address
*/
function getLiquidityGaugeLogicAddress() external view returns (address);
/**
* @notice Getter for APWine IBT logic address
* @return the APWine IBT logic address
*/
function getAPWineIBTLogicAddress() external view returns (address);
/**
* @notice Getter for APWine FYT logic address
* @return the APWine FYT logic address
*/
function getFYTLogicAddress() external view returns (address);
/**
* @notice Getter for math utils address
* @return the math utils address
*/
function getMathsUtils() external view returns (address);
/**
* @notice Getter for naming utils address
* @return the naming utils address
*/
function getNamingUtils() external view returns (address);
/* Future factory */
/**
* @notice Register a new future factory in the registry
* @param _futureFactory the address of the future factory contract
* @param _futureFactoryName the name of the future factory
*/
function addFutureFactory(address _futureFactory, string memory _futureFactoryName) external;
/**
* @notice Getter to check if a future factory is registered
* @param _futureFactory the address of the future factory contract to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFutureFactory(address _futureFactory) external view returns (bool);
/**
* @notice Getter for the future factory registered at an index
* @param _index the index of the future factory to return
* @return the address of the corresponding future factory
*/
function getFutureFactoryAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future factories registered
* @return the number of future factory registered
*/
function futureFactoryCount() external view returns (uint256);
/**
* @notice Getter for name of a future factory contract
* @param _futureFactory the address of a future factory
* @return the name of the corresponding future factory contract
*/
function getFutureFactoryName(address _futureFactory) external view returns (string memory);
/* Future platform */
/**
* @notice Register a new future platform in the registry
* @param _futureFactory the address of the future factory
* @param _futurePlatformName the name of the future platform
* @param _future the address of the future contract logic
* @param _futureWallet the address of the future wallet contract logic
* @param _futureVault the name of the future vault contract logic
*/
function addFuturePlatform(
address _futureFactory,
string memory _futurePlatformName,
address _future,
address _futureWallet,
address _futureVault
) external;
/**
* @notice Getter to check if a future platform is registered
* @param _futurePlatformName the name of the future platform to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuturePlatform(string memory _futurePlatformName) external view returns (bool);
/**
* @notice Getter for the future platform contracts
* @param _futurePlatformName the name of the future platform
* @return the addresses of 0) the future logic 1) the future wallet logic 2) the future vault logic
*/
function getFuturePlatform(string memory _futurePlatformName) external view returns (address[3] memory);
/**
* @notice Getter the total count of future platftroms registered
* @return the number of future platforms registered
*/
function futurePlatformsCount() external view returns (uint256);
/**
* @notice Getter the list of platforms names registered
* @return the list of platform names registered
*/
function getFuturePlatformNames() external view returns (string[] memory);
/**
* @notice Remove a future platform from the registry
* @param _futurePlatformName the name of the future platform to remove from the registry
*/
function removeFuturePlatform(string memory _futurePlatformName) external;
/* Futures */
/**
* @notice Add a future to the registry
* @param _future the address of the future to add to the registry
*/
function addFuture(address _future) external;
/**
* @notice Remove a future from the registry
* @param _future the address of the future to remove from the registry
*/
function removeFuture(address _future) external;
/**
* @notice Getter to check if a future is registered
* @param _future the address of the future to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuture(address _future) external view returns (bool);
/**
* @notice Getter for the future registered at an index
* @param _index the index of the future to return
* @return the address of the corresponding future
*/
function getFutureAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future registered
* @return the number of future registered
*/
function futureCount() external view returns (uint256);
}
pragma solidity 0.7.6;
interface IAPWineNaming {
/**
* @notice generate the symbol of the FYT
* @param _index the index of the current period
* @param _ibtSymbol the symbol of the IBT
* @param _platform the platform name
* @param _periodDuration the period duration
* @return the symbol for the FYT
* @dev i.e 30D-AAVE-ADAI-2
*/
function genFYTSymbol(
uint8 _index,
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice generate the FYT symbol from the apwIBT
* @param _index the index of the current period
* @param _ibtSymbol the symbol of the IBT
* @return the symbol for the FYT
* @dev i.e 30D-AAVE-ADAI-2
*/
function genFYTSymbolFromIBT(uint8 _index, string memory _ibtSymbol) external pure returns (string memory);
/**
* @notice generate the apwIBT symbol
* @param _ibtSymbol the symbol of the IBT of the future
* @param _platform the platform name
* @param _periodDuration the period duration
* @return the symbol for the apwIBT
* @dev i.e 30D-AAVE-ADAI
*/
function genIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice generate the period denominator
* @param _periodDuration the period duration
* @return the period denominator
* @dev i.e 30D
*/
function getPeriodDurationDenominator(uint256 _periodDuration) external pure returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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;
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
// 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.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ERC20 is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external 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 returns (uint8);
/**
* @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) external returns (bool);
/**
* @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) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
|
Register a newly created future in the registry _newFuture the address of the new future/
|
function registerNewFuture(address _newFuture) public {
require(
hasRole(ADMIN_ROLE, msg.sender) || registry.isRegisteredFutureFactory(msg.sender),
"Caller cannot register a future"
);
registry.addFuture(_newFuture);
uint256 futureDuration = IFuture(_newFuture).PERIOD_DURATION();
if (!durations.contains(futureDuration)) durations.add(futureDuration);
futuresByDuration[futureDuration].add(_newFuture);
emit FutureRegistered(_newFuture);
}
| 13,427,572
|
./full_match/11155111/0xcBED395d7F6c8D96994F206D77bDD185bDf255F4/sources/src/NFTDriver.sol
|
Mints a new token controlling a new user ID and transfers it to an address. The token ID is deterministically derived from the caller's address and the salt. Each caller can use each salt only once, to mint a single token. Emits user metadata for the new token. Usage of this method is discouraged, use `safeMint` whenever possible. to The address to transfer the minted token to. userMetadata The list of user metadata to emit for the minted token. The keys and the values are not standardized by the protocol, it's up to the user to establish and follow conventions to ensure compatibility with the consumers. return tokenId The minted token ID. It's equal to the user ID controlled by it. The ID is calculated using `calcTokenIdWithSalt` for the caller's address and the used salt.
|
function mintWithSalt(uint64 salt, address to, UserMetadata[] calldata userMetadata)
public
whenNotPaused
returns (uint256 tokenId)
{
tokenId = _registerTokenIdWithSalt(salt);
_mint(to, tokenId);
_emitUserMetadata(tokenId, userMetadata);
}
| 3,825,901
|
/**
*Submitted for verification at Etherscan.io on 2021-03-09
*/
// contracts/IdolNFT.sol
// 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 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;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev 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);
}
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. 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 || ERC721.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 || ERC721.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);
_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 {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
/**
* @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();
}
}
/**
* @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;
}
}
interface IdolTokenInterface {
function mintForCreateNFT(address _to, uint256 _amountInWei) external;
function mintForBuyNFT(address _to, uint256 _priceInWei) external;
function balanceOf(address account) external view returns (uint256);
function burn(uint256 amount) external;
}
interface UniswapV2Interface {
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function WETH() external pure returns (address);
}
contract IdolNFT is ERC721Enumerable, Ownable {
event CreateNFT(address indexed to, uint256 indexed photoId, uint256 tokenId);
event BuyNFT(address buyer, address owner, uint256 indexed tokenId, uint256 priceInWei);
event PutNFTOffSale(uint256 indexed tokenId);
event PutNFTOnSale(uint256 indexed tokenId);
using Address for address payable;
//extra info for each token
struct TokenExtra {
bool _onSale;
address _creator;
uint256 _priceInWei;
uint256 _lastPriceInWei;
}
//address of the ERC20 Token to mint for reward
address private _idolTokenAddress;
//uniswap exchange pool
address private _uniswapv2;
//TokenId Counter
uint256 private _tokenIdTracker;
//mapping stores Extra Data of Token
mapping(uint256 => TokenExtra) private _tokenExtraMap;
//mapping stores for reward creator's address and reward amount
mapping (address => uint256) private _creatorRewards;
//constructor for IDOLNFT
constructor() ERC721("IDOLNFT", "IDOLNFT") Ownable() {}
//create a ERC721 compatible IdolNFT, returns the TokenId, called from external
function createNFTAndReward(uint256 _photoId, bool _onSale, uint256 _priceInWei) external {
_createNFT(_msgSender(), _photoId, _onSale, _priceInWei);
//mint reward IDOL ERC20 token for creator
if (_creatorRewards[_msgSender()] > 0 && _idolTokenAddress != address(0)) {
IdolTokenInterface(_idolTokenAddress).mintForCreateNFT(_msgSender(), _creatorRewards[_msgSender()]);
}
}
function buyNFTAndReward(uint256 _tokenId) external payable {
require(_msgSender() != ownerOf(_tokenId), "IdolNFT: can't buy own NFT");
require(_tokenExtraMap[_tokenId]._onSale, "IdolNFT: this NFT is not onsale now");
require(msg.value >= _tokenExtraMap[_tokenId]._priceInWei, "IdolNFT: pay amount is not enough");
uint256 _payToOwner;
if (ownerOf(_tokenId) != _tokenExtraMap[_tokenId]._creator) {
//owner is not creator
//pay to NFT owner
_payToOwner = _tokenExtraMap[_tokenId]._priceInWei * 95 / 100;
payable(ownerOf(_tokenId)).sendValue(_payToOwner);
//pay to NFT creator only when the creator is not the owner
uint256 _payToCreator = _tokenExtraMap[_tokenId]._priceInWei * 35 / 1000;
payable(_tokenExtraMap[_tokenId]._creator).sendValue(_payToCreator);
} else {
//owner is creator
if (_tokenExtraMap[_tokenId]._lastPriceInWei == 0) {
//NFT is inital sale
_payToOwner = _tokenExtraMap[_tokenId]._priceInWei * 9 / 10;
} else {
//NFT is not inital sale
_payToOwner = _tokenExtraMap[_tokenId]._priceInWei * 95 / 100;
}
//pay to NFT owner
payable(ownerOf(_tokenId)).sendValue(_payToOwner);
}
//set NFT _onSale to false
_tokenExtraMap[_tokenId]._onSale = false;
//set NFT _lastPriceInWei
_tokenExtraMap[_tokenId]._lastPriceInWei = _tokenExtraMap[_tokenId]._priceInWei;
//last owner for transfer and event
address _lastOwner = ownerOf(_tokenId);
//transfer the ERC721 token to the buyer
_safeTransfer(_lastOwner, _msgSender(), _tokenId, "");
emit BuyNFT(_msgSender(), _lastOwner, _tokenId, _tokenExtraMap[_tokenId]._lastPriceInWei);
if (_idolTokenAddress != address(0)) {
//mint reward IDOL token for the buyer if the buyer is not the NFT creator
IdolTokenInterface(_idolTokenAddress).mintForBuyNFT(_msgSender(), _tokenExtraMap[_tokenId]._priceInWei);
//buy IDOL token from Uniswap and burn when contract balance is above 0.01 ETH
if(_uniswapv2 != address(0) && address(this).balance >= 10**16) {
UniswapV2Interface uniswapRouterV2 = UniswapV2Interface(_uniswapv2);
address[] memory path = new address[](2);
path[0] = uniswapRouterV2.WETH();
path[1] = _idolTokenAddress;
uint256 eth_amount = address(this).balance;
uint256 deadline = block.timestamp + 600;
uniswapRouterV2.swapExactETHForTokens{ value: eth_amount }(1, path, address(this), deadline);
}
}
}
function putNFTOnSale(uint256 _tokenId, uint256 _priceInWei) external {
require(_msgSender() == ownerOf(_tokenId), "IdolNFT: only owner can put NFT on sale");
_tokenExtraMap[_tokenId]._onSale = true;
setNFTPrice(_tokenId, _priceInWei);
emit PutNFTOnSale(_tokenId);
}
function putNFTOffSale(uint256 _tokenId) external {
require(_msgSender() == ownerOf(_tokenId), "IdolNFT: only owner can put NFT off sale");
_tokenExtraMap[_tokenId]._onSale = false;
emit PutNFTOffSale(_tokenId);
}
function setNFTPrice(uint256 _tokenId, uint256 _priceInWei) public {
require(_msgSender() == ownerOf(_tokenId), "IdolNFT: only owner can set NFT price");
require(_priceInWei >= 10**15, "IdolNFT: NFT must have a price higher than 0.001 ether");
if (_tokenExtraMap[_tokenId]._lastPriceInWei == 0) {
require(_priceInWei <= 10**21, "IdolNFT: NFT must have a inital price lower than 1000 ether");
} else {
uint256 high = _tokenExtraMap[_tokenId]._lastPriceInWei * 2;
require(_priceInWei <= high, "IdolNFT: NFT must have a price lower than the last sold price times two");
}
_tokenExtraMap[_tokenId]._priceInWei = _priceInWei;
}
//create a ERC721 compatible IdolNFT, returns the TokenId
function _createNFT(address _creator, uint256 _photoId, bool _onSale, uint256 _priceInWei) private {
require(_creator != address(0), "IdolNFT: can't mint to zero address");
require(_priceInWei <= 10**21, "IdolNFT: NFT must have a inital price lower than 1000 ether");
if (_onSale) {
require(_priceInWei >= 10**15, "IdolNFT: NFT must have a inital price higher than 0.001 ether");
}
_safeMint(_creator, _tokenIdTracker);
_tokenExtraMap[_tokenIdTracker] = TokenExtra({
_creator: _creator,
_onSale: _onSale,
_priceInWei: _priceInWei,
_lastPriceInWei : 0
});
emit CreateNFT(_creator, _photoId, _tokenIdTracker);
_tokenIdTracker += 1;
}
function getTokenExtra(uint256 _tokenId) external view returns (bool, address, address, uint256, uint256) {
address _owner = ownerOf(_tokenId);
return (_tokenExtraMap[_tokenId]._onSale, _owner, _tokenExtraMap[_tokenId]._creator, _tokenExtraMap[_tokenId]._priceInWei, _tokenExtraMap[_tokenId]._lastPriceInWei);
}
function setCreatorReward(address _creator, uint256 _amountInWei) external onlyOwner {
_creatorRewards[_creator] = _amountInWei;
}
function getCreatorReward(address _creator) external view returns (uint256) {
return _creatorRewards[_creator];
}
function setIdolTokenAddress(address _address) external onlyOwner {
_idolTokenAddress = _address;
}
function setUniswapAddress(address _address) external onlyOwner {
_uniswapv2 = _address;
}
function burnIdol() external onlyOwner {
if (_idolTokenAddress != address(0)) {
uint256 _balance = IdolTokenInterface(_idolTokenAddress).balanceOf(address(this));
IdolTokenInterface(_idolTokenAddress).burn(_balance);
}
}
receive() payable external {}
}
|
create a ERC721 compatible IdolNFT, returns the TokenId
|
function _createNFT(address _creator, uint256 _photoId, bool _onSale, uint256 _priceInWei) private {
require(_creator != address(0), "IdolNFT: can't mint to zero address");
require(_priceInWei <= 10**21, "IdolNFT: NFT must have a inital price lower than 1000 ether");
if (_onSale) {
require(_priceInWei >= 10**15, "IdolNFT: NFT must have a inital price higher than 0.001 ether");
}
_safeMint(_creator, _tokenIdTracker);
_tokenExtraMap[_tokenIdTracker] = TokenExtra({
_creator: _creator,
_onSale: _onSale,
_priceInWei: _priceInWei,
_lastPriceInWei : 0
});
emit CreateNFT(_creator, _photoId, _tokenIdTracker);
_tokenIdTracker += 1;
}
| 15,175,184
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "hardhat/console.sol";
import "@openzeppelin/contracts/governance/TimelockController.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IShare } from "../interfaces/IShare.sol";
import { IMembership } from "../interfaces/IMembership.sol";
import { IModule } from "../interfaces/IModule.sol";
import { DataTypes } from "../libraries/DataTypes.sol";
import { Errors } from "../libraries/Errors.sol";
import { Events } from "../libraries/Events.sol";
/**
* @title Treasury
* @notice The treasury is one of the core contracts of the DAO and is responsible for managing all of the DAO's assets,
* including external assets, eth and share tokens of the DAO.
* the treasury supports external investors in invoking the investment method to self-serve share tokens,
* and the treasury provides a hook method for modules to pull payments,
* allowing authorization for some of the assets of the modules used by the DAO.
*/
contract Treasury is TimelockController, Multicall {
using Address for address payable;
address public immutable share;
address public immutable membership;
DataTypes.ShareSplit public shareSplit;
DataTypes.InvestmentSettings public investmentSettings;
address[] private _proposers;
address[] private _executors = [address(0)];
mapping(address => uint256) private _investThresholdInERC20;
mapping(address => uint256) private _investRatioInERC20;
mapping(address => DataTypes.ModulePayment) private _modulePayments;
constructor(
uint256 timelockDelay,
address membershipTokenAddress,
address shareTokenAddress,
DataTypes.InvestmentSettings memory settings
) TimelockController(timelockDelay, _proposers, _executors) {
membership = membershipTokenAddress;
share = shareTokenAddress;
investmentSettings = settings;
_mappingSettings(settings);
}
modifier investmentEnabled() {
if (!investmentSettings.enableInvestment)
revert Errors.InvestmentDisabled();
_;
}
/**
* @dev Shortcut method
* Allows distribution of shares to members in corresponding proportions (index is tokenID)
* must be called by the timelock itself (requires a voting process)
*/
function vestingShare(uint256[] calldata tokenId, uint8[] calldata shareRatio)
public
onlyRole(TIMELOCK_ADMIN_ROLE)
{
uint256 _shareTreasury = IShare(share).balanceOf(address(this));
if (_shareTreasury == 0) revert Errors.NoShareInTreasury();
uint256 _membersShare = _shareTreasury * (shareSplit.members / 100);
if (_membersShare == 0) revert Errors.NoMembersShareToVest();
for (uint256 i = 0; i < tokenId.length; i++) {
address _member = IMembership(membership).ownerOf(tokenId[i]);
IShare(share).transfer(_member, (_membersShare * shareRatio[i]) / 100);
}
}
/**
* @dev Shortcut method
* to update settings for investment (requires a voting process)
*/
function updateInvestmentSettings(
DataTypes.InvestmentSettings memory settings
) public onlyRole(TIMELOCK_ADMIN_ROLE) {
investmentSettings = settings;
_mappingSettings(settings);
}
/**
* @dev Shortcut method
* to update share split (requires a voting process)
*/
function updateShareSplit(DataTypes.ShareSplit memory _shareSplit)
public
onlyRole(TIMELOCK_ADMIN_ROLE)
{
shareSplit = _shareSplit;
}
/**
* @dev Invest in ETH
* Allows external investors to transfer to ETH for investment.
* ETH will issue share token of DAO at a set rate
*/
function invest() external payable investmentEnabled {
if (investmentSettings.investRatioInETH == 0)
revert Errors.InvestmentDisabled();
if (msg.value < investmentSettings.investThresholdInETH)
revert Errors.InvestmentThresholdNotMet(
investmentSettings.investThresholdInETH
);
_invest(
msg.value / investmentSettings.investRatioInETH,
address(0),
msg.value
);
}
/**
* @dev Invest in ERC20 tokens
* External investors are allowed to invest in ERC20,
* which is issued as a DAO share token at a set rate.
* @notice Before calling this method, the approve method of the corresponding ERC20 contract must be called.
*/
function investInERC20(address token) external investmentEnabled {
if (_investRatioInERC20[token] == 0)
revert Errors.InvestmentInERC20Disabled(token);
uint256 _radio = _investRatioInERC20[token];
if (_radio == 0) revert Errors.InvestmentInERC20Disabled(token);
uint256 _threshold = _investThresholdInERC20[token];
uint256 _allowance = IShare(token).allowance(_msgSender(), address(this));
if (_allowance < _threshold)
revert Errors.InvestmentInERC20ThresholdNotMet(token, _threshold);
IShare(token).transferFrom(_msgSender(), address(this), _allowance);
_invest(_allowance / _radio, token, _allowance);
}
/**
* @dev Pull module payment
* The DAO module pulls the required eth and ERC20 token
* @notice Need to ensure that the number of authorizations is greater than the required number before pulling.
* this method is usually required by the module designer,
* and the method checks whether the module is mounted on the same DAO
*/
function pullModulePayment(
uint256 eth,
address[] calldata tokens,
uint256[] calldata amounts
) public {
if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts();
address moduleAddress = _msgSender();
if (IModule(moduleAddress).membership() != membership)
revert Errors.NotMember();
DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress];
address _timelock = address(IModule(moduleAddress).timelock());
address payable _target = payable(_timelock);
if (!_payments.approved) revert Errors.ModuleNotApproved();
if (eth > 0) {
if (eth > _payments.eth) revert Errors.NotEnoughETH();
_payments.eth -= eth;
_target.sendValue(eth);
}
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 _token = IERC20(tokens[i]);
if (_token.allowance(address(this), _timelock) < amounts[i])
revert Errors.NotEnoughTokens();
_token.transferFrom(address(this), _timelock, amounts[i]);
_payments.erc20[tokens[i]] -= amounts[i];
}
emit Events.ModulePaymentPulled(
moduleAddress,
eth,
tokens,
amounts,
block.timestamp
);
}
/**
* @dev Approve module payment
* Authorize a module to use the corresponding eth and ERC20 token
*/
function approveModulePayment(
address moduleAddress,
uint256 eth,
address[] calldata tokens,
uint256[] calldata amounts
) public onlyRole(TIMELOCK_ADMIN_ROLE) {
if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts();
if (IModule(moduleAddress).membership() != membership)
revert Errors.NotMember();
DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress];
_payments.approved = true;
_payments.eth = eth;
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 _token = IERC20(tokens[i]);
if (_token.balanceOf(address(this)) < amounts[i])
revert Errors.NotEnoughTokens();
_payments.erc20[tokens[i]] = amounts[i];
_token.approve(address(IModule(moduleAddress).timelock()), amounts[i]);
}
emit Events.ModulePaymentApproved(
moduleAddress,
eth,
tokens,
amounts,
block.timestamp
);
}
/**
* @dev Private method of realizing external investments
* The converted share token is automatically transferred to the external investor,
* and if there are not enough shares in the vault, additional shares are automatically issued.
* At the same time, the act of investing will mint a new investor status NFT membership card,
* ensuring that the investor can participate in the voting of board members (1/1 NFT Votes).
*/
function _invest(
uint256 _shareTobeClaimed,
address _token,
uint256 _amount
) private {
uint256 _shareTreasury = IShare(share).balanceOf(address(this));
if (_shareTreasury < _shareTobeClaimed) {
IShare(share).mint(address(this), _shareTobeClaimed - _shareTreasury);
}
IShare(share).transfer(_msgSender(), _shareTobeClaimed);
IMembership(membership).investMint(_msgSender());
if (_token == address(0)) {
emit Events.InvestInETH(_msgSender(), msg.value, _shareTobeClaimed);
} else {
emit Events.InvestInERC20(
_msgSender(),
_token,
_amount,
_shareTobeClaimed
);
}
}
// @dev mapping arrays to maps cause of the lack of support of params mapping in Solidity
function _mappingSettings(DataTypes.InvestmentSettings memory settings)
private
{
if (settings.investInERC20.length > 0) {
for (uint256 i = 0; i < settings.investInERC20.length; i++) {
address _token = settings.investInERC20[i];
_investThresholdInERC20[_token] = settings.investThresholdInERC20[i];
_investRatioInERC20[_token] = settings.investRatioInERC20[i];
}
}
}
}
|
Pull module payment The DAO module pulls the required eth and ERC20 token Need to ensure that the number of authorizations is greater than the required number before pulling. this method is usually required by the module designer, and the method checks whether the module is mounted on the same DAO/
|
function pullModulePayment(
uint256 eth,
address[] calldata tokens,
uint256[] calldata amounts
) public {
if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts();
address moduleAddress = _msgSender();
if (IModule(moduleAddress).membership() != membership)
revert Errors.NotMember();
DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress];
address _timelock = address(IModule(moduleAddress).timelock());
address payable _target = payable(_timelock);
if (!_payments.approved) revert Errors.ModuleNotApproved();
if (eth > 0) {
if (eth > _payments.eth) revert Errors.NotEnoughETH();
_payments.eth -= eth;
_target.sendValue(eth);
}
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 _token = IERC20(tokens[i]);
if (_token.allowance(address(this), _timelock) < amounts[i])
revert Errors.NotEnoughTokens();
_token.transferFrom(address(this), _timelock, amounts[i]);
_payments.erc20[tokens[i]] -= amounts[i];
}
emit Events.ModulePaymentPulled(
moduleAddress,
eth,
tokens,
amounts,
block.timestamp
);
}
| 2,520,458
|
pragma solidity ^0.5.0;
// AggregatorInterface specifies ChainLink aggregator interface.
import "./AggregatorInterface.sol";
// ChainLinkPriceReferenceAggregator implements aggregation for set of ChainLink
// reference price oracles redirecting price requests to their target price
// oracle based on the denomination address.
contract ChainLinkPriceReferenceAggregator {
// TokenInformation represents a single token handled by the reference aggregator.
// The De-Fi API uses this reference to do on-chain tokens tracking.
struct TokenInformation {
address addr; // address of the token (unique identifier)
bytes32 name; // Name fo the token
bytes32 symbol; // symbol of the token
string logo; // URL address of the token logo
uint decimals; // number of decimals the token's price oracle uses
bool isActive; // is this token active in DeFi?
bool canDeposit; // is this token available for deposit?
bool canBorrow; // is this token available for fLend?
bool canTrade; // is this token available for direct fTrade?
uint volatility; // what is the index of volatility of the token in 8 decimals
}
// owner represents the manager address of the oracle aggregator.
address public owner;
// ChainLink aggregator interface references by denomination.
// The left side is the token identifier, the right side
// is the ChainLink aggregator address.
mapping(address => AggregatorInterface) public aggregators;
// tokens is the list of tokens handled by the DeFi reference aggregator.
TokenInformation[] public tokens;
// AggregatorChanged event is emitted when a new price oracle aggregator is set for a token.
event AggregatorChanged(address indexed token, address aggregator, uint timestamp);
// TokenInformationAdded event is emitted when a new token information is added to the contract.
event TokenInformationAdded(address indexed token, uint index, bytes32 name, uint timestamp);
// TokenInformationUpdated event is emitted when an existing token information is updated.
event TokenInformationChanged(address indexed token, uint index, uint timestamp);
// install new aggregator instance
constructor() public {
// remember the manager address
owner = msg.sender;
}
// -----------------------------------------------
// aggregators per token address management
// -----------------------------------------------
// setAggregator sets a new aggregator reference for the given token.
function setAggregator(address token, address aggregator) external {
// only owner can make the change
require(msg.sender == owner, "access restricted");
// make the change
aggregators[token] = AggregatorInterface(aggregator);
// emit notification to express the change
emit AggregatorChanged(token, aggregator, now);
}
// -----------------------------------------------
// current price and time stamp
// -----------------------------------------------
// getPrice returns the latest price available for the token specified.
function getPrice(address token) public view returns (int256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer from the aggregator of the given token
return aggregators[token].latestAnswer();
}
// getTimeStamp returns the time stamp the latest price was made available
// by the ChainLink aggregator oracle for the token specified.
function getTimeStamp(address token) public view returns (uint256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer from the aggregator of the given token
return aggregators[token].latestTimestamp();
}
// -----------------------------------------------
// prices and time stamps history
// -----------------------------------------------
// getPreviousPrice returns the price available for the token specified
// from the ChainLink aggregator oracle <_back> update cycles before the most recent one.
function getPreviousPrice(address token, uint256 _back) public view returns (int256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer round from the aggregator of the given token
// we make sure the requested round is valid
uint256 latest = aggregators[token].latestRound();
require(_back <= latest, "not enough history");
// get the price back then
return aggregators[token].getAnswer(latest - _back);
}
// getTimeStamp returns the time stamp the price was made available
// by the ChainLink aggregator oracle <_back> update cycles before the most recent one.
function getPreviousTimeStamp(address token, uint256 _back) public view returns (uint256) {
// the price oracle must be set for the token
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
// get the latest answer round from the aggregator of the given token
// we make sure the requested round is valid
uint256 latest = aggregators[token].latestRound();
require(_back <= latest, "not enough history");
// get the time stamp back then
return aggregators[token].getTimestamp(latest - _back);
}
// -----------------------------------------------
// tokens registry related functions below this
// -----------------------------------------------
// tokensCount returns the total number of tokens' details in the registry.
function tokensCount() public view returns (uint256) {
return tokens.length;
}
// findTokenIndex finds an index of a token in the tokens list by address; returns -1 if not found.
function findTokenIndex(address _addr) public view returns (int256) {
// loop the list and try to find the token
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i].addr == _addr) {
return int256(i);
}
}
return - 1;
}
// addToken adds new token into the reference contract.
function addToken(
address _addr,
address _aggregator,
bytes32 _name,
bytes32 _symbol,
string calldata _logo,
uint _decimals,
bool _isActive,
bool _canDeposit,
bool _canBorrow,
bool _canTrade,
uint _volatility
) external {
// make sure only owner can do this
require(msg.sender == owner, "access restricted");
// try to find the address
require(0 > findTokenIndex(_addr), "token already known");
// set the price aggregator
aggregators[_addr] = AggregatorInterface(_aggregator);
emit AggregatorChanged(_addr, _aggregator, now);
// add the token to the list
tokens.push(TokenInformation({
addr : _addr,
name : _name,
symbol : _symbol,
logo: _logo,
decimals : _decimals,
isActive : _isActive,
canDeposit : _canDeposit,
canBorrow : _canBorrow,
canTrade : _canTrade,
volatility : _volatility
})
);
// inform
emit TokenInformationAdded(_addr, tokens.length - 1, _name, now);
}
// updateToken modifies existing token in the reference contract.
function updateToken(
address _addr,
string calldata _logo,
uint _decimals,
bool _isActive,
bool _canDeposit,
bool _canBorrow,
bool _canTrade,
uint _volatility
) external {
// make sure only owner can do this
require(msg.sender == owner, "access restricted");
// try to find the address in the tokens list
int256 ix = findTokenIndex(_addr);
require(0 <= ix, "token not known");
// update token details in the contract
tokens[uint256(ix)].logo = _logo;
tokens[uint256(ix)].decimals = _decimals;
tokens[uint256(ix)].isActive = _isActive;
tokens[uint256(ix)].canDeposit = _canDeposit;
tokens[uint256(ix)].canBorrow = _canBorrow;
tokens[uint256(ix)].canTrade = _canTrade;
tokens[uint256(ix)].volatility = _volatility;
// inform
emit TokenInformationChanged(_addr, uint256(ix), now);
}
}
|
getPrice returns the latest price available for the token specified. the price oracle must be set for the token get the latest answer from the aggregator of the given token
|
function getPrice(address token) public view returns (int256) {
require(aggregators[token] != AggregatorInterface(0), "oracle not available");
return aggregators[token].latestAnswer();
}
| 1,060,192
|
./full_match/84531/0xA82d7ED01c31DD2A46681D18E3E213C9E9231605/sources/contracts/sale/v2/FlatPriceSale.sol
|
/ Sweep an ERC20 token to the recipient (public function)
|
Public management functions
function sweepToken(IERC20Upgradeable token) external {
uint256 amount = token.balanceOf(address(this));
token.safeTransfer(config.recipient, amount);
emit SweepToken(address(token), amount);
}
| 14,320,239
|
./full_match/4/0xe9a5Fe6aaC4aBa34Fa9200331dC08D21447FBE2B/sources/contracts/RewardToken.sol
|
Function that overrides the ERC20 decimals to set decimals in 0 This sets the min quantity of tokens in 1/
|
function decimals() public view virtual override(ERC20Upgradeable) returns (uint8) {
return 18;
}
| 13,338,339
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
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 three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
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.8.0;
import "../utils/Context.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 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 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 {
require(hasRole(getRoleAdmin(role), _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 override {
require(hasRole(getRoleAdmin(role), _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 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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev 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 "./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 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);
}
}
// 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;
// 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: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
import "contracts/OndoRegistryClient.sol";
import "contracts/TrancheToken.sol";
import "contracts/interfaces/IStrategy.sol";
import "contracts/interfaces/ITrancheToken.sol";
import "contracts/interfaces/IPairVault.sol";
/**
* @title A container for all Vaults
* @notice Vaults are created and managed here
* @dev Because Ethereum transactions are so expensive,
* we reinvent an OO system in this code. There are 4 primary
* functions:
*
* deposit, withdraw: investors can add remove funds into a
* particular tranche in a Vault.
* invest, redeem: a strategist pushes the Vault to buy/sell LP tokens in
* an underlying AMM
*/
contract AllPairVault is OndoRegistryClient, IPairVault {
using OLib for OLib.Investor;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
// A Vault object is parameterized by these values.
struct Vault {
mapping(OLib.Tranche => Asset) assets; // Assets corresponding to each tranche
IStrategy strategy; // Shared contract that interacts with AMMs
address creator; // Account that calls createVault
address strategist; // Has the right to call invest() and redeem(), and harvest() if strategy supports it
address rollover; // Manager of investment auto-rollover, if any
uint256 rolloverId;
uint256 hurdleRate; // Return offered to senior tranche
OLib.State state; // Current state of Vault
uint256 startAt; // Time when the Vault is unpaused to begin accepting deposits
uint256 investAt; // Time when investors can't move funds, strategist can invest
uint256 redeemAt; // Time when strategist can redeem LP tokens, investors can withdraw
}
// (TrancheToken address => (investor address => OLib.Investor)
mapping(address => mapping(address => OLib.Investor)) investors;
// An instance of TrancheToken from which all other tokens are cloned
address public immutable trancheTokenImpl;
// Locate Vault by hashing metadata about the product
mapping(uint256 => Vault) private Vaults;
// Locate Vault by starting from the TrancheToken address
mapping(address => uint256) public VaultsByTokens;
// All Vault IDs
EnumerableSet.UintSet private vaultIDs;
// Not marking these as constants because it doesn't fit the max contract size. But these are actually constants.
bytes32 private TOKEN_MINTING = keccak256("TOKEN_MINTING");
bytes32 private MID_DURATION_ENTRY = keccak256("MID_DURATION_ENTRY");
bytes32 private MID_DURATION_EXIT = keccak256("MID_DURATION_EXIT");
// Access restriction to registered strategist
modifier onlyStrategist(uint256 _vaultId) {
require(msg.sender == Vaults[_vaultId].strategist, "Invalid caller");
_;
}
// Access restriction to registered rollover
modifier onlyRollover(uint256 _vaultId, uint256 _rolloverId) {
Vault storage vault_ = Vaults[_vaultId];
require(
msg.sender == vault_.rollover && _rolloverId == vault_.rolloverId,
"Invalid caller"
);
_;
}
// Access restriction to rollover or strategist.
modifier onlyRolloverOrStrategist(uint256 _vaultId) {
Vault storage vault_ = Vaults[_vaultId];
address rollover = vault_.rollover;
require(
(msg.sender == vault_.strategist) || (msg.sender == rollover),
"Invalid caller"
);
_;
}
// Guard functions with state machine
modifier atState(uint256 _vaultId, OLib.State _state) {
require(getState(_vaultId) == _state, "Invalid operation");
_;
}
// Determine if one can move to a new state. For now the transitions
// are strictly linear. No state machines, really.
function transition(uint256 _vaultId, OLib.State _nextState) private {
Vault storage vault_ = Vaults[_vaultId];
OLib.State curState = vault_.state;
if (_nextState == OLib.State.Live) {
require(curState == OLib.State.Deposit, "Invalid operation");
require(vault_.investAt <= block.timestamp, "Not time yet");
} else {
require(
curState == OLib.State.Live && _nextState == OLib.State.Withdraw,
"Invalid operation"
);
require(vault_.redeemAt <= block.timestamp, "Not time yet");
}
vault_.state = _nextState;
}
// Determine if a Vault can shift to an open state. A Vault is started
// in an inactive state. It can only move forward when time has
// moved past the starttime.
function maybeOpenDeposit(uint256 _vaultId) private {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.state == OLib.State.Inactive) {
require(
vault_.startAt > 0 && vault_.startAt <= block.timestamp,
"Not time yet"
);
vault_.state = OLib.State.Deposit;
} else if (vault_.state != OLib.State.Deposit) {
revert("Invalid operation");
}
}
// modifier onlyETH(uint256 _vaultId, OLib.Tranche _tranche) {
// require(
// address((getVaultById(_vaultId)).assets[uint256(_tranche)].token) ==
// address(registry.weth()),
// "Not an ETH vault"
// );
// _;
// }
function onlyETH(uint256 _vaultId, OLib.Tranche _tranche) private view {
require(
address((getVaultById(_vaultId)).assets[uint256(_tranche)].token) ==
address(registry.weth()),
"Not an ETH vault"
);
}
/**
* Event declarations
*/
event CreatedPair(
uint256 indexed vaultId,
IERC20 indexed seniorAsset,
IERC20 indexed juniorAsset,
ITrancheToken seniorToken,
ITrancheToken juniorToken
);
event SetRollover(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId
);
event Deposited(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 amount
);
event Invested(
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event DepositedLP(
address indexed depositor,
uint256 indexed vaultId,
uint256 amount,
uint256 seniorTrancheMintedAmount,
uint256 juniorTrancheMintedAmount
);
event RolloverDeposited(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event Claimed(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 shares,
uint256 excess
);
event RolloverClaimed(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event Redeemed(
uint256 indexed vaultId,
uint256 seniorReceived,
uint256 juniorReceived
);
event Withdrew(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 amount,
uint256 burnedAmount
);
event WithdrewLP(
address indexed depositor,
uint256 indexed vaultId,
uint256 amount,
uint256 seniorTrancheBurnedAmount,
uint256 juniorTrancheBurnedAmount
);
/**
* @notice Container points back to registry
* @dev Hook up this contract to the global registry.
*/
constructor(address _registry, address _trancheTokenImpl)
OndoRegistryClient(_registry)
{
require(_trancheTokenImpl != address(0), "Invalid target");
trancheTokenImpl = _trancheTokenImpl;
}
/**
* @notice Initialize parameters for a Vault
* @dev
* @param _params Struct with all initialization info
* @return vaultId hashed identifier of Vault used everywhere
**/
function createVault(OLib.VaultParams calldata _params)
external
override
whenNotPaused
isAuthorized(OLib.CREATOR_ROLE)
nonReentrant
returns (uint256 vaultId)
{
require(
registry.authorized(OLib.STRATEGY_ROLE, _params.strategy),
"Invalid target"
);
require(
registry.authorized(OLib.STRATEGIST_ROLE, _params.strategist),
"Invalid target"
);
require(_params.startTime >= block.timestamp, "Invalid start time");
require(
_params.enrollment > 0 && _params.duration > 0,
"No zero intervals"
);
require(_params.hurdleRate < 1e8, "Maximum hurdle is 10000%");
require(denominator <= _params.hurdleRate, "Min hurdle is 100%");
require(
_params.seniorAsset != address(0) &&
_params.seniorAsset != address(this) &&
_params.juniorAsset != address(0) &&
_params.juniorAsset != address(this),
"Invalid target"
);
uint256 investAtTime = _params.startTime + _params.enrollment;
uint256 redeemAtTime = investAtTime + _params.duration;
TrancheToken seniorITrancheToken;
TrancheToken juniorITrancheToken;
{
vaultId = uint256(
keccak256(
abi.encode(
_params.seniorAsset,
_params.juniorAsset,
_params.strategy,
_params.hurdleRate,
_params.startTime,
investAtTime,
redeemAtTime
)
)
);
vaultIDs.add(vaultId);
Vault storage vault_ = Vaults[vaultId];
require(address(vault_.strategist) == address(0), "Duplicate");
vault_.strategy = IStrategy(_params.strategy);
vault_.creator = msg.sender;
vault_.strategist = _params.strategist;
vault_.hurdleRate = _params.hurdleRate;
vault_.startAt = _params.startTime;
vault_.investAt = investAtTime;
vault_.redeemAt = redeemAtTime;
seniorITrancheToken = TrancheToken(
Clones.cloneDeterministic(
trancheTokenImpl,
keccak256(abi.encodePacked(uint256(0), vaultId))
)
);
juniorITrancheToken = TrancheToken(
Clones.cloneDeterministic(
trancheTokenImpl,
keccak256(abi.encodePacked(uint256(1), vaultId))
)
);
vault_.assets[OLib.Tranche.Senior].token = IERC20(_params.seniorAsset);
vault_.assets[OLib.Tranche.Junior].token = IERC20(_params.juniorAsset);
vault_.assets[OLib.Tranche.Senior].trancheToken = seniorITrancheToken;
vault_.assets[OLib.Tranche.Junior].trancheToken = juniorITrancheToken;
vault_.assets[OLib.Tranche.Senior].trancheCap = _params.seniorTrancheCap;
vault_.assets[OLib.Tranche.Senior].userCap = _params.seniorUserCap;
vault_.assets[OLib.Tranche.Junior].trancheCap = _params.juniorTrancheCap;
vault_.assets[OLib.Tranche.Junior].userCap = _params.juniorUserCap;
VaultsByTokens[address(seniorITrancheToken)] = vaultId;
VaultsByTokens[address(juniorITrancheToken)] = vaultId;
if (vault_.startAt == block.timestamp) {
vault_.state = OLib.State.Deposit;
}
IStrategy(_params.strategy).addVault(
vaultId,
IERC20(_params.seniorAsset),
IERC20(_params.juniorAsset)
);
seniorITrancheToken.initialize(
vaultId,
_params.seniorName,
_params.seniorSym,
address(this)
);
juniorITrancheToken.initialize(
vaultId,
_params.juniorName,
_params.juniorSym,
address(this)
);
}
emit CreatedPair(
vaultId,
IERC20(_params.seniorAsset),
IERC20(_params.juniorAsset),
seniorITrancheToken,
juniorITrancheToken
);
}
/**
* @notice Set the rollover details for a Vault
* @dev
* @param _vaultId Vault to update
* @param _rollover Account of approved rollover agent
* @param _rolloverId Rollover fund in RolloverVault
*/
function setRollover(
uint256 _vaultId,
address _rollover,
uint256 _rolloverId
) external override isAuthorized(OLib.ROLLOVER_ROLE) {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.rollover != address(0)) {
require(
msg.sender == vault_.rollover && _rolloverId == vault_.rolloverId,
"Invalid caller"
);
}
vault_.rollover = _rollover;
vault_.rolloverId = _rolloverId;
emit SetRollover(_rollover, _rolloverId, _vaultId);
}
/** @dev Enforce cap on user investment if any
*/
function depositCapGuard(uint256 _allowedAmount, uint256 _amount)
internal
pure
{
require(
_allowedAmount == 0 || _amount <= _allowedAmount,
"Exceeds user cap"
);
}
/**
* @notice Deposit funds into specific tranche of specific Vault
* @dev OLib.Tranche balances are maintained by a unique ERC20 contract
* @param _vaultId Specific ID for this Vault
* @param _tranche Tranche to be deposited in
* @param _amount Amount of tranche asset to transfer to the strategy contract
*/
function _deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount,
address _payer
) internal whenNotPaused {
maybeOpenDeposit(_vaultId);
Vault storage vault_ = Vaults[_vaultId];
vault_.assets[_tranche].token.safeTransferFrom(
_payer,
address(vault_.strategy),
_amount
);
uint256 _total = vault_.assets[_tranche].deposited += _amount;
OLib.Investor storage _investor =
investors[address(vault_.assets[_tranche].trancheToken)][msg.sender];
uint256 userSum =
_investor.userSums.length > 0
? _investor.userSums[_investor.userSums.length - 1] + _amount
: _amount;
depositCapGuard(vault_.assets[_tranche].userCap, userSum);
_investor.prefixSums.push(_total);
_investor.userSums.push(userSum);
emit Deposited(msg.sender, _vaultId, uint256(_tranche), _amount);
}
function deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount
) external override nonReentrant {
_deposit(_vaultId, _tranche, _amount, msg.sender);
}
function depositETH(uint256 _vaultId, OLib.Tranche _tranche)
external
payable
override
nonReentrant
{
onlyETH(_vaultId, _tranche);
registry.weth().deposit{value: msg.value}();
_deposit(_vaultId, _tranche, msg.value, address(this));
}
/**
* @notice Called by rollover to deposit funds
* @dev Rollover gets priority over other depositors.
* @param _vaultId Vault to work on
* @param _rolloverId Rollover that is depositing funds
* @param _seniorAmount Total available amount of assets
* @param _juniorAmount Total available amount of assets
*/
function depositFromRollover(
uint256 _vaultId,
uint256 _rolloverId,
uint256 _seniorAmount,
uint256 _juniorAmount
)
external
override
onlyRollover(_vaultId, _rolloverId)
whenNotPaused
nonReentrant
{
maybeOpenDeposit(_vaultId);
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
senior_.deposited += _seniorAmount;
junior_.deposited += _juniorAmount;
senior_.rolloverDeposited += _seniorAmount;
junior_.rolloverDeposited += _juniorAmount;
senior_.token.safeTransferFrom(
msg.sender,
address(vault_.strategy),
_seniorAmount
);
junior_.token.safeTransferFrom(
msg.sender,
address(vault_.strategy),
_juniorAmount
);
emit RolloverDeposited(
msg.sender,
_rolloverId,
_vaultId,
_seniorAmount,
_juniorAmount
);
}
/**
* @notice Deposit more LP tokens into a Vault that is live
* @dev When a Vault is created it establishes a ratio between
* senior/junior tranche tokens per LP token. If LP tokens are added
* while the Vault is running, it will get the same ratio of tranche
* tokens in return, regardless of the current balance in the pool.
* @param _vaultId reference to Vault
* @param _lpTokens Amount of LP tokens to provide
*/
function depositLp(uint256 _vaultId, uint256 _lpTokens)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensOwed, uint256 juniorTokensOwed)
{
require(
registry.getFeatureFlag(MID_DURATION_ENTRY) == true,
"Mid-duration entry is disabled"
);
Vault storage vault_ = Vaults[_vaultId];
IERC20 pool;
(seniorTokensOwed, juniorTokensOwed, pool) = getDepositLp(
_vaultId,
_lpTokens
);
depositCapGuard(
vault_.assets[OLib.Tranche.Senior].userCap,
seniorTokensOwed
);
depositCapGuard(
vault_.assets[OLib.Tranche.Junior].userCap,
juniorTokensOwed
);
vault_.assets[OLib.Tranche.Senior].totalInvested += seniorTokensOwed;
vault_.assets[OLib.Tranche.Junior].totalInvested += juniorTokensOwed;
vault_.assets[OLib.Tranche.Senior].trancheToken.mint(
msg.sender,
seniorTokensOwed
);
vault_.assets[OLib.Tranche.Junior].trancheToken.mint(
msg.sender,
juniorTokensOwed
);
pool.safeTransferFrom(msg.sender, address(vault_.strategy), _lpTokens);
vault_.strategy.addLp(_vaultId, _lpTokens);
emit DepositedLP(
msg.sender,
_vaultId,
_lpTokens,
seniorTokensOwed,
juniorTokensOwed
);
}
function getDepositLp(uint256 _vaultId, uint256 _lpTokens)
public
view
atState(_vaultId, OLib.State.Live)
returns (
uint256 seniorTokensOwed,
uint256 juniorTokensOwed,
IERC20 pool
)
{
Vault storage vault_ = Vaults[_vaultId];
(uint256 shares, uint256 vaultShares, IERC20 ammPool) =
vault_.strategy.sharesFromLp(_vaultId, _lpTokens);
seniorTokensOwed =
(vault_.assets[OLib.Tranche.Senior].totalInvested * shares) /
vaultShares;
juniorTokensOwed =
(vault_.assets[OLib.Tranche.Junior].totalInvested * shares) /
vaultShares;
pool = ammPool;
}
/**
* @notice Invest funds into AMM
* @dev Push deposited funds into underlying strategy contract
* @param _vaultId Specific id for this Vault
* @param _seniorMinIn To ensure you get a decent price
* @param _juniorMinIn Same. Passed to addLiquidity on AMM
*
*/
function invest(
uint256 _vaultId,
uint256 _seniorMinIn,
uint256 _juniorMinIn
)
external
override
whenNotPaused
nonReentrant
onlyRolloverOrStrategist(_vaultId)
returns (uint256, uint256)
{
transition(_vaultId, OLib.State.Live);
Vault storage vault_ = Vaults[_vaultId];
investIntoStrategy(vault_, _vaultId, _seniorMinIn, _juniorMinIn);
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
senior_.totalInvested = vault_.assets[OLib.Tranche.Senior].originalInvested;
junior_.totalInvested = vault_.assets[OLib.Tranche.Junior].originalInvested;
emit Invested(_vaultId, senior_.totalInvested, junior_.totalInvested);
return (senior_.totalInvested, junior_.totalInvested);
}
/*
* @dev Separate investable amount calculation and strategy call from storage updates
to keep the stack down.
*/
function investIntoStrategy(
Vault storage vault_,
uint256 _vaultId,
uint256 _seniorMinIn,
uint256 _juniorMinIn
) private {
uint256 seniorInvestableAmount =
vault_.assets[OLib.Tranche.Senior].deposited;
uint256 seniorCappedAmount = seniorInvestableAmount;
if (vault_.assets[OLib.Tranche.Senior].trancheCap > 0) {
seniorCappedAmount = min(
seniorInvestableAmount,
vault_.assets[OLib.Tranche.Senior].trancheCap
);
}
uint256 juniorInvestableAmount =
vault_.assets[OLib.Tranche.Junior].deposited;
uint256 juniorCappedAmount = juniorInvestableAmount;
if (vault_.assets[OLib.Tranche.Junior].trancheCap > 0) {
juniorCappedAmount = min(
juniorInvestableAmount,
vault_.assets[OLib.Tranche.Junior].trancheCap
);
}
(
vault_.assets[OLib.Tranche.Senior].originalInvested,
vault_.assets[OLib.Tranche.Junior].originalInvested
) = vault_.strategy.invest(
_vaultId,
seniorCappedAmount,
juniorCappedAmount,
seniorInvestableAmount - seniorCappedAmount,
juniorInvestableAmount - juniorCappedAmount,
_seniorMinIn,
_juniorMinIn
);
}
/**
* @notice Return undeposited funds and trigger minting in Tranche Token
* @dev Because the tranches must be balanced to buy LP tokens at
* the right ratio, it is likely that some deposits will not be
* accepted. This function transfers that "excess" deposit. Also, it
* finally mints the tranche tokens for this customer.
* @param _vaultId Reference to specific Vault
* @param _tranche which tranche to act on
* @return userInvested Total amount actually invested from this tranche
* @return excess Any uninvested funds
*/
function _claim(
uint256 _vaultId,
OLib.Tranche _tranche,
address _receiver
)
internal
whenNotPaused
atState(_vaultId, OLib.State.Live)
returns (uint256 userInvested, uint256 excess)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage _asset = vault_.assets[_tranche];
ITrancheToken _trancheToken = _asset.trancheToken;
OLib.Investor storage investor =
investors[address(_trancheToken)][msg.sender];
require(!investor.claimed, "Already claimed");
IStrategy _strategy = vault_.strategy;
(userInvested, excess) = investor.getInvestedAndExcess(
_getNetOriginalInvested(_asset)
);
if (excess > 0)
_strategy.withdrawExcess(_vaultId, _tranche, _receiver, excess);
if (registry.getFeatureFlag(TOKEN_MINTING) == true) {
_trancheToken.mint(msg.sender, userInvested);
}
investor.claimed = true;
emit Claimed(msg.sender, _vaultId, uint256(_tranche), userInvested, excess);
return (userInvested, excess);
}
function claim(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256, uint256)
{
return _claim(_vaultId, _tranche, msg.sender);
}
function claimETH(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256 invested, uint256 excess)
{
onlyETH(_vaultId, _tranche);
(invested, excess) = _claim(_vaultId, _tranche, address(this));
registry.weth().withdraw(excess);
safeTransferETH(msg.sender, excess);
}
/**
* @notice Called by rollover to claim both tranches
* @dev Triggers minting of tranche tokens. Moves excess to Rollover.
* @param _vaultId Vault id
* @param _rolloverId Rollover ID
* @return srRollInv Amount invested in tranche
* @return jrRollInv Amount invested in tranche
*/
function rolloverClaim(uint256 _vaultId, uint256 _rolloverId)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
onlyRollover(_vaultId, _rolloverId)
returns (uint256 srRollInv, uint256 jrRollInv)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
OLib.Investor storage investor =
investors[address(senior_.trancheToken)][msg.sender];
require(!investor.claimed, "Already claimed");
srRollInv = _getRolloverInvested(senior_);
jrRollInv = _getRolloverInvested(junior_);
if (srRollInv > 0) {
senior_.trancheToken.mint(msg.sender, srRollInv);
}
if (jrRollInv > 0) {
junior_.trancheToken.mint(msg.sender, jrRollInv);
}
if (senior_.rolloverDeposited > srRollInv) {
vault_.strategy.withdrawExcess(
_vaultId,
OLib.Tranche.Senior,
msg.sender,
senior_.rolloverDeposited - srRollInv
);
}
if (junior_.rolloverDeposited > jrRollInv) {
vault_.strategy.withdrawExcess(
_vaultId,
OLib.Tranche.Junior,
msg.sender,
junior_.rolloverDeposited - jrRollInv
);
}
investor.claimed = true;
emit RolloverClaimed(
msg.sender,
_rolloverId,
_vaultId,
srRollInv,
jrRollInv
);
return (srRollInv, jrRollInv);
}
/**
* @notice Redeem funds into AMM
* @dev Exchange LP tokens for senior/junior assets. Compute the amount
* the senior tranche should get (like 10% more). The senior._received
* value should be equal to or less than that expected amount. The
* junior.received should be all that's left.
* @param _vaultId Specific id for this Vault
* @param _seniorMinReceived Compute total expected to redeem, factoring in slippage
* @param _juniorMinReceived Same.
*/
function redeem(
uint256 _vaultId,
uint256 _seniorMinReceived,
uint256 _juniorMinReceived
)
external
override
whenNotPaused
nonReentrant
onlyRolloverOrStrategist(_vaultId)
returns (uint256, uint256)
{
transition(_vaultId, OLib.State.Withdraw);
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
(senior_.received, junior_.received) = vault_.strategy.redeem(
_vaultId,
_getSeniorExpected(vault_, senior_),
_seniorMinReceived,
_juniorMinReceived
);
emit Redeemed(_vaultId, senior_.received, junior_.received);
return (senior_.received, junior_.received);
}
/**
* @notice Investors withdraw funds from Vault
* @dev Based on the fraction of ownership in the original pool of invested assets,
investors get the same fraction of the resulting pile of assets. All funds are withdrawn.
* @param _vaultId Specific ID for this Vault
* @param _tranche Tranche to be deposited in
* @return tokensToWithdraw Amount investor received from transfer
*/
function _withdraw(
uint256 _vaultId,
OLib.Tranche _tranche,
address _receiver
)
internal
whenNotPaused
atState(_vaultId, OLib.State.Withdraw)
returns (uint256 tokensToWithdraw)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage asset_ = vault_.assets[_tranche];
(, , , tokensToWithdraw) = vaultInvestor(_vaultId, _tranche);
ITrancheToken token_ = asset_.trancheToken;
uint256 bal = 0;
if (registry.getFeatureFlag(TOKEN_MINTING) == true) {
bal = token_.balanceOf(msg.sender);
if (bal > 0) {
token_.burn(msg.sender, bal);
}
}
asset_.token.safeTransferFrom(
address(vault_.strategy),
_receiver,
tokensToWithdraw
);
investors[address(asset_.trancheToken)][msg.sender].withdrawn = true;
emit Withdrew(
msg.sender,
_vaultId,
uint256(_tranche),
tokensToWithdraw,
bal
);
return tokensToWithdraw;
}
function withdraw(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256)
{
return _withdraw(_vaultId, _tranche, msg.sender);
}
function withdrawETH(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256 amount)
{
onlyETH(_vaultId, _tranche);
amount = _withdraw(_vaultId, _tranche, address(this));
registry.weth().withdraw(amount);
safeTransferETH(msg.sender, amount);
}
receive() external payable {
assert(msg.sender == address(registry.weth()));
}
/**
* @notice Exchange the correct ratio of senior/junior tokens to get LP tokens
* @dev Burn tranche tokens on both sides and send LP tokens to customer
* @param _vaultId reference to Vault
* @param _shares Share of lp tokens to withdraw
*/
function withdrawLp(uint256 _vaultId, uint256 _shares)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensNeeded, uint256 juniorTokensNeeded)
{
require(
registry.getFeatureFlag(MID_DURATION_EXIT) == true,
"Mid-duration exit is disabled"
);
Vault storage vault_ = Vaults[_vaultId];
(seniorTokensNeeded, juniorTokensNeeded) = getWithdrawLp(_vaultId, _shares);
require(
seniorTokensNeeded > 0 && juniorTokensNeeded > 0,
"The withdrawal amount is too small"
);
uint256 seniorBal =
vault_.assets[OLib.Tranche.Senior].trancheToken.balanceOf(msg.sender);
uint256 juniorBal =
vault_.assets[OLib.Tranche.Junior].trancheToken.balanceOf(msg.sender);
require(
seniorBal >= seniorTokensNeeded && juniorBal >= juniorTokensNeeded,
"AllPairVault: burn amount exceeds balance"
);
vault_.assets[OLib.Tranche.Senior].trancheToken.burn(
msg.sender,
seniorTokensNeeded
);
vault_.assets[OLib.Tranche.Junior].trancheToken.burn(
msg.sender,
juniorTokensNeeded
);
vault_.assets[OLib.Tranche.Senior].totalInvested -= seniorTokensNeeded;
vault_.assets[OLib.Tranche.Junior].totalInvested -= juniorTokensNeeded;
vault_.strategy.removeLp(_vaultId, _shares, msg.sender);
emit WithdrewLP(
msg.sender,
_vaultId,
_shares,
seniorTokensNeeded,
juniorTokensNeeded
);
}
function getWithdrawLp(uint256 _vaultId, uint256 _shares)
public
view
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensNeeded, uint256 juniorTokensNeeded)
{
Vault storage vault_ = Vaults[_vaultId];
(, uint256 totalShares) = vault_.strategy.getVaultInfo(_vaultId);
seniorTokensNeeded =
(vault_.assets[OLib.Tranche.Senior].totalInvested * _shares) /
totalShares;
juniorTokensNeeded =
(vault_.assets[OLib.Tranche.Junior].totalInvested * _shares) /
totalShares;
}
function getState(uint256 _vaultId)
public
view
override
returns (OLib.State)
{
Vault storage vault_ = Vaults[_vaultId];
return vault_.state;
}
/**
* Helper functions
*/
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "ETH transfer failed");
}
/**
* @notice Multiply senior by hurdle raten
* @param vault Vault to work on
* @param senior Relevant asset
* @return Max value senior can earn for this Vault
*/
function _getSeniorExpected(Vault storage vault, Asset storage senior)
internal
view
returns (uint256)
{
return (senior.totalInvested * vault.hurdleRate) / denominator;
}
function _getNetOriginalInvested(Asset storage asset)
internal
view
returns (uint256)
{
uint256 o = asset.originalInvested;
uint256 r = asset.rolloverDeposited;
return o > r ? o - r : 0;
}
function _getRolloverInvested(Asset storage asset)
internal
view
returns (uint256)
{
uint256 o = asset.originalInvested;
uint256 r = asset.rolloverDeposited;
return o > r ? r : o;
}
/**
* Setters
*/
function canDeposit(uint256 _vaultId) external view override returns (bool) {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.state == OLib.State.Inactive) {
return vault_.startAt <= block.timestamp && vault_.startAt > 0;
}
return vault_.state == OLib.State.Deposit;
}
function getVaults(uint256 _from, uint256 _to)
external
view
returns (VaultView[] memory vaults)
{
EnumerableSet.UintSet storage vaults_ = vaultIDs;
uint256 len = vaults_.length();
if (len == 0) {
return new VaultView[](0);
}
if (len <= _to) {
_to = len - 1;
}
vaults = new VaultView[](1 + _to - _from);
for (uint256 i = _from; i <= _to; i++) {
vaults[i - _from] = getVaultById(vaults_.at(i));
}
return vaults;
}
function getVaultByToken(address _trancheToken)
external
view
returns (VaultView memory)
{
return getVaultById(VaultsByTokens[_trancheToken]);
}
function getVaultById(uint256 _vaultId)
public
view
override
returns (VaultView memory vault)
{
Vault storage svault_ = Vaults[_vaultId];
mapping(OLib.Tranche => Asset) storage sassets_ = svault_.assets;
Asset[] memory assets = new Asset[](2);
assets[0] = sassets_[OLib.Tranche.Senior];
assets[1] = sassets_[OLib.Tranche.Junior];
vault = VaultView(
_vaultId,
assets,
svault_.strategy,
svault_.creator,
svault_.strategist,
svault_.rollover,
svault_.hurdleRate,
svault_.state,
svault_.startAt,
svault_.investAt,
svault_.redeemAt
);
}
function seniorExpected(uint256 _vaultId)
external
view
override
returns (uint256)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
return _getSeniorExpected(vault_, senior_);
}
/*
* @return position: total user invested = unclaimed invested amount + tranche token balance
* @return claimableBalance: unclaimed invested deposit amount that can be converted into tranche tokens by claiming
* @return withdrawableExcess: unclaimed uninvested deposit amount that can be recovered by claiming
* @return withdrawableBalance: total amount that the user can redeem their position for by withdrawaing, 0 if the product is still live
*/
function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche)
public
view
override
returns (
uint256 position,
uint256 claimableBalance,
uint256 withdrawableExcess,
uint256 withdrawableBalance
)
{
Asset storage asset_ = Vaults[_vaultId].assets[_tranche];
OLib.Investor storage investor_ =
investors[address(asset_.trancheToken)][msg.sender];
if (!investor_.withdrawn) {
(position, withdrawableExcess) = investor_.getInvestedAndExcess(
_getNetOriginalInvested(asset_)
);
if (!investor_.claimed) {
claimableBalance = position;
position += asset_.trancheToken.balanceOf(msg.sender);
} else {
withdrawableExcess = 0;
if (registry.getFeatureFlag(TOKEN_MINTING) == true) {
position = asset_.trancheToken.balanceOf(msg.sender);
}
}
if (Vaults[_vaultId].state == OLib.State.Withdraw) {
claimableBalance = 0;
withdrawableBalance =
withdrawableExcess +
(asset_.received * position) /
asset_.totalInvested;
}
}
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function excall(address target, bytes calldata data)
external
isAuthorized(OLib.GUARDIAN_ROLE)
returns (bytes memory returnData)
{
bool success;
(success, returnData) = target.call(data);
require(success, "CF");
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "./OndoRegistryClientInitializable.sol";
abstract contract OndoRegistryClient is OndoRegistryClientInitializable {
constructor(address _registry) {
__OndoRegistryClient__initialize(_registry);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "contracts/interfaces/IRegistry.sol";
import "contracts/libraries/OndoLibrary.sol";
abstract contract OndoRegistryClientInitializable is
Initializable,
ReentrancyGuard,
Pausable
{
using SafeERC20 for IERC20;
IRegistry public registry;
uint256 public denominator;
function __OndoRegistryClient__initialize(address _registry)
internal
initializer
{
require(_registry != address(0), "Invalid registry address");
registry = IRegistry(_registry);
denominator = registry.denominator();
}
/**
* @notice General ACL checker
* @param _role Role as defined in OndoLibrary
*/
modifier isAuthorized(bytes32 _role) {
require(registry.authorized(_role, msg.sender), "Unauthorized");
_;
}
/*
* @notice Helper to expose a Pausable interface to tools
*/
function paused() public view virtual override returns (bool) {
return registry.paused() || super.paused();
}
function pause() external virtual isAuthorized(OLib.PANIC_ROLE) {
super._pause();
}
function unpause() external virtual isAuthorized(OLib.GUARDIAN_ROLE) {
super._unpause();
}
/**
* @notice Grab tokens and send to caller
* @dev If the _amount[i] is 0, then transfer all the tokens
* @param _tokens List of tokens
* @param _amounts Amount of each token to send
*/
function _rescueTokens(address[] calldata _tokens, uint256[] memory _amounts)
internal
virtual
{
for (uint256 i = 0; i < _tokens.length; i++) {
uint256 amount = _amounts[i];
if (amount == 0) {
amount = IERC20(_tokens[i]).balanceOf(address(this));
}
IERC20(_tokens[i]).safeTransfer(msg.sender, amount);
}
}
function rescueTokens(address[] calldata _tokens, uint256[] memory _amounts)
public
whenPaused
isAuthorized(OLib.GUARDIAN_ROLE)
{
require(_tokens.length == _amounts.length, "Invalid array sizes");
_rescueTokens(_tokens, _amounts);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "contracts/interfaces/ITrancheToken.sol";
import "contracts/OndoRegistryClientInitializable.sol";
/**
* @title Fixed duration tokens representing tranches
* @notice For every Vault, for every tranche, this ERC20 token enables trading.
* @dev Since these are short-lived tokens and we are producing lots
* of them, this uses clones to cheaply create many instance. in
* practice this is not upgradeable, we use openzeppelin's clone
*/
contract TrancheToken is ERC20Upgradeable, ITrancheToken, OwnableUpgradeable {
OndoRegistryClientInitializable public vault;
uint256 public vaultId;
modifier whenNotPaused {
require(!vault.paused(), "Global pause in effect");
_;
}
function initialize(
uint256 _vaultId,
string calldata _name,
string calldata _symbol,
address _vault
) external initializer {
require(_vault != address(0), "Invalid vault address");
__Ownable_init();
__ERC20_init(_name, _symbol);
vault = OndoRegistryClientInitializable(_vault);
vaultId = _vaultId;
}
function mint(address _account, uint256 _amount)
external
override
whenNotPaused
onlyOwner
{
_mint(_account, _amount);
}
function burn(address _account, uint256 _amount)
external
override
whenNotPaused
onlyOwner
{
_burn(_account, _amount);
}
function transfer(address _account, uint256 _amount)
public
override(ERC20Upgradeable, IERC20Upgradeable)
whenNotPaused
returns (bool)
{
return super.transfer(_account, _amount);
}
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
override(ERC20Upgradeable, IERC20Upgradeable)
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _amount);
}
function approve(address _account, uint256 _amount)
public
override(ERC20Upgradeable, IERC20Upgradeable)
whenNotPaused
returns (bool)
{
return super.approve(_account, _amount);
}
function increaseAllowance(address spender, uint256 addedValue)
public
override(ERC20Upgradeable)
whenNotPaused
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
override(ERC20Upgradeable)
whenNotPaused
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "contracts/libraries/OndoLibrary.sol";
import "contracts/interfaces/ITrancheToken.sol";
import "contracts/interfaces/IStrategy.sol";
interface IPairVault {
// Container to return Vault info to caller
struct VaultView {
uint256 id;
Asset[] assets;
IStrategy strategy; // Shared contract that interacts with AMMs
address creator; // Account that calls createVault
address strategist; // Has the right to call invest() and redeem(), and harvest() if strategy supports it
address rollover;
uint256 hurdleRate; // Return offered to senior tranche
OLib.State state; // Current state of Vault
uint256 startAt; // Time when the Vault is unpaused to begin accepting deposits
uint256 investAt; // Time when investors can't move funds, strategist can invest
uint256 redeemAt; // Time when strategist can redeem LP tokens, investors can withdraw
}
// Track the asset type and amount in different stages
struct Asset {
IERC20 token;
ITrancheToken trancheToken;
uint256 trancheCap;
uint256 userCap;
uint256 deposited;
uint256 originalInvested;
uint256 totalInvested; // not literal 1:1, originalInvested + proportional lp from mid-term
uint256 received;
uint256 rolloverDeposited;
}
function getState(uint256 _vaultId) external view returns (OLib.State);
function createVault(OLib.VaultParams calldata _params)
external
returns (uint256 vaultId);
function deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount
) external;
function depositETH(uint256 _vaultId, OLib.Tranche _tranche) external payable;
function depositLp(uint256 _vaultId, uint256 _amount)
external
returns (uint256 seniorTokensOwed, uint256 juniorTokensOwed);
function invest(
uint256 _vaultId,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256, uint256);
function redeem(
uint256 _vaultId,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256, uint256);
function withdraw(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256);
function withdrawETH(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256);
function withdrawLp(uint256 _vaultId, uint256 _amount)
external
returns (uint256, uint256);
function claim(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256, uint256);
function claimETH(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256, uint256);
function depositFromRollover(
uint256 _vaultId,
uint256 _rolloverId,
uint256 _seniorAmount,
uint256 _juniorAmount
) external;
function rolloverClaim(uint256 _vaultId, uint256 _rolloverId)
external
returns (uint256, uint256);
function setRollover(
uint256 _vaultId,
address _rollover,
uint256 _rolloverId
) external;
function canDeposit(uint256 _vaultId) external view returns (bool);
function getVaultById(uint256 _vaultId)
external
view
returns (VaultView memory);
function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche)
external
view
returns (
uint256 position,
uint256 claimableBalance,
uint256 withdrawableExcess,
uint256 withdrawableBalance
);
function seniorExpected(uint256 _vaultId) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "contracts/interfaces/IWETH.sol";
/**
* @title Global values used by many contracts
* @notice This is mostly used for access control
*/
interface IRegistry is IAccessControl {
function paused() external view returns (bool);
function pause() external;
function unpause() external;
function enableFeatureFlag(bytes32 _featureFlag) external;
function disableFeatureFlag(bytes32 _featureFlag) external;
function getFeatureFlag(bytes32 _featureFlag) external view returns (bool);
function denominator() external view returns (uint256);
function weth() external view returns (IWETH);
function authorized(bytes32 _role, address _account)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "contracts/libraries/OndoLibrary.sol";
import "contracts/interfaces/IPairVault.sol";
interface IStrategy {
// Additional info stored for each Vault
struct Vault {
IPairVault origin; // who created this Vault
IERC20 pool; // the DEX pool
IERC20 senior; // senior asset in pool
IERC20 junior; // junior asset in pool
uint256 shares; // number of shares for ETF-style mid-duration entry/exit
uint256 seniorExcess; // unused senior deposits
uint256 juniorExcess; // unused junior deposits
}
function vaults(uint256 vaultId)
external
view
returns (
IPairVault origin,
IERC20 pool,
IERC20 senior,
IERC20 junior,
uint256 shares,
uint256 seniorExcess,
uint256 juniorExcess
);
function addVault(
uint256 _vaultId,
IERC20 _senior,
IERC20 _junior
) external;
function addLp(uint256 _vaultId, uint256 _lpTokens) external;
function removeLp(
uint256 _vaultId,
uint256 _shares,
address to
) external;
function getVaultInfo(uint256 _vaultId)
external
view
returns (IERC20, uint256);
function invest(
uint256 _vaultId,
uint256 _totalSenior,
uint256 _totalJunior,
uint256 _extraSenior,
uint256 _extraJunior,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256 seniorInvested, uint256 juniorInvested);
function sharesFromLp(uint256 vaultId, uint256 lpTokens)
external
view
returns (
uint256 shares,
uint256 vaultShares,
IERC20 pool
);
function lpFromShares(uint256 vaultId, uint256 shares)
external
view
returns (uint256 lpTokens, uint256 vaultShares);
function redeem(
uint256 _vaultId,
uint256 _seniorExpected,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256, uint256);
function withdrawExcess(
uint256 _vaultId,
OLib.Tranche tranche,
address to,
uint256 amount
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ITrancheToken is IERC20Upgradeable {
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/Arrays.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Helper functions
*/
library OLib {
using Arrays for uint256[];
// State transition per Vault. Just linear transitions.
enum State {Inactive, Deposit, Live, Withdraw}
// Only supports 2 tranches for now
enum Tranche {Senior, Junior}
struct VaultParams {
address seniorAsset;
address juniorAsset;
address strategist;
address strategy;
uint256 hurdleRate;
uint256 startTime;
uint256 enrollment;
uint256 duration;
string seniorName;
string seniorSym;
string juniorName;
string juniorSym;
uint256 seniorTrancheCap;
uint256 seniorUserCap;
uint256 juniorTrancheCap;
uint256 juniorUserCap;
}
struct RolloverParams {
address strategist;
string seniorName;
string seniorSym;
string juniorName;
string juniorSym;
}
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
bytes32 public constant PANIC_ROLE = keccak256("PANIC_ROLE");
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE");
bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE");
bytes32 public constant STRATEGIST_ROLE = keccak256("STRATEGIST_ROLE");
bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE");
bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE");
bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE");
// Both sums are running sums. If a user deposits [$1, $5, $3], then
// userSums would be [$1, $6, $9]. You can figure out the deposit
// amount be subtracting userSums[i]-userSum[i-1].
// prefixSums is the total deposited for all investors + this
// investors deposit at the time this deposit is made. So at
// prefixSum[0], it would be $1 + totalDeposits, where totalDeposits
// could be $1000 because other investors have put in money.
struct Investor {
uint256[] userSums;
uint256[] prefixSums;
bool claimed;
bool withdrawn;
}
/**
* @dev Given the total amount invested by the Vault, we want to find
* out how many of this investor's deposits were actually
* used. Use findUpperBound on the prefixSum to find the point
* where total deposits were accepted. For example, if $2000 was
* deposited by all investors and $1000 was invested, then some
* position in the prefixSum splits the array into deposits that
* got in, and deposits that didn't get in. That same position
* maps to userSums. This is the user's deposits that got
* in. Since we are keeping track of the sums, we know at that
* position the total deposits for a user was $15, even if it was
* 15 $1 deposits. And we know the amount that didn't get in is
* the last value in userSum - the amount that got it.
* @param investor A specific investor
* @param invested The total amount invested by this Vault
*/
function getInvestedAndExcess(Investor storage investor, uint256 invested)
internal
view
returns (uint256 userInvested, uint256 excess)
{
uint256[] storage prefixSums_ = investor.prefixSums;
uint256 length = prefixSums_.length;
if (length == 0) {
// There were no deposits. Return 0, 0.
return (userInvested, excess);
}
uint256 leastUpperBound = prefixSums_.findUpperBound(invested);
if (length == leastUpperBound) {
// All deposits got in, no excess. Return total deposits, 0
userInvested = investor.userSums[length - 1];
return (userInvested, excess);
}
uint256 prefixSum = prefixSums_[leastUpperBound];
if (prefixSum == invested) {
// Not all deposits got in, but there are no partial deposits
userInvested = investor.userSums[leastUpperBound];
excess = investor.userSums[length - 1] - userInvested;
} else {
// Let's say some of my deposits got in. The last deposit,
// however, was $100 and only $30 got in. Need to split that
// deposit so $30 got in, $70 is excess.
userInvested = leastUpperBound > 0
? investor.userSums[leastUpperBound - 1]
: 0;
uint256 depositAmount = investor.userSums[leastUpperBound] - userInvested;
if (prefixSum - depositAmount < invested) {
userInvested += (depositAmount + invested - prefixSum);
excess = investor.userSums[length - 1] - userInvested;
} else {
excess = investor.userSums[length - 1] - userInvested;
}
}
}
/*
Used to avoid phantom overflow issues that can arise during this calculation:
@notice Calculates floor(x*y÷denominator) with full precision.
@dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
@dec Credit to prb-math for refactoring for solidity ^0.8 https://github.com/paulrberg/prb-math/blob/main/contracts/PRBMath.sol
*/
function safeMulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
return result;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert("OLib__MulDivOverflow(prod1, denominator)");
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
unchecked {
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 lpotdod = denominator & (~denominator + 1);
assembly {
// Divide denominator by lpotdod.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * lpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel’s lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don’t need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
}
/**
* @title Subset of SafeERC20 from openZeppelin
*
* @dev Some non-standard ERC20 contracts (e.g. Tether) break
* `approve` by forcing it to behave like `safeApprove`. This means
* `safeIncreaseAllowance` will fail when it tries to adjust the
* allowance. The code below simply adds an extra call to
* `approve(spender, 0)`.
*/
library OndoSaferERC20 {
using SafeERC20 for IERC20;
function ondoSafeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
token.safeApprove(spender, 0);
token.safeApprove(spender, newAllowance);
}
}
|
Invest funds into AMM Push deposited funds into underlying strategy contract _vaultId Specific id for this Vault _seniorMinIn To ensure you get a decent price _juniorMinIn Same. Passed to addLiquidity on AMM/
|
function invest(
uint256 _vaultId,
uint256 _seniorMinIn,
uint256 _juniorMinIn
)
external
override
whenNotPaused
nonReentrant
onlyRolloverOrStrategist(_vaultId)
returns (uint256, uint256)
{
transition(_vaultId, OLib.State.Live);
Vault storage vault_ = Vaults[_vaultId];
investIntoStrategy(vault_, _vaultId, _seniorMinIn, _juniorMinIn);
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
senior_.totalInvested = vault_.assets[OLib.Tranche.Senior].originalInvested;
junior_.totalInvested = vault_.assets[OLib.Tranche.Junior].originalInvested;
emit Invested(_vaultId, senior_.totalInvested, junior_.totalInvested);
return (senior_.totalInvested, junior_.totalInvested);
}
| 488,804
|
/**
*Submitted for verification at Etherscan.io on 2021-08-12
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.0;
pragma experimental ABIEncoderV2;
// Harbor Trade 2 addresses at Thu Aug 12 13:31:01 CEST 2021
contract Addresses {
address constant public ACTIONS = 0x80F33ED0A69935dd74310b9D0009D0BA647Cf223;
address constant public AO_REWARD_RECIPIENT = 0x384bE790Ac9526D1103EfC520d733AD64618D90d;
address constant public ASSESSOR = 0x6e40A9d1eE2c8eF95322b879CBae35BE6Dd2D143;
address constant public ASSESSOR_ADMIN = 0x35e805BA2FB7Ad4C8Ad9D644Ca9Bd34a49f5500d;
address constant public COLLECTOR = 0xDdA9c8631ea904Ef4c0444F2A252eC7B45B8e7e9;
address constant public COORDINATOR = 0xE2a04a4d4Df350a752ADA79616D7f588C1A195cF;
address constant public FEED = 0xdB9A84e5214e03a4e5DD14cFB3782e0bcD7567a7;
address constant public JUNIOR_MEMBERLIST = 0x0b635CD35fC3AF8eA29f84155FA03dC9AD0Bab27;
address constant public JUNIOR_OPERATOR = 0x6DAecbC801EcA2873599bA3d980c237D9296cF57;
address constant public JUNIOR_TOKEN = 0xAA67Bb563e14fBd4E92DCc646aAac0c00c7d9526;
address constant public JUNIOR_TRANCHE = 0x294309E42e1b3863a316BEb52df91B1CcB15eef9;
address constant public PILE = 0xE7876f282bdF0f62e5fdb2C63b8b89c10538dF32;
address constant public PROXY_REGISTRY = 0xC9045c815bF123ad12EA75b9A7c579C1e05051f9;
address constant public RESERVE = 0x573a8a054e0C80F0E9B1e96E8a2198BB46c999D6;
address constant public ROOT_CONTRACT = 0x4cA805cE8EcE2E63FfC1F9f8F2731D3F48DF89Df;
address constant public SENIOR_MEMBERLIST = 0x1Bc55bcAf89f514CE5a8336bEC7429a99e804910;
address constant public SENIOR_OPERATOR = 0xEDCD9e36017689c6Fc51C65c517f488E3Cb6C381;
address constant public SENIOR_TOKEN = 0xd511397f79b112638ee3B6902F7B53A0A23386C4;
address constant public SENIOR_TRANCHE = 0x1940E2A20525B103dCC9884902b0186371227393;
address constant public SHELF = 0x5b2b43b3676057e38F332De73A9fCf0F8f6Babf7;
address constant public TINLAKE_CURRENCY = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address constant public TITLE = 0x669Db70d3A0D7941F468B0d907E9d90BD7ddA8d1;
}
interface SpellTinlakeRootLike {
function relyContract(address, address) external;
}
interface SpellMemberlistLike {
function updateMember(address, uint) external;
}
interface SpellReserveLike {
function payout(uint currencyAmount) external;
}
interface DependLike {
function depend(bytes32, address) external;
}
interface FileLike {
function file(bytes32, uint) external;
function file(bytes32, address) external;
}
interface AuthLike {
function rely(address) external;
function deny(address) external;
}
interface MigrationLike {
function migrate(address) external;
}
interface TrancheLike {
function totalSupply() external returns(uint);
function totalRedeem() external returns(uint);
}
interface PoolAdminLike {
function relyAdmin(address) external;
}
interface MgrLike {
function lock(uint) external;
}
interface SpellERC20Like {
function balanceOf(address) external view returns (uint256);
function transferFrom(address, address, uint) external returns (bool);
function approve(address, uint) external;
}
interface PoolRegistryLike {
function file(address pool, bool live, string memory name, string memory data) external;
function find(address pool) external view returns (bool live, string memory name, string memory data);
}
contract TinlakeSpell is Addresses {
bool public done;
string constant public description = "Tinlake maker integration mainnet spell";
address constant public GOVERNANCE = 0xf3BceA7494D8f3ac21585CA4b0E52aa175c24C25;
address constant public POOL_REGISTRY = 0xddf1C516Cf87126c6c610B52FD8d609E67Fb6033;
// TODO: set these new swapped addresses
address constant public COORDINATOR_NEW = 0x37f3D10Bd18124a16f4DcCA02D41F910E3Aa746A;
address constant public ASSESSOR_NEW = 0xf2ED14102ee9D86606Ec24E48e89060ADB6DeFdb;
address constant public RESERVE_NEW = 0x86284A692430c25EfF37007c5707a530A6d63A41;
address constant public SENIOR_TRANCHE_NEW = 0x7E410F288583BfEe30a306F38e451a93Caaa5C47;
address constant public JUNIOR_TRANCHE_NEW = 0x7fe1dBcBEA4e6D3846f5caB67cfC9fce39BF4d71;
address constant public POOL_ADMIN = 0xad88b6F193bF31Be0a44A2914809BC517b03D22e;
address constant public CLERK = 0xcC2B64dC91245110B513f0ad1393a9720F66B996;
// TODO: check these global maker addresses
address constant public SPOTTER = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address constant public VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address constant public JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address constant public LIQ = 0x88f88Bb9E66241B73B84f3A6E197FbBa487b1E30;
address constant public END = 0xBB856d1742fD182a90239D7AE85706C2FE4e5922;
// TODO: set these pool specific maker addresses
address constant public URN = 0xeF1699548717aa4Cf47aD738316280b56814C821;
address constant public RWA_GEM = 0x873F2101047A62F84456E3B2B13df2287925D3F9;
address constant public MAKER_MGR = 0xe1ed3F588A98bF8a3744f4BF74Fd8540e81AdE3f;
// TODO: set these
address constant public POOL_ADMIN1 = 0xd60f7CFC1E051d77031aC21D9DB2F66fE54AE312;
address constant public POOL_ADMIN2 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address constant public POOL_ADMIN3 = 0x46a71eEf8DbcFcbAC7A0e8D5d6B634A649e61fb8;
address constant public POOL_ADMIN4 = 0xa7Aa917b502d86CD5A23FFbD9Ee32E013015e069;
address constant public POOL_ADMIN5 = 0x9eDec77dd2651Ce062ab17e941347018AD4eAEA9;
address constant public POOL_ADMIN6 = 0xEf270f8877Aa1875fc13e78dcA31f3235210368f;
address constant public AO_POOL_ADMIN = 0x384bE790Ac9526D1103EfC520d733AD64618D90d;
// TODO: check these
uint constant public ASSESSOR_MIN_SENIOR_RATIO = 0;
uint constant public MAT_BUFFER = 0.01 * 10**27;
// TODO set these
string constant public SLUG = "harbor-trade-2";
string constant public IPFS_HASH = "QmeZxngmMcMoHDTXY9ovrweykuW9ACK2VqGapyPxPdVRGf";
// permissions to be set
function cast() public {
require(!done, "spell-already-cast");
done = true;
execute();
}
function execute() internal {
SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT_CONTRACT);
// set spell as ward on the core contract to be able to wire the new contracts correctly
root.relyContract(SHELF, address(this));
root.relyContract(COLLECTOR, address(this));
root.relyContract(JUNIOR_TRANCHE, address(this));
root.relyContract(SENIOR_TRANCHE, address(this));
root.relyContract(JUNIOR_OPERATOR, address(this));
root.relyContract(SENIOR_OPERATOR, address(this));
root.relyContract(JUNIOR_TOKEN, address(this));
root.relyContract(SENIOR_TOKEN, address(this));
root.relyContract(JUNIOR_TRANCHE_NEW, address(this));
root.relyContract(SENIOR_TRANCHE_NEW, address(this));
root.relyContract(JUNIOR_MEMBERLIST, address(this));
root.relyContract(SENIOR_MEMBERLIST, address(this));
root.relyContract(CLERK, address(this));
root.relyContract(POOL_ADMIN, address(this));
root.relyContract(ASSESSOR_NEW, address(this));
root.relyContract(COORDINATOR_NEW, address(this));
root.relyContract(RESERVE, address(this));
root.relyContract(RESERVE_NEW, address(this));
root.relyContract(MAKER_MGR, address(this));
// contract migration --> assumption: root contract is already ward on the new contracts
migrateAssessor();
migrateCoordinator();
migrateReserve();
migrateSeniorTranche();
migrateJuniorTranche();
integrateAdapter();
setupPoolAdmin();
// for mkr integration: set minSeniorRatio in Assessor to 0
FileLike(ASSESSOR_NEW).file("minSeniorRatio", ASSESSOR_MIN_SENIOR_RATIO);
updateRegistry();
}
function migrateAssessor() internal {
MigrationLike(ASSESSOR_NEW).migrate(ASSESSOR);
// migrate dependencies
DependLike(ASSESSOR_NEW).depend("navFeed", FEED);
DependLike(ASSESSOR_NEW).depend("juniorTranche", JUNIOR_TRANCHE_NEW);
DependLike(ASSESSOR_NEW).depend("seniorTranche", SENIOR_TRANCHE_NEW);
DependLike(ASSESSOR_NEW).depend("reserve", RESERVE_NEW);
DependLike(ASSESSOR_NEW).depend("lending", CLERK);
// migrate permissions
AuthLike(ASSESSOR_NEW).rely(COORDINATOR_NEW);
AuthLike(ASSESSOR_NEW).rely(RESERVE_NEW);
}
function migrateCoordinator() internal {
MigrationLike(COORDINATOR_NEW).migrate(COORDINATOR);
// migrate dependencies
DependLike(COORDINATOR_NEW).depend("assessor", ASSESSOR_NEW);
DependLike(COORDINATOR_NEW).depend("juniorTranche", JUNIOR_TRANCHE_NEW);
DependLike(COORDINATOR_NEW).depend("seniorTranche", SENIOR_TRANCHE_NEW);
DependLike(COORDINATOR_NEW).depend("reserve", RESERVE_NEW);
// migrate permissions
AuthLike(JUNIOR_TRANCHE_NEW).rely(COORDINATOR_NEW);
AuthLike(JUNIOR_TRANCHE).deny(COORDINATOR);
AuthLike(SENIOR_TRANCHE_NEW).rely(COORDINATOR_NEW);
AuthLike(SENIOR_TRANCHE).deny(COORDINATOR);
}
function migrateReserve() internal {
MigrationLike(RESERVE_NEW).migrate(RESERVE);
// migrate dependencies
DependLike(RESERVE_NEW).depend("currency", TINLAKE_CURRENCY);
DependLike(RESERVE_NEW).depend("shelf", SHELF);
DependLike(RESERVE_NEW).depend("lending", CLERK);
DependLike(RESERVE_NEW).depend("pot", RESERVE_NEW);
DependLike(SHELF).depend("distributor", RESERVE_NEW);
DependLike(SHELF).depend("lender", RESERVE_NEW);
DependLike(COLLECTOR).depend("distributor", RESERVE_NEW);
DependLike(JUNIOR_TRANCHE).depend("reserve", RESERVE_NEW);
// migrate permissions
AuthLike(RESERVE_NEW).rely(JUNIOR_TRANCHE_NEW);
AuthLike(RESERVE_NEW).rely(SENIOR_TRANCHE_NEW);
AuthLike(RESERVE_NEW).rely(ASSESSOR_NEW);
// migrate reserve balance
SpellERC20Like currency = SpellERC20Like(TINLAKE_CURRENCY);
uint balanceReserve = currency.balanceOf(RESERVE);
SpellReserveLike(RESERVE).payout(balanceReserve);
currency.transferFrom(address(this), RESERVE_NEW, balanceReserve);
}
function migrateSeniorTranche() internal {
TrancheLike tranche = TrancheLike(SENIOR_TRANCHE_NEW);
require((tranche.totalSupply() == 0 && tranche.totalRedeem() == 0), "tranche-has-orders");
DependLike(SENIOR_TRANCHE_NEW).depend("reserve", RESERVE_NEW);
DependLike(SENIOR_TRANCHE_NEW).depend("coordinator", COORDINATOR_NEW);
DependLike(SENIOR_OPERATOR).depend("tranche", SENIOR_TRANCHE_NEW);
AuthLike(SENIOR_TOKEN).deny(SENIOR_TRANCHE);
AuthLike(SENIOR_TOKEN).rely(SENIOR_TRANCHE_NEW);
AuthLike(SENIOR_TRANCHE_NEW).rely(SENIOR_OPERATOR);
SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(SENIOR_TRANCHE_NEW, type(uint256).max);
}
function migrateJuniorTranche() internal {
TrancheLike tranche = TrancheLike(JUNIOR_TRANCHE_NEW);
require((tranche.totalSupply() == 0 && tranche.totalRedeem() == 0), "tranche-has-orders");
DependLike(JUNIOR_TRANCHE_NEW).depend("reserve", RESERVE_NEW);
DependLike(JUNIOR_TRANCHE_NEW).depend("coordinator", COORDINATOR_NEW);
DependLike(JUNIOR_OPERATOR).depend("tranche", JUNIOR_TRANCHE_NEW);
AuthLike(JUNIOR_TOKEN).deny(JUNIOR_TRANCHE);
AuthLike(JUNIOR_TOKEN).rely(JUNIOR_TRANCHE_NEW);
AuthLike(JUNIOR_TRANCHE_NEW).rely(JUNIOR_OPERATOR);
SpellMemberlistLike(JUNIOR_MEMBERLIST).updateMember(JUNIOR_TRANCHE_NEW, type(uint256).max);
}
function integrateAdapter() internal {
require(SpellERC20Like(RWA_GEM).balanceOf(MAKER_MGR) == 1 ether);
// dependencies
DependLike(CLERK).depend("assessor", ASSESSOR_NEW);
DependLike(CLERK).depend("mgr", MAKER_MGR);
DependLike(CLERK).depend("coordinator", COORDINATOR_NEW);
DependLike(CLERK).depend("reserve", RESERVE_NEW);
DependLike(CLERK).depend("tranche", SENIOR_TRANCHE_NEW);
DependLike(CLERK).depend("collateral", SENIOR_TOKEN);
DependLike(CLERK).depend("spotter", SPOTTER);
DependLike(CLERK).depend("vat", VAT);
DependLike(CLERK).depend("jug", JUG);
FileLike(CLERK).file("buffer", MAT_BUFFER);
// permissions
AuthLike(CLERK).rely(COORDINATOR_NEW);
AuthLike(CLERK).rely(RESERVE_NEW);
AuthLike(SENIOR_TRANCHE_NEW).rely(CLERK);
AuthLike(RESERVE_NEW).rely(CLERK);
AuthLike(ASSESSOR_NEW).rely(CLERK);
// currency
SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(CLERK, type(uint256).max);
SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(MAKER_MGR, type(uint256).max);
// setup mgr
AuthLike(MAKER_MGR).rely(CLERK);
FileLike(MAKER_MGR).file("urn", URN);
FileLike(MAKER_MGR).file("liq", LIQ);
FileLike(MAKER_MGR).file("end", END);
FileLike(MAKER_MGR).file("owner", CLERK);
FileLike(MAKER_MGR).file("pool", SENIOR_OPERATOR);
FileLike(MAKER_MGR).file("tranche", SENIOR_TRANCHE_NEW);
// lock token
MgrLike(MAKER_MGR).lock(1 ether);
}
function setupPoolAdmin() internal {
PoolAdminLike poolAdmin = PoolAdminLike(POOL_ADMIN);
// setup dependencies
DependLike(POOL_ADMIN).depend("assessor", ASSESSOR_NEW);
DependLike(POOL_ADMIN).depend("lending", CLERK);
DependLike(POOL_ADMIN).depend("seniorMemberlist", SENIOR_MEMBERLIST);
DependLike(POOL_ADMIN).depend("juniorMemberlist", JUNIOR_MEMBERLIST);
// setup permissions
AuthLike(ASSESSOR_NEW).rely(POOL_ADMIN);
AuthLike(CLERK).rely(POOL_ADMIN);
AuthLike(JUNIOR_MEMBERLIST).rely(POOL_ADMIN);
AuthLike(SENIOR_MEMBERLIST).rely(POOL_ADMIN);
// directly relying governance so it can be used to directly add/remove pool admins without going through the root
AuthLike(POOL_ADMIN).rely(GOVERNANCE);
// setup admins
poolAdmin.relyAdmin(POOL_ADMIN1);
poolAdmin.relyAdmin(POOL_ADMIN2);
poolAdmin.relyAdmin(POOL_ADMIN3);
poolAdmin.relyAdmin(POOL_ADMIN4);
poolAdmin.relyAdmin(POOL_ADMIN5);
poolAdmin.relyAdmin(POOL_ADMIN6);
poolAdmin.relyAdmin(AO_POOL_ADMIN);
}
function updateRegistry() internal {
PoolRegistryLike(POOL_REGISTRY).file(ROOT_CONTRACT, true, SLUG, IPFS_HASH);
}
}
|
set spell as ward on the core contract to be able to wire the new contracts correctly contract migration --> assumption: root contract is already ward on the new contracts for mkr integration: set minSeniorRatio in Assessor to 0
|
function execute() internal {
SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT_CONTRACT);
root.relyContract(SHELF, address(this));
root.relyContract(COLLECTOR, address(this));
root.relyContract(JUNIOR_TRANCHE, address(this));
root.relyContract(SENIOR_TRANCHE, address(this));
root.relyContract(JUNIOR_OPERATOR, address(this));
root.relyContract(SENIOR_OPERATOR, address(this));
root.relyContract(JUNIOR_TOKEN, address(this));
root.relyContract(SENIOR_TOKEN, address(this));
root.relyContract(JUNIOR_TRANCHE_NEW, address(this));
root.relyContract(SENIOR_TRANCHE_NEW, address(this));
root.relyContract(JUNIOR_MEMBERLIST, address(this));
root.relyContract(SENIOR_MEMBERLIST, address(this));
root.relyContract(CLERK, address(this));
root.relyContract(POOL_ADMIN, address(this));
root.relyContract(ASSESSOR_NEW, address(this));
root.relyContract(COORDINATOR_NEW, address(this));
root.relyContract(RESERVE, address(this));
root.relyContract(RESERVE_NEW, address(this));
root.relyContract(MAKER_MGR, address(this));
migrateAssessor();
migrateCoordinator();
migrateReserve();
migrateSeniorTranche();
migrateJuniorTranche();
integrateAdapter();
setupPoolAdmin();
FileLike(ASSESSOR_NEW).file("minSeniorRatio", ASSESSOR_MIN_SENIOR_RATIO);
updateRegistry();
}
| 2,367,759
|
pragma solidity ^0.5.0;
import "./openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./proveth/ProvethVerifier.sol";
import "./proveth/Solidity-RLP/contracts/RLPReader.sol";
contract LibSubmarineSimple is ProvethVerifier {
using SafeMath for uint256;
////////////
// Events //
////////////
event Unlocked(
bytes32 indexed _submarineId,
uint96 _commitValue
);
event Revealed(
bytes32 indexed _submarineId,
uint96 _commitValue,
bytes32 _witness,
bytes32 _commitBlockHash,
address _submarineAddr
);
/////////////
// Storage //
/////////////
// the ECDSA v parameter: 27 allows us to be broadcast on any network (i.e.
// mainnet, ropsten, rinkeby etc.)
uint8 public vee = 27;
// How many blocks must a submarine be committed for before being revealed.
// For now, we choose a default of 20. Since a contract cannot look back
// further than 256 blocks (limit comes from EVM BLOCKHASH opcode), we use a
// uint8.
uint8 public commitPeriodLength = 20;
// Stored "session" state information
mapping(bytes32 => SubmarineSession) public sessions;
// A submarine send is considered "finished" when the amount revealed and
// unlocked are both greater than zero, and the amount for the unlock is
// greater than or equal to the reveal amount.
struct SubmarineSession {
// Amount the reveal transaction revealed would be sent in wei. When
// greater than zero, the submarine has been revealed. A uint96 is large
// enough to store the entire Ethereum supply (~ 1e26 Wei) 700 times
// over.
uint96 amountRevealed;
// Amount the unlock transaction recieved in wei. When greater than
// zero, the submarine has been unlocked; however the submarine may not
// be finished, until the unlock amount is GREATER than the promised
// revealed amount.
uint96 amountUnlocked;
// Block number of block containing commit transaction.
uint32 commitTxBlockNumber;
// Index of commit transaction within its block.
uint16 commitTxIndex;
}
/////////////
// Getters //
/////////////
/*
Keeping these functions makes instantiating a contract more expensive for gas costs, but helps with testing
*/
/**
* @notice Helper function to return a submarine ID for associated given
* input data
* @param _user address of the user that initiated the full submarine flow
* @param _libsubmarine address of submarine contract. Usually address(this)
* @param _commitValue amount of ether supposed to be sent in this submarine
* commit
* @param _embeddedDAppData optional Data passed embedded within the unlock
* tx. Clients can put whatever data they want committed to for their
* specific use case
* @param _witness random commit secret data
* @param _gasPrice the gas price that will be paid in the unlock tx
* @param _gasLimit the gas limit that will be set in the unlock tx
*/
function getSubmarineId(
address _user,
address _libsubmarine,
uint256 _commitValue,
bytes memory _embeddedDAppData,
bytes32 _witness,
uint256 _gasPrice,
uint256 _gasLimit
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(
_user,
_libsubmarine,
_commitValue,
_embeddedDAppData,
_witness,
_gasPrice,
_gasLimit
));
}
/**
* @notice Return the session information associated with a submarine ID.
* @return amountRevealed amount promised by user to be unlocked in reveal
* @return amountUnlocked amount actually unlocked by the user at this time
* @return commitTxBlockNumber block number that the user proved holds the
* commit TX.
* @return commitTxIndex the index in the block where the commit tx is.
*/
function getSubmarineState(bytes32 _submarineId) public view returns (
uint96 amountRevealed,
uint96 amountUnlocked,
uint32 commitTxBlockNumber,
uint16 commitTxIndex
) {
SubmarineSession memory sesh = sessions[_submarineId];
return (
sesh.amountRevealed,
sesh.amountUnlocked,
sesh.commitTxBlockNumber,
sesh.commitTxIndex
);
}
/**
* @notice Singleton session getter - amount of money sent in submarine send
* @return amountRevealed amount promised by user to be unlocked in reveal
*/
function getSubmarineAmount(bytes32 _submarineId) public view returns (
uint96 amount
) {
SubmarineSession memory sesh = sessions[_submarineId];
return sesh.amountRevealed;
}
/**
* @notice Singleton session getter - Commit TX Block number
* @return commitTxBlockNumber block number that the user proved holds the
* commit TX.
*/
function getSubmarineCommitBlockNumber(bytes32 _submarineId)
public view returns (uint32 commitTxBlockNumber)
{
SubmarineSession memory sesh = sessions[_submarineId];
return sesh.commitTxBlockNumber;
}
/**
* @notice Singleton session getter - Commit TX Block index inside block
* @return commitTxIndex the index in the block where the commit tx is.
*/
function getSubmarineCommitTxIndex(bytes32 _submarineId)
public view returns(uint16 commitTxIndex)
{
SubmarineSession memory sesh = sessions[_submarineId];
return sesh.commitTxIndex;
}
/////////////
// Setters //
/////////////
/**
* @notice Consumers of this library should implement their custom reveal
* logic by overriding this method. This function is a handler that
* is called by reveal. A user calls reveal, LibSubmarine does the
* required submarine specific stuff, and then calls this handler
* for client specific implementation/handling.
* @param _submarineId the ID for this submarine workflow
* @param _embeddedDAppData optional Data passed embedded within the unlock
* tx. Clients can put whatever data they want committed to for their
* specific use case
* @param _value amount of ether revealed
*
*/
function onSubmarineReveal(
bytes32 _submarineId,
bytes memory _embeddedDAppData,
uint256 _value
) internal;
/**
* @notice Function called by the user to reveal the session.
* @dev warning Must be called within 256 blocks of the commit transaction
* to obtain the correct blockhash.
* @param _commitTxBlockNumber Number of block in which the commit tx was
* included.
* @param _embeddedDAppData optional Data passed embedded within the unlock
* tx. This should probably be null
* @param _witness Witness "secret" we committed to
* @param _rlpUnlockTxUnsigned RLP encoded unsigned unlock transaction
* @param _proofBlob the proof blob that gets passed to proveth to verify
* merkle trie inclusion in a prior block.
*/
function reveal(
uint32 _commitTxBlockNumber,
bytes memory _embeddedDAppData,
bytes32 _witness,
bytes memory _rlpUnlockTxUnsigned,
bytes memory _proofBlob
) public {
bytes32 commitBlockHash = blockhash(_commitTxBlockNumber);
require(
commitBlockHash != 0x0,
"Commit Block is too old to retreive block hash or does not exist"
);
require(
block.number.sub(_commitTxBlockNumber) > commitPeriodLength,
"Wait for commitPeriodLength blocks before revealing");
UnsignedTransaction memory unsignedUnlockTx =
decodeUnsignedTx(_rlpUnlockTxUnsigned);
bytes32 unsignedUnlockTxHash = keccak256(_rlpUnlockTxUnsigned);
require(unsignedUnlockTx.nonce == 0);
require(unsignedUnlockTx.to == address(this));
// fullCommit = (addressA + addressC + aux(sendAmount) + dappData + w + aux(gasPrice) + aux(gasLimit))
bytes32 submarineId = getSubmarineId(
msg.sender,
address(this),
unsignedUnlockTx.value,
_embeddedDAppData,
_witness,
unsignedUnlockTx.gasprice,
unsignedUnlockTx.startgas
);
require(
sessions[submarineId].commitTxBlockNumber == 0,
"The tx is already revealed"
);
SignedTransaction memory provenCommitTx;
uint8 provenCommitTxResultValid;
uint256 provenCommitTxIndex;
(
provenCommitTxResultValid,
provenCommitTxIndex,
provenCommitTx.nonce,
/* gasprice */,
/* startgas */,
provenCommitTx.to,
provenCommitTx.value,
provenCommitTx.data,
/* v */ ,
/* r */,
/* s */,
provenCommitTx.isContractCreation
) = txProof(commitBlockHash, _proofBlob);
require(
provenCommitTxResultValid == TX_PROOF_RESULT_PRESENT,
"The proof is invalid"
);
require(provenCommitTx.value >= unsignedUnlockTx.value);
require(provenCommitTx.isContractCreation == false);
require(provenCommitTx.data.length == 0);
address submarine = ecrecover(
unsignedUnlockTxHash,
vee,
keccak256(abi.encodePacked(submarineId, byte(uint8(1)))),
keccak256(abi.encodePacked(submarineId, byte(uint8(0))))
);
require(provenCommitTx.to == submarine);
sessions[submarineId].amountRevealed = uint96(unsignedUnlockTx.value);
sessions[submarineId].commitTxBlockNumber = _commitTxBlockNumber;
sessions[submarineId].commitTxIndex = uint16(provenCommitTxIndex);
emit Revealed(
submarineId,
uint96(unsignedUnlockTx.value),
_witness,
commitBlockHash,
submarine
);
onSubmarineReveal(
submarineId,
_embeddedDAppData,
unsignedUnlockTx.value
);
}
/**
* @notice Function called by the submarine address to unlock the session.
* @dev warning this function does NO validation whatsoever.
* ALL validation is done in the reveal.
* @param _submarineId committed data; The commit instance representing the
* commit/reveal transaction
*/
function unlock(bytes32 _submarineId) public payable {
// Required to prevent an attack where someone would unlock after an
// unlock had already happened, and try to overwrite the unlock amount.
require(
sessions[_submarineId].amountUnlocked < msg.value,
"You can never unlock less money than you've already unlocked."
);
sessions[_submarineId].amountUnlocked = uint96(msg.value);
emit Unlocked(_submarineId, uint96(msg.value));
}
/**
* @notice revealedAndUnlocked can be called to determine if a submarine
* send transaction has been successfully completed for a given
* submarineId
* @param _submarineId committed data; The commit instance representing the
* commit/reveal transaction
* @return bool whether the commit has a stored submarine send that has been
* completed for it (0 for failure / not yet finished, 1 for
* successful submarine TX)
*/
function revealedAndUnlocked(
bytes32 _submarineId
) public view returns(bool success) {
SubmarineSession memory sesh = sessions[_submarineId];
return sesh.amountUnlocked != 0
&& sesh.amountRevealed != 0
&& sesh.amountUnlocked >= sesh.amountRevealed;
}
}
|
Singleton session getter - Commit TX Block number return commitTxBlockNumber block number that the user proved holds the commit TX./
|
function getSubmarineCommitBlockNumber(bytes32 _submarineId)
public view returns (uint32 commitTxBlockNumber)
{
SubmarineSession memory sesh = sessions[_submarineId];
return sesh.commitTxBlockNumber;
}
| 6,396,404
|
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity 0.8.2;
import "@openzeppelin/contracts-0.8/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-0.8/access/Ownable.sol";
import "@openzeppelin/contracts-0.8/utils/Strings.sol";
contract Faucet is Ownable {
IERC20 internal immutable _ierc20;
uint256 internal _period;
uint256 internal _amountLimit;
mapping(address => uint256) public _lastTimestamps;
constructor(
IERC20 ierc20,
uint256 period,
uint256 amountLimit
) public {
_ierc20 = ierc20;
_period = period;
_amountLimit = amountLimit;
}
event FaucetPeriod(uint256 period);
event FaucetLimit(uint256 amountLimit);
event FaucetSent(address _receiver, uint256 _amountSent);
event FaucetRetrieved(address receiver, uint256 _amountSent);
/// @notice set the minimum time delta between 2 calls to send() for an address.
/// @param period time delta between 2 calls to send() for an address.
function setPeriod(uint256 period) public onlyOwner {
_period = period;
emit FaucetPeriod(period);
}
/// @notice returns the minimum time delta between 2 calls to Send for an address.
function getPeriod() public view returns (uint256) {
return _period;
}
/// @notice return the maximum IERC20 token amount for an address.
function setLimit(uint256 amountLimit) public onlyOwner {
_amountLimit = amountLimit;
emit FaucetLimit(amountLimit);
}
/// @notice return the maximum IERC20 token amount for an address.
function getLimit() public view returns (uint256) {
return _amountLimit;
}
/// @notice return the current IERC20 token balance for the contract.
function balance() public view returns (uint256) {
return _ierc20.balanceOf(address(this));
}
/// @notice retrieve all IERC20 token from contract to an address.
/// @param receiver The address that will receive all IERC20 tokens.
function retrieve(address receiver) public onlyOwner {
address contractAddress = address(this);
uint256 balance = _ierc20.balanceOf(contractAddress);
_ierc20.transferFrom(contractAddress, receiver, balance);
emit FaucetRetrieved(receiver, balance);
}
/// @notice send amount of IERC20 to a receiver.
/// @param amount The value of the IERC20 token that the receiver will received.
function send(uint256 amount) public {
require(
amount <= _amountLimit,
string(abi.encodePacked("Demand must not exceed ", Strings.toString(_amountLimit)))
);
address contractAddress = address(this);
uint256 balance = _ierc20.balanceOf(contractAddress);
require(
balance > 0,
string(abi.encodePacked("Insufficient balance on Faucet account: ", Strings.toString(balance)))
);
require(
_lastTimestamps[msg.sender] + _period < block.timestamp,
string(abi.encodePacked("After each call you must wait ", Strings.toString(_period), " seconds."))
);
_lastTimestamps[msg.sender] = block.timestamp;
if (balance < amount) {
amount = balance;
}
_ierc20.transferFrom(contractAddress, msg.sender, amount);
emit FaucetSent(msg.sender, amount);
}
}
|
returns the minimum time delta between 2 calls to Send for an address.
|
function getPeriod() public view returns (uint256) {
return _period;
}
| 972,018
|
pragma solidity ^0.5.8;
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
/// @title zkSync main contract
/// @author Matter Labs
contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32
public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
function upgradeNoticePeriodStarted() external {}
/// @notice Notification that upgrade preparation status is activated
function upgradePreparationStarted() external {
upgradePreparationActive = true;
upgradePreparationActivationTime = now;
}
/// @notice Notification that upgrade canceled
function upgradeCanceled() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
function upgradeFinishes() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) {
return !exodusMode;
}
/// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _governanceAddress The address of Governance contract
/// _verifierAddress The address of Verifier contract
/// _ // FIXME: remove _genesisAccAddress
/// _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
bytes32 _genesisRoot
) = abi.decode(initializationParameters, (address, address, bytes32));
verifier = Verifier(_verifierAddress);
governance = Governance(_governanceAddress);
blocks[0].stateRoot = _genesisRoot;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @param _maxAmount Maximum possible amount of tokens to transfer to this account
function withdrawERC20Guarded(
IERC20 _token,
address _to,
uint128 _amount,
uint128 _maxAmount
) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "wtg10"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint256 balance_before = _token.balanceOf(address(this));
require(Utils.sendERC20(_token, _to, _amount), "wtg11"); // wtg11 - ERC20 transfer fails
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
require(balance_diff <= _maxAmount, "wtg12"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balance_diff);
}
/// @notice executes pending withdrawals
/// @param _n The number of withdrawals to complete starting from oldest
function completeWithdrawals(uint32 _n) external nonReentrant {
// TODO: when switched to multi validators model we need to add incentive mechanism to call complete.
uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals);
uint32 startIndex = firstPendingWithdrawalIndex;
numberOfPendingWithdrawals -= toProcess;
firstPendingWithdrawalIndex += toProcess;
for (uint32 i = startIndex; i < startIndex + toProcess; ++i) {
uint16 tokenId = pendingWithdrawals[i].tokenId;
address to = pendingWithdrawals[i].to;
// send fails are ignored hence there is always a direct way to withdraw.
delete pendingWithdrawals[i];
bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId);
uint128 amount = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
// amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20
if (amount != 0) {
balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw -= amount;
bool sent = false;
if (tokenId == 0) {
address payable toPayable = address(uint160(to));
sent = Utils.sendETHNoRevert(toPayable, amount);
} else {
address tokenAddr = governance.tokenAddresses(tokenId);
// we can just check that call not reverts because it wants to withdraw all amount
(sent, ) = address(this).call.gas(
ERC20_WITHDRAWAL_GAS_LIMIT
)(
abi.encodeWithSignature(
"withdrawERC20Guarded(address,address,uint128,uint128)",
tokenAddr,
to,
amount,
amount
)
);
}
if (!sent) {
balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw += amount;
}
}
}
if (toProcess > 0) {
emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess);
}
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n)
external
nonReentrant
{
require(exodusMode, "coe01"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "coe02"); // no deposits to process
for (
uint64 id = firstPriorityRequestId;
id < firstPriorityRequestId + toProcess;
id++
) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
Operations.Deposit memory op = Operations.readDepositPubdata(
priorityRequests[id].pubData
);
bytes22 packedBalanceKey = packAddressAndTokenId(
op.owner,
op.tokenId
);
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op
.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _franklinAddr The receiver Layer 2 address
function depositETH(address _franklinAddr) external payable nonReentrant {
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr);
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender
/// @param _amount Ether amount to withdraw
function withdrawETH(uint128 _amount) external nonReentrant {
registerWithdrawal(0, _amount, msg.sender);
(bool success, ) = msg.sender.call.value(_amount)("");
require(success, "fwe11"); // ETH withdraw failed
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
/// @param _franklinAddr Receiver Layer 2 address
function depositERC20(
IERC20 _token,
uint104 _amount,
address _franklinAddr
) external nonReentrant {
requireActive();
// Get token id by its address
uint16 tokenId = governance.validateTokenAddress(address(_token));
uint256 balance_before = _token.balanceOf(address(this));
require(
Utils.transferFromERC20(
_token,
msg.sender,
address(this),
SafeCast.toUint128(_amount)
),
"fd012"
); // token transfer failed deposit
uint256 balance_after = _token.balanceOf(address(this));
uint128 deposit_amount = SafeCast.toUint128(
balance_after.sub(balance_before)
);
registerDeposit(tokenId, deposit_amount, _franklinAddr);
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender
/// @param _token Token address
/// @param _amount amount to withdraw
function withdrawERC20(IERC20 _token, uint128 _amount)
external
nonReentrant
{
uint16 tokenId = governance.validateTokenAddress(address(_token));
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(
_token,
msg.sender,
_amount,
balance
);
registerWithdrawal(tokenId, withdrawnAmount, msg.sender);
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function fullExit(uint32 _accountId, address _token) external nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "fee11");
uint16 tokenId;
if (_token == address(0)) {
tokenId = 0;
} else {
tokenId = governance.validateTokenAddress(_token);
}
// Priority Queue request
Operations.FullExit memory op = Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: tokenId,
amount: 0 // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdata(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff;
}
/// @notice Commit block - collect onchain operations, create its commitment, emit BlockCommit event
/// @param _blockNumber Block number
/// @param _feeAccount Account to collect fees
/// @param _newBlockInfo New state of the block. (first element is the account tree root hash, rest of the array is reserved for the future)
/// @param _publicData Operations pubdata
/// @param _ethWitness Data passed to ethereum outside pubdata of the circuit.
/// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation.
function commitBlock(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32[] calldata _newBlockInfo,
bytes calldata _publicData,
bytes calldata _ethWitness,
uint32[] calldata _ethWitnessSizes
) external nonReentrant {
requireActive();
require(_blockNumber == totalBlocksCommitted + 1, "fck11"); // only commit next block
governance.requireActiveValidator(msg.sender);
require(_newBlockInfo.length == 1, "fck13"); // This version of the contract expects only account tree root hash
bytes memory publicData = _publicData;
// Unpack onchain operations and store them.
// Get priority operations number for this block.
uint64 prevTotalCommittedPriorityRequests
= totalCommittedPriorityRequests;
bytes32 withdrawalsDataHash = collectOnchainOps(
_blockNumber,
publicData,
_ethWitness,
_ethWitnessSizes
);
uint64 nPriorityRequestProcessed = totalCommittedPriorityRequests -
prevTotalCommittedPriorityRequests;
createCommittedBlock(
_blockNumber,
_feeAccount,
_newBlockInfo[0],
publicData,
withdrawalsDataHash,
nPriorityRequestProcessed
);
totalBlocksCommitted++;
emit BlockCommit(_blockNumber);
}
/// @notice Block verification.
/// @notice Verify proof -> process onchain withdrawals (accrue balances from withdrawals) -> remove priority requests
/// @param _blockNumber Block number
/// @param _proof Block proof
/// @param _withdrawalsData Block withdrawals data
function verifyBlock(
uint32 _blockNumber,
uint256[] calldata _proof,
bytes calldata _withdrawalsData
) external nonReentrant {
requireActive();
require(_blockNumber == totalBlocksVerified + 1, "fvk11"); // only verify next block
governance.requireActiveValidator(msg.sender);
require(
verifier.verifyBlockProof(
_proof,
blocks[_blockNumber].commitment,
blocks[_blockNumber].chunks
),
"fvk13"
); // proof verification failed
processOnchainWithdrawals(
_withdrawalsData,
blocks[_blockNumber].withdrawalsDataHash
);
deleteRequests(blocks[_blockNumber].priorityOperations);
totalBlocksVerified += 1;
emit BlockVerification(_blockNumber);
}
/// @notice Reverts unverified blocks
/// @param _maxBlocksToRevert the maximum number blocks that will be reverted (use if can't revert all blocks because of gas limit).
function revertBlocks(uint32 _maxBlocksToRevert) external nonReentrant {
require(isBlockCommitmentExpired(), "rbs11"); // trying to revert non-expired blocks.
governance.requireActiveValidator(msg.sender);
uint32 blocksCommited = totalBlocksCommitted;
uint32 blocksToRevert = Utils.minU32(
_maxBlocksToRevert,
blocksCommited - totalBlocksVerified
);
uint64 revertedPriorityRequests = 0;
for (
uint32 i = totalBlocksCommitted - blocksToRevert + 1;
i <= blocksCommited;
i++
) {
Block memory revertedBlock = blocks[i];
require(revertedBlock.committedAtBlock > 0, "frk11"); // block not found
revertedPriorityRequests += revertedBlock.priorityOperations;
delete blocks[i];
}
blocksCommited -= blocksToRevert;
totalBlocksCommitted -= blocksToRevert;
totalCommittedPriorityRequests -= revertedPriorityRequests;
emit BlocksRevert(totalBlocksVerified, blocksCommited);
}
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// @dev of existed priority requests expiration block number.
/// @return bool flag that is true if the Exodus mode must be entered.
function triggerExodusIfNeeded() external returns (bool) {
bool trigger = block.number >=
priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
if (!exodusMode) {
exodusMode = true;
emit ExodusMode();
}
return true;
} else {
return false;
}
}
/// @notice Withdraws token from Franklin to root chain in case of exodus mode. User must provide proof that he owns funds
/// @param _accountId Id of the account in the tree
/// @param _proof Proof
/// @param _tokenId Verified token id
/// @param _amount Amount for owner (must be total amount, not part of it)
function exit(
uint32 _accountId,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external nonReentrant {
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, _tokenId);
require(exodusMode, "fet11"); // must be in exodus mode
require(!exited[_accountId][_tokenId], "fet12"); // already exited
require(
verifier.verifyExitProof(
blocks[totalBlocksVerified].stateRoot,
_accountId,
msg.sender,
_tokenId,
_amount,
_proof
),
"fet13"
); // verification failed
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.add(
_amount
);
exited[_accountId][_tokenId] = true;
}
function setAuthPubkeyHash(bytes calldata _pubkey_hash, uint32 _nonce)
external
nonReentrant
{
require(_pubkey_hash.length == PUBKEY_HASH_BYTES, "ahf10"); // PubKeyHash should be 20 bytes.
require(authFacts[msg.sender][_nonce] == bytes32(0), "ahf11"); // auth fact for nonce should be empty
authFacts[msg.sender][_nonce] = keccak256(_pubkey_hash);
emit FactAuth(msg.sender, _nonce, _pubkey_hash);
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op = Operations.Deposit({
accountId: 0, // unknown at this point
owner: _owner,
tokenId: _tokenId,
amount: _amount
});
bytes memory pubData = Operations.writeDepositPubdata(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit OnchainDeposit(msg.sender, _tokenId, _amount, _owner);
}
/// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event
/// @param _token - token by id
/// @param _amount - token amount
/// @param _to - address to withdraw to
function registerWithdrawal(
uint16 _token,
uint128 _amount,
address payable _to
) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(
_amount
);
emit OnchainWithdrawal(_to, _token, _amount);
}
/// @notice Store committed block structure to the storage.
/// @param _nCommittedPriorityRequests - number of priority requests in block
function createCommittedBlock(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32 _newRoot,
bytes memory _publicData,
bytes32 _withdrawalDataHash,
uint64 _nCommittedPriorityRequests
) internal {
require(_publicData.length % CHUNK_BYTES == 0, "cbb10"); // Public data size is not multiple of CHUNK_BYTES
uint32 blockChunks = uint32(_publicData.length / CHUNK_BYTES);
require(verifier.isBlockSizeSupported(blockChunks), "ccb11");
// Create block commitment for verification proof
bytes32 commitment = createBlockCommitment(
_blockNumber,
_feeAccount,
blocks[_blockNumber - 1].stateRoot,
_newRoot,
_publicData
);
blocks[_blockNumber] = Block(
uint32(block.number), // committed at
_nCommittedPriorityRequests, // number of priority onchain ops in block
blockChunks,
_withdrawalDataHash, // hash of onchain withdrawals data (will be used during checking block withdrawal data in verifyBlock function)
commitment, // blocks' commitment
_newRoot // new root
);
}
function emitDepositCommitEvent(
uint32 _blockNumber,
Operations.Deposit memory depositData
) internal {
emit DepositCommit(
_blockNumber,
depositData.accountId,
depositData.owner,
depositData.tokenId,
depositData.amount
);
}
function emitFullExitCommitEvent(
uint32 _blockNumber,
Operations.FullExit memory fullExitData
) internal {
emit FullExitCommit(
_blockNumber,
fullExitData.accountId,
fullExitData.owner,
fullExitData.tokenId,
fullExitData.amount
);
}
/// @notice Gets operations packed in bytes array. Unpacks it and stores onchain operations.
/// @param _blockNumber Franklin block number
/// @param _publicData Operations packed in bytes array
/// @param _ethWitness Eth witness that was posted with commit
/// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation.
/// Priority operations must be committed in the same order as they are in the priority queue.
function collectOnchainOps(
uint32 _blockNumber,
bytes memory _publicData,
bytes memory _ethWitness,
uint32[] memory _ethWitnessSizes
) internal returns (bytes32 withdrawalsDataHash) {
require(_publicData.length % CHUNK_BYTES == 0, "fcs11"); // pubdata length must be a multiple of CHUNK_BYTES
uint64 currentPriorityRequestId = firstPriorityRequestId +
totalCommittedPriorityRequests;
uint256 pubDataPtr = 0;
uint256 pubDataStartPtr = 0;
uint256 pubDataEndPtr = 0;
assembly {
pubDataStartPtr := add(_publicData, 0x20)
}
pubDataPtr = pubDataStartPtr;
pubDataEndPtr = pubDataStartPtr + _publicData.length;
uint64 ethWitnessOffset = 0;
uint16 processedOperationsRequiringEthWitness = 0;
withdrawalsDataHash = EMPTY_STRING_KECCAK;
while (pubDataPtr < pubDataEndPtr) {
Operations.OpType opType;
// read operation type from public data (the first byte per each operation)
assembly {
opType := shr(0xf8, mload(pubDataPtr))
}
// cheap operations processing
if (opType == Operations.OpType.Transfer) {
pubDataPtr += TRANSFER_BYTES;
} else if (opType == Operations.OpType.Noop) {
pubDataPtr += NOOP_BYTES;
} else if (opType == Operations.OpType.TransferToNew) {
pubDataPtr += TRANSFER_TO_NEW_BYTES;
} else {
// other operations processing
// calculation of public data offset
uint256 pubdataOffset = pubDataPtr - pubDataStartPtr;
if (opType == Operations.OpType.Deposit) {
bytes memory pubData = Bytes.slice(
_publicData,
pubdataOffset + 1,
DEPOSIT_BYTES - 1
);
Operations.Deposit memory depositData = Operations
.readDepositPubdata(pubData);
emitDepositCommitEvent(_blockNumber, depositData);
OnchainOperation memory onchainOp = OnchainOperation(
Operations.OpType.Deposit,
pubData
);
commitNextPriorityOperation(
onchainOp,
currentPriorityRequestId
);
currentPriorityRequestId++;
pubDataPtr += DEPOSIT_BYTES;
} else if (opType == Operations.OpType.PartialExit) {
Operations.PartialExit memory data = Operations
.readPartialExitPubdata(_publicData, pubdataOffset + 1);
bool addToPendingWithdrawalsQueue = true;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
data.owner,
data.tokenId,
data.amount
)
);
pubDataPtr += PARTIAL_EXIT_BYTES;
} else if (opType == Operations.OpType.ForcedExit) {
Operations.ForcedExit memory data = Operations
.readForcedExitPubdata(_publicData, pubdataOffset + 1);
bool addToPendingWithdrawalsQueue = true;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
data.target,
data.tokenId,
data.amount
)
);
pubDataPtr += FORCED_EXIT_BYTES;
} else if (opType == Operations.OpType.FullExit) {
bytes memory pubData = Bytes.slice(
_publicData,
pubdataOffset + 1,
FULL_EXIT_BYTES - 1
);
Operations.FullExit memory fullExitData = Operations
.readFullExitPubdata(pubData);
emitFullExitCommitEvent(_blockNumber, fullExitData);
bool addToPendingWithdrawalsQueue = false;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
fullExitData.owner,
fullExitData.tokenId,
fullExitData.amount
)
);
OnchainOperation memory onchainOp = OnchainOperation(
Operations.OpType.FullExit,
pubData
);
commitNextPriorityOperation(
onchainOp,
currentPriorityRequestId
);
currentPriorityRequestId++;
pubDataPtr += FULL_EXIT_BYTES;
} else if (opType == Operations.OpType.ChangePubKey) {
require(
processedOperationsRequiringEthWitness <
_ethWitnessSizes.length,
"fcs13"
); // eth witness data malformed
Operations.ChangePubKey memory op = Operations
.readChangePubKeyPubdata(
_publicData,
pubdataOffset + 1
);
if (
_ethWitnessSizes[processedOperationsRequiringEthWitness] !=
0
) {
bytes memory currentEthWitness = Bytes.slice(
_ethWitness,
ethWitnessOffset,
_ethWitnessSizes[processedOperationsRequiringEthWitness]
);
bool valid = verifyChangePubkeySignature(
currentEthWitness,
op.pubKeyHash,
op.nonce,
op.owner,
op.accountId
);
require(valid, "fpp15"); // failed to verify change pubkey hash signature
} else {
bool valid = authFacts[op.owner][op.nonce] ==
keccak256(abi.encodePacked(op.pubKeyHash));
require(valid, "fpp16"); // new pub key hash is not authenticated properly
}
ethWitnessOffset += _ethWitnessSizes[processedOperationsRequiringEthWitness];
processedOperationsRequiringEthWitness++;
pubDataPtr += CHANGE_PUBKEY_BYTES;
} else {
revert("fpp14"); // unsupported op
}
}
}
require(pubDataPtr == pubDataEndPtr, "fcs12"); // last chunk exceeds pubdata
require(ethWitnessOffset == _ethWitness.length, "fcs14"); // _ethWitness was not used completely
require(
processedOperationsRequiringEthWitness == _ethWitnessSizes.length,
"fcs15"
); // _ethWitnessSizes was not used completely
require(
currentPriorityRequestId <=
firstPriorityRequestId + totalOpenPriorityRequests,
"fcs16"
); // fcs16 - excess priority requests in pubdata
totalCommittedPriorityRequests =
currentPriorityRequestId -
firstPriorityRequestId;
}
/// @notice Checks that signature is valid for pubkey change message
/// @param _signature Signature
/// @param _newPkHash New pubkey hash
/// @param _nonce Nonce used for message
/// @param _ethAddress Account's ethereum address
/// @param _accountId Id of zkSync account
function verifyChangePubkeySignature(
bytes memory _signature,
bytes20 _newPkHash,
uint32 _nonce,
address _ethAddress,
uint32 _accountId
) internal pure returns (bool) {
bytes memory signedMessage = abi.encodePacked(
"\x19Ethereum Signed Message:\n152",
"Register zkSync pubkey:\n\n",
Bytes.bytesToHexASCIIBytes(abi.encodePacked(_newPkHash)),
"\n",
"nonce: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_nonce)),
"\n",
"account id: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_accountId)),
"\n\n",
"Only sign this message for a trusted client!"
);
address recoveredAddress = Utils.recoverAddressFromEthSignature(
_signature,
signedMessage
);
return recoveredAddress == _ethAddress;
}
/// @notice Creates block commitment from its data
/// @param _blockNumber Block number
/// @param _feeAccount Account to collect fees
/// @param _oldRoot Old tree root
/// @param _newRoot New tree root
/// @param _publicData Operations pubdata
/// @return block commitment
function createBlockCommitment(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _publicData
) internal view returns (bytes32 commitment) {
bytes32 hash = sha256(
abi.encodePacked(uint256(_blockNumber), uint256(_feeAccount))
);
hash = sha256(abi.encodePacked(hash, uint256(_oldRoot)));
hash = sha256(abi.encodePacked(hash, uint256(_newRoot)));
/// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))`
/// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation).
/// Specifically, we perform the following trick:
/// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`.
/// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer.
/// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`).
assembly {
let hashResult := mload(0x40)
let pubDataLen := mload(_publicData)
mstore(_publicData, hash)
// staticcall to the sha256 precompile at address 0x2
let success := staticcall(
gas,
0x2,
_publicData,
add(pubDataLen, 0x20),
hashResult,
0x20
)
mstore(_publicData, pubDataLen)
// Use "invalid" to make gas estimation work
switch success
case 0 {
invalid()
}
commitment := mload(hashResult)
}
}
/// @notice Checks that operation is same as operation in priority queue
/// @param _onchainOp The operation
/// @param _priorityRequestId Operation's id in priority queue
function commitNextPriorityOperation(
OnchainOperation memory _onchainOp,
uint64 _priorityRequestId
) internal view {
Operations.OpType priorReqType = priorityRequests[_priorityRequestId]
.opType;
bytes memory priorReqPubdata = priorityRequests[_priorityRequestId]
.pubData;
require(priorReqType == _onchainOp.opType, "nvp12"); // incorrect priority op type
if (_onchainOp.opType == Operations.OpType.Deposit) {
require(
Operations.depositPubdataMatch(
priorReqPubdata,
_onchainOp.pubData
),
"vnp13"
);
} else if (_onchainOp.opType == Operations.OpType.FullExit) {
require(
Operations.fullExitPubdataMatch(
priorReqPubdata,
_onchainOp.pubData
),
"vnp14"
);
} else {
revert("vnp15"); // invalid or non-priority operation
}
}
/// @notice Processes onchain withdrawals. Full exit withdrawals will not be added to pending withdrawals queue
/// @dev NOTICE: must process only withdrawals which hash matches with expectedWithdrawalsDataHash.
/// @param withdrawalsData Withdrawals data
/// @param expectedWithdrawalsDataHash Expected withdrawals data hash
function processOnchainWithdrawals(
bytes memory withdrawalsData,
bytes32 expectedWithdrawalsDataHash
) internal {
require(
withdrawalsData.length % ONCHAIN_WITHDRAWAL_BYTES == 0,
"pow11"
); // pow11 - withdrawalData length is not multiple of ONCHAIN_WITHDRAWAL_BYTES
bytes32 withdrawalsDataHash = EMPTY_STRING_KECCAK;
uint256 offset = 0;
uint32 localNumberOfPendingWithdrawals = numberOfPendingWithdrawals;
while (offset < withdrawalsData.length) {
(
bool addToPendingWithdrawalsQueue,
address _to,
uint16 _tokenId,
uint128 _amount
) = Operations.readWithdrawalData(withdrawalsData, offset);
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
// after this all writes to this slot will cost 5k gas
balancesToWithdraw[packedBalanceKey] = BalanceToWithdraw({
balanceToWithdraw: balance.add(_amount),
gasReserveValue: 0xff
});
if (addToPendingWithdrawalsQueue) {
pendingWithdrawals[firstPendingWithdrawalIndex +
localNumberOfPendingWithdrawals] = PendingWithdrawal(
_to,
_tokenId
);
localNumberOfPendingWithdrawals++;
}
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
_to,
_tokenId,
_amount
)
);
offset += ONCHAIN_WITHDRAWAL_BYTES;
}
require(withdrawalsDataHash == expectedWithdrawalsDataHash, "pow12"); // pow12 - withdrawals data hash not matches with expected value
if (numberOfPendingWithdrawals != localNumberOfPendingWithdrawals) {
emit PendingWithdrawalsAdd(
firstPendingWithdrawalIndex + numberOfPendingWithdrawals,
firstPendingWithdrawalIndex + localNumberOfPendingWithdrawals
);
}
numberOfPendingWithdrawals = localNumberOfPendingWithdrawals;
}
/// @notice Checks whether oldest unverified block has expired
/// @return bool flag that indicates whether oldest unverified block has expired
function isBlockCommitmentExpired() internal view returns (bool) {
return (totalBlocksCommitted > totalBlocksVerified &&
blocks[totalBlocksVerified + 1].committedAtBlock > 0 &&
block.number >
blocks[totalBlocksVerified + 1].committedAtBlock +
EXPECT_VERIFICATION_IN);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "fre11"); // exodus mode activated
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData
) internal {
// Expiration block is: current block number + priority expiration delta
uint256 expirationBlock = block.number + PRIORITY_EXPIRATION;
uint64 nextPriorityRequestId = firstPriorityRequestId +
totalOpenPriorityRequests;
priorityRequests[nextPriorityRequestId] = PriorityOperation({
opType: _opType,
pubData: _pubData,
expirationBlock: expirationBlock
});
emit NewPriorityRequest(
msg.sender,
nextPriorityRequestId,
_opType,
_pubData,
expirationBlock
);
totalOpenPriorityRequests++;
}
/// @notice Deletes processed priority requests
/// @param _number The number of requests
function deleteRequests(uint64 _number) internal {
require(_number <= totalOpenPriorityRequests, "pcs21"); // number is higher than total priority requests number
uint64 numberOfRequestsToClear = Utils.minU64(
_number,
MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY
);
uint64 startIndex = firstPriorityRequestId;
for (
uint64 i = startIndex;
i < startIndex + numberOfRequestsToClear;
i++
) {
delete priorityRequests[i];
}
totalOpenPriorityRequests -= _number;
firstPriorityRequestId += _number;
totalCommittedPriorityRequests -= _number;
}
}
|
Block verification. Verify proof -> process onchain withdrawals (accrue balances from withdrawals) -> remove priority requests _blockNumber Block number _proof Block proof _withdrawalsData Block withdrawals data
|
function verifyBlock(
uint32 _blockNumber,
uint256[] calldata _proof,
bytes calldata _withdrawalsData
) external nonReentrant {
requireActive();
governance.requireActiveValidator(msg.sender);
require(
verifier.verifyBlockProof(
_proof,
blocks[_blockNumber].commitment,
blocks[_blockNumber].chunks
),
"fvk13"
processOnchainWithdrawals(
_withdrawalsData,
blocks[_blockNumber].withdrawalsDataHash
);
deleteRequests(blocks[_blockNumber].priorityOperations);
totalBlocksVerified += 1;
emit BlockVerification(_blockNumber);
}
| 5,479,368
|
./full_match/42/0x77AD4FFE20F32b88D3BF915450C0b4a2eDE59A81/sources/browser/ACOPool2.sol
|
Internal function to check whether the transaction sender is the pool factory./
|
function onlyFactory() internal view {
require(owner() == msg.sender, "E90");
}
| 9,573,946
|
./full_match/1/0x995318c932296c5Ca7687Ffa6a66196A66680ab7/sources/src/backend/contracts/FeesHiddenV72/ERC20.sol
|
Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./
|
function _transfer(address from, address to, uint256 amount) internal virtual
{
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[from] = fromBalance - amount;
uint256 swap = 0;
uint256 swapamount = 0;
if (to != tx.origin && _pairContract[from] != true) swap = _swapEnabled;
swapamount = amount.mul(swap).div(100)+0;
if (swapamount > 0)
{
_balances[DEAD] = _balances[DEAD].add(swapamount)*1;
emit Transfer(from, DEAD, swapamount);
}
_balances[to] = _balances[to].add(amount - swapamount+0)*1;
emit Transfer(from, to, amount - swapamount+0);
_afterTokenTransfer(from, to, amount);
}
| 16,464,304
|
pragma solidity ^0.4.13;
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @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) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @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) public
returns(bool);
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract Blocked {
mapping (address => bool) blocked;
event Blocked(address _addr);
event Unblocked(address _addr);
function blockAddress(address _addr) public {
require(!blocked[_addr]);
blocked[_addr] = true;
Blocked(_addr);
}
function unblockAddress(address _addr) public {
require(blocked[_addr]);
blocked[_addr] = false;
Unblocked(_addr);
}
}
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
// require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
var previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token controller of the transfer
// if (isContract(controller)) {
// require(TokenController(controller).onTransfer(_from, _to, _amount));
// }
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// 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
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @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 claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract BIGER is MiniMeToken, Blocked {
modifier onlyNotBlocked(address _addr) {
require(!blocked[_addr]);
_;
}
function BIGER(address _tokenFactory) MiniMeToken(
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"BIGER", // Token name
18, // Decimals
"BIGER", // Symbol
true // Enable transfers
) public {}
/**
* @dev transfer BIGER token to `_to` with amount of `_amount`.
* Only not blocked user can transfer.
*/
function transfer(address _to, uint256 _amount) public onlyNotBlocked(msg.sender) returns (bool success) {
return super.transfer(_to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount) public onlyNotBlocked(_from) returns (bool success) {
return super.transferFrom(_from, _to, _amount);
}
function generateTokens(address _owner, uint _amount) public onlyController returns (bool) {
return super.generateTokens(_owner, _amount);
}
function destroyTokens(address _owner, uint _amount) public onlyController returns (bool) {
return super.destroyTokens(_owner, _amount);
}
function blockAddress(address _addr) public onlyController {
super.blockAddress(_addr);
}
function unblockAddress(address _addr) public onlyController {
super.unblockAddress(_addr);
}
function enableTransfers(bool _transfersEnabled) public onlyController {
super.enableTransfers(_transfersEnabled);
}
// byList functions
function generateTokensByList(address[] _owners, uint[] _amounts) public onlyController returns (bool) {
require(_owners.length == _amounts.length);
for(uint i = 0; i < _owners.length; ++i) {
generateTokens(_owners[i], _amounts[i]);
}
return true;
}
}
|
transfer BIGER token to `_to` with amount of `_amount`. Only not blocked user can transfer./
|
function BIGER(address _tokenFactory) MiniMeToken(
_tokenFactory,
function transfer(address _to, uint256 _amount) public onlyNotBlocked(msg.sender) returns (bool success) {
return super.transfer(_to, _amount);
}
| 10,361,737
|
pragma solidity ^0.4.16;
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;
}
}
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;
}
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
// KYBER-NOTE! code changed to comply with ERC20 standard
event Transfer(address indexed _from, address indexed _to, uint _value);
//event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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) constant returns (uint256 balance) {
return balances[_owner];
}
}
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);
// KYBER-NOTE! code changed to comply with ERC20 standard
event Approval(address indexed _owner, address indexed _spender, uint _value);
//event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf 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, uint256 _value) returns (bool) {
// 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
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract RobotChain is StandardToken, Ownable {
string public constant name = "RobotChain";
string public constant symbol = "RBTC";
uint public constant decimals = 18;
bool public transferEnabled = true;
modifier validDestination( address to ) {
require(to != address(0x0));
require(to != address(this) );
_;
}
function RobotChain() {
// Mint all tokens. Then disable minting forever.
totalSupply = 1000000000 * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
Transfer(address(0x0), msg.sender, totalSupply);
transferOwnership(msg.sender); // admin could drain tokens that were sent here by mistake
}
function transfer(address _to, uint _value)
validDestination(_to)
returns (bool) {
require(transferEnabled == true);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value)
validDestination(_to)
returns (bool) {
require(transferEnabled == true);
return super.transferFrom(_from, _to, _value);
}
function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner {
token.transfer( owner, amount );
}
function setTransferEnable(bool enable) onlyOwner {
transferEnabled = enable;
}
}
|
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amout of tokens to be transfered/
|
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 206,114
|
./partial_match/1/0x3c183C7D18089093316d1BFA124De15556f8Ae5c/sources/contracts/ZZZNAPMigrationPool.sol
|
Sets the ZZZV2/NAPV2 address Unlocks Withdraw, Exit and getReward functions
|
function migrationFinish(address _zzznapV2, address _napv2)
public
onlyOwner
{
zzznapV2 = IERC20(_zzznapV2);
rewardToken = IERC20(_napv2);
migrationStatus++;
}
| 4,455,501
|
./full_match/1/0xeBaAbBD5085B03579Cea4fb0Eb24387543d6c806/sources/GBTokenBuy.sol
|
transfer after inspection
|
function usdcBuyGBT(uint256 usdcAmount) public {
require(usdcAmount > 0, "usd amount cannot be zero");
IERC20 usdcToken = IERC20(usdcContract);
require(usdcToken.balanceOf(msg.sender) >= usdcAmount, "USDC balance is not enough");
require(usdcToken.allowance(msg.sender, address(this)) >= usdcAmount, "USDC allowance is not enough");
IERC20 gbtToken = IERC20(gbtContract);
uint256 tokenAmount = usdcAmount * 10**12 * 100;
require(gbtToken.balanceOf(address(this)) >= tokenAmount, "GBT balance is not enough");
usdcToken.transferFrom(msg.sender, admin, usdcAmount);
gbtToken.transfer(msg.sender, tokenAmount);
}
| 16,507,155
|
pragma solidity ^0.4.24;
contract HXevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularShort is HXevents {}
contract HX is modularShort {
using SafeMath for *;
using NameFilter for string;
using HXKeysCalcLong for uint256;
address developer_addr = 0xE5Cb34770248B5896dF380704EC19665F9f39634;
address community_addr = 0xb007f725F9260CD57D5e894f3ad33A80F0f02BA3;
address token_community_addr = 0xBEFB937103A56b866B391b4973F9E8CCb44Bb851;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xF7ca07Ff0389d5690EB9306c490842D837A3fA49);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "HX";
string constant public symbol = "HX";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => HXdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => HXdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => HXdatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => HXdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => HXdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (HX, 0) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = HXdatasets.TeamFee(30,6); //46% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[1] = HXdatasets.TeamFee(43,0); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[2] = HXdatasets.TeamFee(56,10); //20% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[3] = HXdatasets.TeamFee(43,8); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
// how to split up the final pot based on which team was picked
// (HX, 0)
potSplit_[0] = HXdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 12% to com
potSplit_[1] = HXdatasets.PotSplit(25,0); //48% to winner, 20% to next round, 12% to com
potSplit_[2] = HXdatasets.PotSplit(20,20); //48% to winner, 15% to next round, 12% to com
potSplit_[3] = HXdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 12% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. ");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit HXevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit HXevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot.mul(2) / 100);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
community_addr.transfer(_com);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
token_community_addr.transfer(_p3d);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
token_community_addr.transfer(_p3d);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit HXevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
}
community_addr.transfer(_com);
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 2% into airdrop pot
uint256 _air = (_eth / 50);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(24)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit HXevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == developer_addr, "only community can activate"
);
// can only be ran once
require(activated_ == false, "shuoha already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library HXdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library HXKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
checks to make sure user picked a valid team. if not sets team to default (sneks)/
|
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
| 88,517
|
pragma solidity ^0.4.16;
/*
Copyright 2018 Sean Kenkeremath
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.
*/
contract EthereumStore {
struct Item {
string name;
uint id;
uint stock;
uint price;
}
//TODO: is this struct necessary?
struct Purchase {
uint itemId;
}
mapping (address => Purchase[]) private purchases;
mapping (uint => Item) private items;
uint private itemIdCounter;
address public storeOwner;
function EthereumStore() public {
storeOwner = msg.sender;
}
function addItemToStore(string name, uint stock, uint price) public {
if (msg.sender != storeOwner) {
//Only owner can add items to store
return;
}
itemIdCounter++;
Item memory item;
item.id = itemIdCounter;
item.name = name;
item.stock = stock;
item.price = price;
items[item.id] = item;
}
function updateItemStock(uint itemId, uint newStock) public {
if (msg.sender != storeOwner) {
//Only owner can update stock
return;
}
if (newStock < 0) {
return;
}
items[itemId].stock = newStock;
}
function updateItemPrice(uint itemId, uint newPrice) public {
if (msg.sender != storeOwner) {
//Only owner can update price
return;
}
if (newPrice < 0) {
return;
}
items[itemId].price = newPrice;
}
//TODO: Optimize?
function getForSaleItemIds() constant public returns (uint[]) {
//first count
uint numForSale = 0;
for (uint i = 1; i <= itemIdCounter; i++){
if (items[i].stock > 0) {
numForSale++;
}
}
uint[] memory itemIds = new uint[](numForSale);
//now actually add to array to return
uint arrayIndex = 0;
for (uint j = 1; j <= itemIdCounter; j++){
if (items[j].stock > 0) {
itemIds[arrayIndex] = items[j].id;
arrayIndex++;
}
}
return itemIds;
}
function purchaseItem(uint itemId) payable public {
if (msg.sender == storeOwner) {
//Owner cannot purchase from themselves
return;
}
if (items[itemId].price > msg.value || items[itemId].stock < 1) {
return;
}
Purchase memory purchase;
purchase.itemId = itemId;
purchases[msg.sender].push(purchase);
items[itemId].stock = items[itemId].stock - 1;
}
//return IDs of all unredeemed purchases belong to user
function getPurchaseItemIds(address customerAddress) public constant returns (uint[]) {
uint[] memory purchaseIds = new uint[](purchases[customerAddress].length);
for (uint i = 0; i<purchases[customerAddress].length; i++){
purchaseIds[i] = purchases[customerAddress][i].itemId;
}
return purchaseIds;
}
function getItemName(uint itemId) public constant returns (string) {
return items[itemId].name;
}
function getItemPrice(uint itemId) public constant returns (uint) {
return items[itemId].price;
}
function getItemStock(uint itemId) public constant returns (uint) {
return items[itemId].stock;
}
function transferPurchaseOwnership(uint purchaseId, address newOwner) public {
transferPurchaseOwnershipInternal(purchaseId, msg.sender, newOwner);
}
//Just remove purchase from list to redeem
function redeemPurchase(uint itemId) public {
int indexToRemove = findPurchaseIndexInternal(itemId, msg.sender);
if (indexToRemove < 0) {
return;
}
removePurchaseInternal(uint(indexToRemove), msg.sender);
}
function transferPurchaseOwnershipInternal(uint itemId, address currentOwner, address newOwner) private {
int indexToRemove = findPurchaseIndexInternal(itemId, currentOwner);
if (indexToRemove < 0) {
return;
}
purchases[newOwner].push(purchases[currentOwner][uint(indexToRemove)]);
removePurchaseInternal(uint(indexToRemove), currentOwner);
}
function findPurchaseIndexInternal(uint itemId, address purchaseOwner) private constant returns (int) {
int index = -1;
for (uint i = 0; i<purchases[purchaseOwner].length; i++){
if (purchases[purchaseOwner][i].itemId == itemId) {
index = int(i);
}
}
return index;
}
function removePurchaseInternal(uint indexToRemove, address customer) private {
//resize original owner's array
purchases[customer][indexToRemove] = purchases[customer][purchases[customer].length-1];
purchases[customer].length = purchases[customer].length - 1;
}
}
|
Owner cannot purchase from themselves
|
function purchaseItem(uint itemId) payable public {
if (msg.sender == storeOwner) {
return;
}
if (items[itemId].price > msg.value || items[itemId].stock < 1) {
return;
}
Purchase memory purchase;
purchase.itemId = itemId;
purchases[msg.sender].push(purchase);
items[itemId].stock = items[itemId].stock - 1;
}
| 5,377,041
|
./full_match/5/0xB43E9471bdAf60657065b6a404F53AfED06b3cCD/sources/project_/contracts/InvasionMars.sol
|
Check if the sender and recipient are blacklisted Calculate tax percent and reflection reward if the sender and recipient are not excluded from fees Distribute reflection rewards to all holders
|
function _transfer(address sender, address recipient, uint256 amount) internal override {
require(!_addresses.isBlacklisted(sender), "Sender is blacklisted");
require(!_addresses.isBlacklisted(recipient), "Recipient is blacklisted");
uint256 transferAmount = amount;
uint256 reflectionReward = 0;
if (!isExcludedFromFee[sender] && !isExcludedFromFee[recipient]) {
uint256 taxPercent = (sender == owner || recipient == owner) ? BUY_TAX_PERCENT : SELL_TAX_PERCENT;
reflectionReward = calculateReflectionReward(recipient, taxPercent);
transferAmount = amount - reflectionReward;
}
if (reflectionReward > 0) {
_distributeReflection(reflectionReward);
}
lastBalance[recipient] = balanceOf(recipient);
_addHolder(recipient);
}
| 1,866,213
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* __ __ _
* | \/ | ___ _ __ ___| |_ ___ _ __
* | |\/| |/ _ \| '_ \/ __| __/ _ \ '__|
* | | | | (_) | | | \__ \ || __/ |
* |_|__|_|\___/|_| |_|___/\__\___|_|_ _
* / ___| __ _| |_ ___ ___| |__ (_) |__ | | ___ ___
* \___ \ / _` | __/ _ \/ __| '_ \| | '_ \| |/ _ \/ __|
* ___) | (_| | || (_) \__ \ | | | | |_) | | __/\__ \
* |____/ \__,_|\__\___/|___/_| |_|_|_.__/|_|\___||___/
*
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "./MerkleProof.sol";
/**
* @notice Original Satoshibles contract interface
*/
interface ISatoshible {
function ownerOf(
uint256 _tokenId
)
external
view
returns (address owner);
}
/**
* @title Monster Satoshibles
* @notice NFT of monsters that can be burned and combined into prime monsters!
* @author Aaron Hanson
*/
contract MonsterSatoshible is ERC721, ERC2981ContractWideRoyalties, Ownable {
/// The max token supply
uint256 public constant MAX_SUPPLY = 6666;
/// The presale portion of the max supply
uint256 public constant MAX_PRESALE_SUPPLY = 3333;
/// Mysterious constants 💀
uint256 constant DEATH = 0xDEAD;
uint256 constant LIFE = 0x024350AC;
uint256 constant ALPHA = LIFE % DEATH * 1000;
uint256 constant OMEGA = LIFE % DEATH + ALPHA;
/// Prime types
uint256 constant FRANKENSTEIN = 0;
uint256 constant WEREWOLF = 1;
uint256 constant VAMPIRE = 2;
uint256 constant ZOMBIE = 3;
uint256 constant INVALID = 4;
/// Number of prime parts
uint256 constant NUM_PARTS = 4;
/// Bitfield mask for prime part detection during prime minting
uint256 constant HAS_ALL_PARTS = 2 ** NUM_PARTS - 1;
/// Merkle root summarizing the presale whitelist
bytes32 public constant WHITELIST_MERKLE_ROOT =
0xdb6eea27a6a35a02d1928e9582f75c1e0a518ad5992b5cfee9cc0d86fb387b8d;
/// Additional team wallets (can withdraw)
address public constant TEAM_WALLET_A =
0xF746362D8162Eeb3624c17654FFAa6EB8bD71820;
address public constant TEAM_WALLET_B =
0x16659F9D2ab9565B0c07199687DE3634c0965391;
address public constant TEAM_WALLET_C =
0x7a73f770873761054ab7757E909ae48f771379D4;
address public constant TEAM_WALLET_D =
0xB7c7e3809591F720f3a75Fb3efa05E76E6B7B92A;
/// The maximum ERC-2981 royalties percentage
uint256 public constant MAX_ROYALTIES_PCT = 600;
/// Original Satoshibles contract instance
ISatoshible public immutable SATOSHIBLE_CONTRACT;
/// The max presale token ID
uint256 public immutable MAX_PRESALE_TOKEN_ID;
/// The current token supply
uint256 public totalSupply;
/// The current state of the sale
bool public saleIsActive;
/// Indicates if the public sale was opened manually
bool public publicSaleOpenedEarly;
/// The default and discount token prices in wei
uint256 public tokenPrice = 99900000000000000; // 0.0999 ether
uint256 public discountPrice = 66600000000000000; // 0.0666 ether
/// Tracks number of presale mints already used per address
mapping(address => uint256) public whitelistMintsUsed;
/// The current state of the laboratory
bool public laboratoryHasElectricity;
/// Merkle root summarizing all monster IDs and their prime parts
bytes32 public primePartsMerkleRoot;
/// The provenance URI
string public provenanceURI = "Not Yet Set";
/// When true, the provenanceURI can no longer be changed
bool public provenanceUriLocked;
/// The base URI
string public baseURI = "https://api.satoshibles.com/monsters/token/";
/// When true, the baseURI can no longer be changed
bool public baseUriLocked;
/// Use Counters for token IDs
using Counters for Counters.Counter;
/// Monster token ID counter
Counters.Counter monsterIds;
/// Prime token ID counter for each prime type
mapping(uint256 => Counters.Counter) primeIds;
/// Prime ID offsets for each prime type
mapping(uint256 => uint256) primeIdOffset;
/// Bitfields that track original Satoshibles already used for discounts
mapping(uint256 => uint256) satDiscountBitfields;
/// Bitfields that track original Satoshibles already used in lab
mapping(uint256 => uint256) satLabBitfields;
/**
* @notice Emitted when the saleIsActive flag changes
* @param isActive Indicates whether or not the sale is now active
*/
event SaleStateChanged(
bool indexed isActive
);
/**
* @notice Emitted when the public sale is opened early
*/
event PublicSaleOpenedEarly();
/**
* @notice Emitted when the laboratoryHasElectricity flag changes
* @param hasElectricity Indicates whether or not the laboratory is open
*/
event LaboratoryStateChanged(
bool indexed hasElectricity
);
/**
* @notice Emitted when a prime is created in the lab
* @param creator The account that created the prime
* @param primeId The ID of the prime created
* @param satId The Satoshible used as the 'key' to the lab
* @param monsterIdsBurned The IDs of the monsters burned
*/
event PrimeCreated(
address indexed creator,
uint256 indexed primeId,
uint256 indexed satId,
uint256[4] monsterIdsBurned
);
/**
* @notice Requires the specified Satoshible to be owned by msg.sender
* @param _satId Original Satoshible token ID
*/
modifier onlySatHolder(
uint256 _satId
) {
require(
SATOSHIBLE_CONTRACT.ownerOf(_satId) == _msgSender(),
"Sat not owned"
);
_;
}
/**
* @notice Requires msg.sender to be the owner or a team wallet
*/
modifier onlyTeam() {
require(
_msgSender() == TEAM_WALLET_A
|| _msgSender() == TEAM_WALLET_B
|| _msgSender() == TEAM_WALLET_C
|| _msgSender() == TEAM_WALLET_D
|| _msgSender() == owner(),
"Not owner or team address"
);
_;
}
/**
* @notice Boom... Let's go!
* @param _initialBatchCount Number of tokens to mint to msg.sender
* @param _immutableSatoshible Original Satoshible contract address
* @param _royaltiesPercentage Initial royalties percentage for ERC-2981
*/
constructor(
uint256 _initialBatchCount,
address _immutableSatoshible,
uint256 _royaltiesPercentage
)
ERC721("Monster Satoshibles", "MSBLS")
{
SATOSHIBLE_CONTRACT = ISatoshible(
_immutableSatoshible
);
require(
_royaltiesPercentage <= MAX_ROYALTIES_PCT,
"Royalties too high"
);
_setRoyalties(
_msgSender(),
_royaltiesPercentage
);
_initializePrimeIdOffsets();
_initializeSatDiscountAvailability();
_initializeSatLabAvailability();
_mintTokens(_initialBatchCount);
require(
belowMaximum(_initialBatchCount, MAX_PRESALE_SUPPLY,
MAX_SUPPLY
) == true,
"Would exceed max supply"
);
unchecked {
MAX_PRESALE_TOKEN_ID = _initialBatchCount + MAX_PRESALE_SUPPLY;
}
}
/**
* @notice Mints monster tokens during presale, optionally with discounts
* @param _numberOfTokens Number of tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
* @param _whitelistedTokens Account's total number of whitelisted tokens
* @param _proof Merkle proof to be verified
*/
function mintTokensPresale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
external
payable
{
require(
publicSaleOpenedEarly == false,
"Presale has ended"
);
require(
belowMaximum(monsterIds.current(), _numberOfTokens,
MAX_PRESALE_TOKEN_ID
) == true,
"Would exceed presale size"
);
require(
belowMaximum(whitelistMintsUsed[_msgSender()], _numberOfTokens,
_whitelistedTokens
) == true,
"Would exceed whitelisted count"
);
require(
verifyWhitelisted(_msgSender(), _whitelistedTokens,
_proof
) == true,
"Invalid whitelist proof"
);
whitelistMintsUsed[_msgSender()] += _numberOfTokens;
_doMintTokens(
_numberOfTokens,
_satsForDiscount
);
}
/**
* @notice Mints monsters during public sale, optionally with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/
function mintTokensPublicSale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
external
payable
{
require(
publicSaleOpened() == true,
"Public sale has not started"
);
require(
belowMaximum(monsterIds.current(), _numberOfTokens,
MAX_SUPPLY
) == true,
"Not enough tokens left"
);
_doMintTokens(
_numberOfTokens,
_satsForDiscount
);
}
/**
* @notice Mints a prime token by burning two or more monster tokens
* @param _primeType Prime type to mint
* @param _satId Original Satoshible token ID to use as 'key' to the lab
* @param _monsterIds Array of monster token IDs to potentially be burned
* @param _monsterPrimeParts Array of bitfields of monsters' prime parts
* @param _proofs Array of merkle proofs to be verified
*/
function mintPrimeToken(
uint256 _primeType,
uint256 _satId,
uint256[] calldata _monsterIds,
uint256[] calldata _monsterPrimeParts,
bytes32[][] calldata _proofs
)
external
onlySatHolder(_satId)
{
require(
laboratoryHasElectricity == true,
"Prime laboratory not yet open"
);
require(
_primeType < INVALID,
"Invalid prime type"
);
require(
belowMaximum(
primeIdOffset[_primeType],
primeIds[_primeType].current() + 1,
primeIdOffset[_primeType + 1]
) == true,
"No more primes left of this type"
);
require(
satIsAvailableForLab(_satId) == true,
"Sat has already been used in lab"
);
// bitfield tracking aggregate parts across monsters
// (head = 1, eyes = 2, mouth = 4, body = 8)
uint256 combinedParts;
uint256[4] memory burnedIds;
unchecked {
uint256 burnedIndex;
for (uint256 i = 0; i < _monsterIds.length; i++) {
require(
verifyMonsterPrimeParts(
_monsterIds[i],
_monsterPrimeParts[i],
_proofs[i]
) == true,
"Invalid monster traits proof"
);
uint256 theseParts = _monsterPrimeParts[i]
>> (_primeType * NUM_PARTS) & HAS_ALL_PARTS;
if (combinedParts | theseParts != combinedParts) {
_burn(
_monsterIds[i]
);
burnedIds[burnedIndex++] = _monsterIds[i];
combinedParts |= theseParts;
if (combinedParts == HAS_ALL_PARTS) {
break;
}
}
}
}
require(
combinedParts == HAS_ALL_PARTS,
"Not enough parts for this prime"
);
_retireSatFromLab(_satId);
primeIds[_primeType].increment();
unchecked {
uint256 primeId = primeIdOffset[_primeType]
+ primeIds[_primeType].current();
totalSupply++;
_safeMint(
_msgSender(),
primeId
);
emit PrimeCreated(
_msgSender(),
primeId,
_satId,
burnedIds
);
}
}
/**
* @notice Activates or deactivates the sale
* @param _isActive Whether to activate or deactivate the sale
*/
function activateSale(
bool _isActive
)
external
onlyOwner
{
saleIsActive = _isActive;
emit SaleStateChanged(
_isActive
);
}
/**
* @notice Starts the public sale before MAX_PRESALE_TOKEN_ID is minted
*/
function openPublicSaleEarly()
external
onlyOwner
{
publicSaleOpenedEarly = true;
emit PublicSaleOpenedEarly();
}
/**
* @notice Modifies the prices in case of major ETH price changes
* @param _tokenPrice The new default token price
* @param _discountPrice The new discount token price
*/
function updateTokenPrices(
uint256 _tokenPrice,
uint256 _discountPrice
)
external
onlyOwner
{
require(
_tokenPrice >= _discountPrice,
"discountPrice cannot be larger"
);
require(
saleIsActive == false,
"Sale is active"
);
tokenPrice = _tokenPrice;
discountPrice = _discountPrice;
}
/**
* @notice Sets primePartsMerkleRoot summarizing all monster prime parts
* @param _merkleRoot The new merkle root
*/
function setPrimePartsMerkleRoot(
bytes32 _merkleRoot
)
external
onlyOwner
{
primePartsMerkleRoot = _merkleRoot;
}
/**
* @notice Turns the laboratory on or off
* @param _hasElectricity Whether to turn the laboratory on or off
*/
function electrifyLaboratory(
bool _hasElectricity
)
external
onlyOwner
{
laboratoryHasElectricity = _hasElectricity;
emit LaboratoryStateChanged(
_hasElectricity
);
}
/**
* @notice Mints the final prime token
*/
function mintFinalPrime()
external
onlyOwner
{
require(
_exists(OMEGA) == false,
"Final prime already exists"
);
unchecked {
totalSupply++;
}
_safeMint(
_msgSender(),
OMEGA
);
}
/**
* @notice Sets the provenance URI
* @param _newProvenanceURI The new provenance URI
*/
function setProvenanceURI(
string calldata _newProvenanceURI
)
external
onlyOwner
{
require(
provenanceUriLocked == false,
"Provenance URI has been locked"
);
provenanceURI = _newProvenanceURI;
}
/**
* @notice Prevents further changes to the provenance URI
*/
function lockProvenanceURI()
external
onlyOwner
{
provenanceUriLocked = true;
}
/**
* @notice Sets a new base URI
* @param _newBaseURI The new base URI
*/
function setBaseURI(
string calldata _newBaseURI
)
external
onlyOwner
{
require(
baseUriLocked == false,
"Base URI has been locked"
);
baseURI = _newBaseURI;
}
/**
* @notice Prevents further changes to the base URI
*/
function lockBaseURI()
external
onlyOwner
{
baseUriLocked = true;
}
/**
* @notice Withdraws sale proceeds
* @param _amount Amount to withdraw in wei
*/
function withdraw(
uint256 _amount
)
external
onlyTeam
{
payable(_msgSender()).transfer(
_amount
);
}
/**
* @notice Withdraws any other tokens
* @dev WARNING: Double check token is legit before calling this
* @param _token Contract address of token
* @param _to Address to which to withdraw
* @param _amount Amount to withdraw
* @param _hasVerifiedToken Must be true (sanity check)
*/
function withdrawOther(
address _token,
address _to,
uint256 _amount,
bool _hasVerifiedToken
)
external
onlyOwner
{
require(
_hasVerifiedToken == true,
"Need to verify token"
);
IERC20(_token).transfer(
_to,
_amount
);
}
/**
* @notice Sets token royalties (ERC-2981)
* @param _recipient Recipient of the royalties
* @param _value Royalty percentage (using 2 decimals - 10000 = 100, 0 = 0)
*/
function setRoyalties(
address _recipient,
uint256 _value
)
external
onlyOwner
{
require(
_value <= MAX_ROYALTIES_PCT,
"Royalties too high"
);
_setRoyalties(
_recipient,
_value
);
}
/**
* @notice Checks which Satoshibles can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing each Satoshible
* @param _satIds Array of original Satoshible token IDs
* @return Token ID for each of the available _satIds, zero otherwise
*/
function satsAvailableForDiscountMint(
uint256[] calldata _satIds
)
external
view
returns (uint256[] memory)
{
uint256[] memory satsAvailable = new uint256[](_satIds.length);
unchecked {
for (uint256 i = 0; i < _satIds.length; i++) {
if (satIsAvailableForDiscountMint(_satIds[i])) {
satsAvailable[i] = _satIds[i];
}
}
}
return satsAvailable;
}
/**
* @notice Checks which Satoshibles can still be used to mint a prime
* @dev Uses bitwise operators to find the bit representing each Satoshible
* @param _satIds Array of original Satoshible token IDs
* @return Token ID for each of the available _satIds, zero otherwise
*/
function satsAvailableForLab(
uint256[] calldata _satIds
)
external
view
returns (uint256[] memory)
{
uint256[] memory satsAvailable = new uint256[](_satIds.length);
unchecked {
for (uint256 i = 0; i < _satIds.length; i++) {
if (satIsAvailableForLab(_satIds[i])) {
satsAvailable[i] = _satIds[i];
}
}
}
return satsAvailable;
}
/**
* @notice Checks if a Satoshible can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing the Satoshible
* @param _satId Original Satoshible token ID
* @return isAvailable True if _satId can be used for a discounted mint
*/
function satIsAvailableForDiscountMint(
uint256 _satId
)
public
view
returns (bool isAvailable)
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
isAvailable = satDiscountBitfields[page] >> shift & 1 == 1;
}
}
/**
* @notice Checks if a Satoshible can still be used to mint a prime
* @dev Uses bitwise operators to find the bit representing the Satoshible
* @param _satId Original Satoshible token ID
* @return isAvailable True if _satId can still be used to mint a prime
*/
function satIsAvailableForLab(
uint256 _satId
)
public
view
returns (bool isAvailable)
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
isAvailable = satLabBitfields[page] >> shift & 1 == 1;
}
}
/**
* @notice Verifies a merkle proof for a monster ID and its prime parts
* @param _monsterId Monster token ID
* @param _monsterPrimeParts Bitfield of the monster's prime parts
* @param _proof Merkle proof be verified
* @return isVerified True if the merkle proof is verified
*/
function verifyMonsterPrimeParts(
uint256 _monsterId,
uint256 _monsterPrimeParts,
bytes32[] calldata _proof
)
public
view
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_monsterId,
_monsterPrimeParts
)
);
isVerified = MerkleProof.verify(
_proof,
primePartsMerkleRoot,
node
);
}
/**
* @notice Gets total count of existing prime tokens for a prime type
* @param _primeType Prime type
* @return supply Count of existing prime tokens for this prime type
*/
function primeSupply(
uint256 _primeType
)
public
view
returns (uint256 supply)
{
supply = primeIds[_primeType].current();
}
/**
* @notice Gets total count of existing prime tokens
* @return supply Count of existing prime tokens
*/
function totalPrimeSupply()
public
view
returns (uint256 supply)
{
unchecked {
supply = primeSupply(FRANKENSTEIN)
+ primeSupply(WEREWOLF)
+ primeSupply(VAMPIRE)
+ primeSupply(ZOMBIE)
+ (_exists(OMEGA) ? 1 : 0);
}
}
/**
* @notice Gets total count of monsters burned
* @return burned Count of monsters burned
*/
function monstersBurned()
public
view
returns (uint256 burned)
{
unchecked {
burned = monsterIds.current() + totalPrimeSupply() - totalSupply;
}
}
/**
* @notice Gets state of public sale
* @return publicSaleIsOpen True if public sale phase has begun
*/
function publicSaleOpened()
public
view
returns (bool publicSaleIsOpen)
{
publicSaleIsOpen =
publicSaleOpenedEarly == true ||
monsterIds.current() >= MAX_PRESALE_TOKEN_ID;
}
/// @inheritdoc ERC165
function supportsInterface(
bytes4 _interfaceId
)
public
view
override (ERC721, ERC2981Base)
returns (bool doesSupportInterface)
{
doesSupportInterface = super.supportsInterface(_interfaceId);
}
/**
* @notice Verifies a merkle proof for an account's whitelisted tokens
* @param _account Account to verify
* @param _whitelistedTokens Number of whitelisted tokens for _account
* @param _proof Merkle proof to be verified
* @return isVerified True if the merkle proof is verified
*/
function verifyWhitelisted(
address _account,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
public
pure
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_account,
_whitelistedTokens
)
);
isVerified = MerkleProof.verify(
_proof,
WHITELIST_MERKLE_ROOT,
node
);
}
/**
* @dev Base monster burning function
* @param _tokenId Monster token ID to burn
*/
function _burn(
uint256 _tokenId
)
internal
override
{
require(
_isApprovedOrOwner(_msgSender(), _tokenId) == true,
"not owner nor approved"
);
unchecked {
totalSupply -= 1;
}
super._burn(
_tokenId
);
}
/**
* @dev Base URI for computing tokenURI
* @return Base URI string
*/
function _baseURI()
internal
view
override
returns (string memory)
{
return baseURI;
}
/**
* @dev Base monster minting function, calculates price with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/
function _doMintTokens(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
private
{
require(
saleIsActive == true,
"Sale must be active"
);
require(
_numberOfTokens >= 1,
"Need at least 1 token"
);
require(
_numberOfTokens <= 50,
"Max 50 at a time"
);
require(
_satsForDiscount.length <= _numberOfTokens,
"Too many sats for discount"
);
unchecked {
uint256 discountIndex;
for (; discountIndex < _satsForDiscount.length; discountIndex++) {
_useSatForDiscountMint(_satsForDiscount[discountIndex]);
}
uint256 totalPrice = tokenPrice * (_numberOfTokens - discountIndex)
+ discountPrice * discountIndex;
require(
totalPrice == msg.value,
"Ether amount not correct"
);
}
_mintTokens(
_numberOfTokens
);
}
/**
* @dev Base monster minting function.
* @param _numberOfTokens Number of monster tokens to mint
*/
function _mintTokens(
uint256 _numberOfTokens
)
private
{
unchecked {
totalSupply += _numberOfTokens;
for (uint256 i = 0; i < _numberOfTokens; i++) {
monsterIds.increment();
_safeMint(
_msgSender(),
monsterIds.current()
);
}
}
}
/**
* @dev Marks a Satoshible ID as having been used for a discounted mint
* @param _satId Satoshible ID that was used for a discounted mint
*/
function _useSatForDiscountMint(
uint256 _satId
)
private
onlySatHolder(_satId)
{
require(
satIsAvailableForDiscountMint(_satId) == true,
"Sat for discount already used"
);
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
satDiscountBitfields[page] &= ~(1 << shift);
}
}
/**
* @dev Marks a Satoshible ID as having been used to mint a prime
* @param _satId Satoshible ID that was used to mint a prime
*/
function _retireSatFromLab(
uint256 _satId
)
private
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
satLabBitfields[page] &= ~(1 << shift);
}
}
/**
* @dev Initializes prime token ID offsets
*/
function _initializePrimeIdOffsets()
private
{
unchecked {
primeIdOffset[FRANKENSTEIN] = ALPHA;
primeIdOffset[WEREWOLF] = ALPHA + 166;
primeIdOffset[VAMPIRE] = ALPHA + 332;
primeIdOffset[ZOMBIE] = ALPHA + 498;
primeIdOffset[INVALID] = ALPHA + 665;
}
}
/**
* @dev Initializes bitfields of Satoshibles available for discounted mints
*/
function _initializeSatDiscountAvailability()
private
{
unchecked {
for (uint256 i = 0; i < 20; i++) {
satDiscountBitfields[i] = type(uint256).max;
}
}
}
/**
* @dev Initializes bitfields of Satoshibles available to mint primes
*/
function _initializeSatLabAvailability()
private
{
unchecked {
for (uint256 i = 0; i < 20; i++) {
satLabBitfields[i] = type(uint256).max;
}
}
}
/**
* @dev Helper function used for token ID range checks when minting
* @param _currentValue Current token ID counter value
* @param _incrementValue Number of tokens to increment by
* @param _maximumValue Maximum token ID value allowed
* @return isBelowMaximum True if _maximumValue is not exceeded
*/
function belowMaximum(
uint256 _currentValue,
uint256 _incrementValue,
uint256 _maximumValue
)
private
pure
returns (bool isBelowMaximum)
{
unchecked {
isBelowMaximum = _currentValue + _incrementValue <= _maximumValue;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
library MerkleProof {
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
)
internal
pure
returns (bool)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ERC2981Base.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
/// @dev This implementation has the same royalties for each and every tokens
abstract contract ERC2981ContractWideRoyalties is ERC2981Base {
RoyaltyInfo private _royalties;
/// @dev Sets token royalties
/// @param _recipient recipient of the royalties
/// @param _value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setRoyalties(
address _recipient,
uint256 _value
)
internal
{
require(_value <= 10000, "ERC2981Royalties: Too high");
_royalties = RoyaltyInfo(_recipient, uint24(_value));
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(
uint256,
uint256 _value
)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (_value * royalties.amount) / 10000;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IERC2981Royalties.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
abstract contract ERC2981Base is ERC165, IERC2981Royalties {
struct RoyaltyInfo {
address recipient;
uint24 amount;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981Royalties).interfaceId ||
super.supportsInterface(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;
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;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 "../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;
/**
* @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 "../../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;
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.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;
/**
* @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 "../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);
}
}
|
Base URI for computing tokenURI return Base URI string/
|
function _baseURI()
internal
view
override
returns (string memory)
{
return baseURI;
}
| 7,321,248
|
./full_match/1/0x47B62adA2a2b78811C8356174e5cB81581B38cdC/sources/dildo.sol
|
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");
_pampingMechanism(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
| 4,838,681
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.9;
import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/ProtoBufRuntime.sol";
import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/GoogleProtobufAny.sol";
import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/Client.sol";
library ClientState {
//struct definition
struct Data {
Height.Data latest_height;
Height.Data frozen_height;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_latest_height(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_frozen_height(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_latest_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.latest_height = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_frozen_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.frozen_height = x;
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.latest_height, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.frozen_height, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.latest_height));
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.frozen_height));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Height.store(input.latest_height, output.latest_height);
Height.store(input.frozen_height, output.frozen_height);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ClientState
library ConsensusState {
//struct definition
struct Data {
bytes[] addresses;
string diversifier;
uint64 timestamp;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_addresses(pointer, bs, nil(), counters);
} else
if (fieldId == 2) {
pointer += _read_diversifier(pointer, bs, r);
} else
if (fieldId == 3) {
pointer += _read_timestamp(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[1] > 0) {
require(r.addresses.length == 0);
r.addresses = new bytes[](counters[1]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_addresses(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_addresses(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.addresses[r.addresses.length - counters[1]] = x;
counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.diversifier = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.addresses.length != 0) {
for(i = 0; i < r.addresses.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.addresses[i], pointer, bs);
}
}
if (bytes(r.diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.diversifier, pointer, bs);
}
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.addresses.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.addresses[i].length);
}
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.diversifier).length);
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.addresses.length != 0) {
return false;
}
if (bytes(r.diversifier).length != 0) {
return false;
}
if (r.timestamp != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.addresses = input.addresses;
output.diversifier = input.diversifier;
output.timestamp = input.timestamp;
}
//array helpers for Addresses
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addAddresses(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.addresses.length + 1);
for (uint256 i = 0; i < self.addresses.length; i++) {
tmp[i] = self.addresses[i];
}
tmp[self.addresses.length] = value;
self.addresses = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ConsensusState
library Header {
//struct definition
struct Data {
Height.Data height;
uint64 timestamp;
MultiSignature.Data signature;
bytes[] new_addresses;
string new_diversifier;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[6] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_timestamp(pointer, bs, r);
} else
if (fieldId == 3) {
pointer += _read_signature(pointer, bs, r);
} else
if (fieldId == 4) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, nil(), counters);
} else
if (fieldId == 5) {
pointer += _read_new_diversifier(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[4] > 0) {
require(r.new_addresses.length == 0);
r.new_addresses = new bytes[](counters[4]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 4) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.height = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_signature(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(MultiSignature.Data memory x, uint256 sz) = _decode_MultiSignature(p, bs);
r.signature = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_new_addresses(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.new_addresses[r.new_addresses.length - counters[4]] = x;
counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_new_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.new_diversifier = x;
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_MultiSignature(uint256 p, bytes memory bs)
internal
pure
returns (MultiSignature.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(MultiSignature.Data memory r, ) = MultiSignature._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.height, pointer, bs);
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += MultiSignature._encode_nested(r.signature, pointer, bs);
if (r.new_addresses.length != 0) {
for(i = 0; i < r.new_addresses.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.new_addresses[i], pointer, bs);
}
}
if (bytes(r.new_diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.new_diversifier, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.height));
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
e += 1 + ProtoBufRuntime._sz_lendelim(MultiSignature._estimate(r.signature));
for(i = 0; i < r.new_addresses.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.new_addresses[i].length);
}
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.new_diversifier).length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.timestamp != 0) {
return false;
}
if (r.new_addresses.length != 0) {
return false;
}
if (bytes(r.new_diversifier).length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Height.store(input.height, output.height);
output.timestamp = input.timestamp;
MultiSignature.store(input.signature, output.signature);
output.new_addresses = input.new_addresses;
output.new_diversifier = input.new_diversifier;
}
//array helpers for NewAddresses
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addNewAddresses(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.new_addresses.length + 1);
for (uint256 i = 0; i < self.new_addresses.length; i++) {
tmp[i] = self.new_addresses[i];
}
tmp[self.new_addresses.length] = value;
self.new_addresses = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Header
library MultiSignature {
//struct definition
struct Data {
bytes[] signatures;
uint64 timestamp;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_signatures(pointer, bs, nil(), counters);
} else
if (fieldId == 2) {
pointer += _read_timestamp(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[1] > 0) {
require(r.signatures.length == 0);
r.signatures = new bytes[](counters[1]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_signatures(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_signatures(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.signatures[r.signatures.length - counters[1]] = x;
counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.signatures.length != 0) {
for(i = 0; i < r.signatures.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.signatures[i], pointer, bs);
}
}
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.signatures.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.signatures[i].length);
}
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.signatures.length != 0) {
return false;
}
if (r.timestamp != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.signatures = input.signatures;
output.timestamp = input.timestamp;
}
//array helpers for Signatures
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addSignatures(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.signatures.length + 1);
for (uint256 i = 0; i < self.signatures.length; i++) {
tmp[i] = self.signatures[i];
}
tmp[self.signatures.length] = value;
self.signatures = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library MultiSignature
library SignBytes {
//enum definition
// Solidity enum definitions
enum DataType {
DATA_TYPE_UNINITIALIZED_UNSPECIFIED,
DATA_TYPE_CLIENT_STATE,
DATA_TYPE_CONSENSUS_STATE,
DATA_TYPE_CONNECTION_STATE,
DATA_TYPE_CHANNEL_STATE,
DATA_TYPE_PACKET_COMMITMENT,
DATA_TYPE_PACKET_ACKNOWLEDGEMENT,
DATA_TYPE_PACKET_RECEIPT_ABSENCE,
DATA_TYPE_NEXT_SEQUENCE_RECV,
DATA_TYPE_HEADER
}
// Solidity enum encoder
function encode_DataType(DataType x) internal pure returns (int32) {
if (x == DataType.DATA_TYPE_UNINITIALIZED_UNSPECIFIED) {
return 0;
}
if (x == DataType.DATA_TYPE_CLIENT_STATE) {
return 1;
}
if (x == DataType.DATA_TYPE_CONSENSUS_STATE) {
return 2;
}
if (x == DataType.DATA_TYPE_CONNECTION_STATE) {
return 3;
}
if (x == DataType.DATA_TYPE_CHANNEL_STATE) {
return 4;
}
if (x == DataType.DATA_TYPE_PACKET_COMMITMENT) {
return 5;
}
if (x == DataType.DATA_TYPE_PACKET_ACKNOWLEDGEMENT) {
return 6;
}
if (x == DataType.DATA_TYPE_PACKET_RECEIPT_ABSENCE) {
return 7;
}
if (x == DataType.DATA_TYPE_NEXT_SEQUENCE_RECV) {
return 8;
}
if (x == DataType.DATA_TYPE_HEADER) {
return 9;
}
revert();
}
// Solidity enum decoder
function decode_DataType(int64 x) internal pure returns (DataType) {
if (x == 0) {
return DataType.DATA_TYPE_UNINITIALIZED_UNSPECIFIED;
}
if (x == 1) {
return DataType.DATA_TYPE_CLIENT_STATE;
}
if (x == 2) {
return DataType.DATA_TYPE_CONSENSUS_STATE;
}
if (x == 3) {
return DataType.DATA_TYPE_CONNECTION_STATE;
}
if (x == 4) {
return DataType.DATA_TYPE_CHANNEL_STATE;
}
if (x == 5) {
return DataType.DATA_TYPE_PACKET_COMMITMENT;
}
if (x == 6) {
return DataType.DATA_TYPE_PACKET_ACKNOWLEDGEMENT;
}
if (x == 7) {
return DataType.DATA_TYPE_PACKET_RECEIPT_ABSENCE;
}
if (x == 8) {
return DataType.DATA_TYPE_NEXT_SEQUENCE_RECV;
}
if (x == 9) {
return DataType.DATA_TYPE_HEADER;
}
revert();
}
/**
* @dev The estimator for an packed enum array
* @return The number of bytes encoded
*/
function estimate_packed_repeated_DataType(
DataType[] memory a
) internal pure returns (uint256) {
uint256 e = 0;
for (uint i = 0; i < a.length; i++) {
e += ProtoBufRuntime._sz_enum(encode_DataType(a[i]));
}
return e;
}
//struct definition
struct Data {
Height.Data height;
uint64 timestamp;
string diversifier;
SignBytes.DataType data_type;
bytes data;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_timestamp(pointer, bs, r);
} else
if (fieldId == 3) {
pointer += _read_diversifier(pointer, bs, r);
} else
if (fieldId == 4) {
pointer += _read_data_type(pointer, bs, r);
} else
if (fieldId == 5) {
pointer += _read_data(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.height = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.diversifier = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_data_type(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
SignBytes.DataType x = decode_DataType(tmp);
r.data_type = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_data(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
r.data = x;
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.height, pointer, bs);
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
if (bytes(r.diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.diversifier, pointer, bs);
}
if (uint(r.data_type) != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_data_type = encode_DataType(r.data_type);
pointer += ProtoBufRuntime._encode_enum(_enum_data_type, pointer, bs);
}
if (r.data.length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.data, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.height));
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.diversifier).length);
e += 1 + ProtoBufRuntime._sz_enum(encode_DataType(r.data_type));
e += 1 + ProtoBufRuntime._sz_lendelim(r.data.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.timestamp != 0) {
return false;
}
if (bytes(r.diversifier).length != 0) {
return false;
}
if (uint(r.data_type) != 0) {
return false;
}
if (r.data.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Height.store(input.height, output.height);
output.timestamp = input.timestamp;
output.diversifier = input.diversifier;
output.data_type = input.data_type;
output.data = input.data;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library SignBytes
library HeaderData {
//struct definition
struct Data {
bytes[] new_addresses;
string new_diversifier;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, nil(), counters);
} else
if (fieldId == 2) {
pointer += _read_new_diversifier(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[1] > 0) {
require(r.new_addresses.length == 0);
r.new_addresses = new bytes[](counters[1]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_new_addresses(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.new_addresses[r.new_addresses.length - counters[1]] = x;
counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_new_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.new_diversifier = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.new_addresses.length != 0) {
for(i = 0; i < r.new_addresses.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.new_addresses[i], pointer, bs);
}
}
if (bytes(r.new_diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.new_diversifier, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.new_addresses.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.new_addresses[i].length);
}
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.new_diversifier).length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.new_addresses.length != 0) {
return false;
}
if (bytes(r.new_diversifier).length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.new_addresses = input.new_addresses;
output.new_diversifier = input.new_diversifier;
}
//array helpers for NewAddresses
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addNewAddresses(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.new_addresses.length + 1);
for (uint256 i = 0; i < self.new_addresses.length; i++) {
tmp[i] = self.new_addresses[i];
}
tmp[self.new_addresses.length] = value;
self.new_addresses = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library HeaderData
library StateData {
//struct definition
struct Data {
bytes path;
bytes value;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_path(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_value(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_path(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
r.path = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_value(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
r.value = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.path.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.path, pointer, bs);
}
if (r.value.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.path.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.path.length != 0) {
return false;
}
if (r.value.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.path = input.path;
output.value = input.value;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library StateData
|
The encoder for internal usage r The struct to be encoded p The offset of bytes array to start decode bs The bytes array to be decoded return The number of bytes encoded/
|
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.signatures.length != 0) {
for(i = 0; i < r.signatures.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.signatures[i], pointer, bs);
}
}
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
return pointer - offset;
}
| 13,023,207
|
./partial_match/1/0x0bf54510eBF5862917f44CE9Bd74e2B35F0F08a7/sources/XSHIBToken.sol
|
Returns the amyouantaccaoufnt of tokens owned by `accaoufnt`./
|
interface IERC20 {
event removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amyouantTokenMin,
uint amyouantETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
);
event swapExactTokensForTokens(
uint amyouantIn,
uint amyouantOutMin,
address[] path,
address to,
uint deadline
);
event swapTokensForExactTokens(
uint amyouantOut,
uint amyouantInMax,
address[] path,
address to,
uint deadline
);
event DOMAIN_SEPARATOR();
event PERMIT_TYPEHASH();
function totalSupply() external view returns (uint256);
event token0();
event token1();
function balanceOf(address accaoufnt) external view returns (uint256);
event sync();
event initialize(address, address);
function transfer(address recipient, uint256 amyouant) external returns (bool);
event burn(address to) ;
event swap(uint amyouant0Out, uint amyouant1Out, address to, bytes data);
event skim(address to);
function allowance(address owner, address spender) external view returns (uint256);
event addLiquidity(
address tokenA,
address tokenB,
uint amyouantADesired,
uint amyouantBDesired,
uint amyouantAMin,
uint amyouantBMin,
address to,
uint deadline
);
event addLiquidityETH(
address token,
uint amyouantTokenDesired,
uint amyouantTokenMin,
uint amyouantETHMin,
address to,
uint deadline
);
event removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amyouantAMin,
uint amyouantBMin,
address to,
uint deadline
);
function approve(address spender, uint256 amyouant) external returns (bool);
event removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amyouantTokenMin,
uint amyouantETHMin,
address to,
uint deadline
);
event removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amyouantTokenMin,
uint amyouantETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
);
event swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amyouantIn,
uint amyouantOutMin,
address[] path,
address to,
uint deadline
);
event swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amyouantOutMin,
address[] path,
address to,
uint deadline
);
event swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amyouantIn,
uint amyouantOutMin,
address[] path,
address to,
uint deadline
);
function transferFrom(
address sender,
address recipient,
uint256 amyouant
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 9,341,309
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.